问题描述
我有一个应用程序,用户可以在其中通过单击位置 (x,y) 来动态添加形状,例如圆形(为简单起见)。我一直在保留一个圆的 ArrayList,因此它们通过paintComponent()方法重新添加到JPanel,但是我怀疑这可能是多余的,因为有一个幕后数组被保留,可以通过内置 getComponents() 方法。我对吗?我的代码的关键部分如下:
public class DrawingPanel extends JPanel implements Constants {
Point point;
figure figure;
public DrawingPanel() {
point = new Point(0,0);
figure = new Circle(point,defaultSize);
setLayout(null);
setBackground(Color.white);
setPreferredSize(new Dimension(450,450));
addMouseListener(new ActionHandler());
}
public void paintComponent(Graphics page) {
super.paintComponent(page);
add(figure);
}
private class ActionHandler extends MouseAdapter {
@Override
public void mousepressed(MouseEvent e) {
super.mousepressed(e);
Point point = e.getPoint();
System.out.println("Mouse pressed at (" + e.getX() + "," + e.getY() + ")");
String figureState = itemHandler.getfigureState();
String figureActionState = itemHandler.getfigureActionState();
if (figureActionState.equals("None")) {
switch (figureState) {
case "Circle" -> {
figure = new Circle(point,defaultSize);
figure.setBounds((int) point.getX(),(int) point.getY(),50,50);
figure.addMouseListener(new ActionHandler());
}
case "Square" -> {
figure = new Rect(point,50);
figure.addMouseListener(new ActionHandler());
}
case "Cross" -> {
figure = new Cross(point,50);
figure.addMouseListener(new ActionHandler());
}
}
}
repaint();
}
}
}
public class figure extends JComponent {
Point position;
Dimension size;
public figure(Point position,Dimension size) {
this.position = position;
this.size = size;
}
public void paintComponent(Graphics page) {
super.paintComponent(page);
}
}
public interface Constants {
ItemHandler itemHandler = new ItemHandler();
Dimension defaultSize = new Dimension(50,50);
}
解决方法
您有整体设计问题:
-
绘画方法不应改变类的状态。绘制方法应该只绘制类的当前状态。因此,您不应在paintComponent() 方法中向面板添加组件。
-
我认为没有理由保留这两个 ArrayList。组件应该知道如何绘制自身并包含绘制自身所需的所有必要信息。
也许您可以只绘制一个 class Form extends React.Component {
constructor(props) {
super(props);
this.state = { input: 'INITIALDATA' } // Data fetched at componentDidMount
this.initialState = this.state;
}
componentDidMount() {
// fetch and set the initial data
// or if you fetch the initial data here,then set it to this.intialState
// after fetching
fetchInitialData().then(res => this.initialState = res);
}
......
......
handleSubmit = e => {
......
......
}).then(res => {
// Normal maneuver if success
this.setState({ input: res.json() });
}).catch(e => {
/* Fall back to the initial data fetched!
*/
this.setState(this.initialState);
})
}
render() {
......
......
}
}
ReactDOM.render(<Form/>,document.body)
,而不是使用实际的组件。查看Drag a Painted Shape。它保留所有要绘制的 Shape
的 ArrayList。此 ArrayList 用于标识要拖动的 Shapes
。您需要用现有的鼠标处理逻辑替换拖动逻辑。