我试图让用户选择他们想要在我的GUI上绘制的形状。我有一系列按钮:圆形,方形和矩形。我的actionListener工作,因为它将一个字符串打印到我的控制台,但它不会在我的GUI上显示形状。如何使用actionCommand
在我的面板上绘制该形状。
public void paintComponent(Graphics g) {
g2D = (Graphics2D) g;
//Rectangle2D rect = new Rectangle2D.Double(x, y, x2-x, y2-y);
//g2D.draw(rect);
repaint();
}
public void actionPerformed(ActionEvent arg0) {
if(arg0.getActionCommand().equals("Rect")){
System.out.println("hello");
Rectangle2D rect = new Rectangle2D.Double(x, y, x2-x, y2-y);
g2D.draw(rect); //can only be accessed within paintComponent method
repaint();
}
答案 0 :(得分:3)
如果您首先绘制矩形,然后要求重新绘制,矩形将消失。
您应该将新形状存储在临时变量中并将其渲染到paintComponent中。
private Rectangle2D temp;
// inside the actionPerformed
temp = new Rectangle2D.Double(x, y, x2-x, y2-y);
repaint();
// inside the paintComponent
if(temp != null) {
g2D.draw(temp);
}
答案 1 :(得分:2)
使rect成为字段nto局部变量。在actionPerformed中创建正确的rect并调用repaint()。然后将调用paintComponent()。它应该是这样的
public void paintComponent(Graphics g) {
g2D = (Graphics2D) g;
g2D.draw(rect);
}