[英]How can this actionPerformed interact with my button?
我试图允许用户选择他们想在我的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();
}
如果您先绘制矩形,然后要求重新绘制,矩形将消失。
您应该将新形状存储在temp变量中,并将其呈现在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);
}
使rect为字段n到局部变量。 在actionPerformed中创建适当的rect并调用repaint()。 然后将调用paintComponent()。 应该是这样
public void paintComponent(Graphics g) {
g2D = (Graphics2D) g;
g2D.draw(rect);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.