Java 此操作如何与我的按钮交互?
我试图允许用户选择他们想要在我的GUI上绘制的形状。我有很多按钮可供选择:圆形、方形和矩形。我的actionListener在向我的控制台打印字符串时工作,但它不会在我的GUI上显示该形状。如何使用Java 此操作如何与我的按钮交互?,java,swing,button,Java,Swing,Button,我试图允许用户选择他们想要在我的GUI上绘制的形状。我有很多按钮可供选择:圆形、方形和矩形。我的actionListener在向我的控制台打印字符串时工作,但它不会在我的GUI上显示该形状。如何使用actionCommand在面板上绘制该形状 public void paintComponent(Graphics g) { g2D = (Graphics2D) g; //Rectangle2D rect = new Rectangle2D.Double(x, y, x2-x, y
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();
}
如果您先绘制矩形,然后要求重新绘制,则矩形将消失 您应该将新形状存储在临时变量中,并在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);
}
如果您先绘制矩形,然后要求重新绘制,则矩形将消失 您应该将新形状存储在临时变量中,并在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字段设置为局部变量。在执行的操作中,创建正确的rect并调用repaint()。然后将调用paintComponent()。应该是这样的
public void paintComponent(Graphics g) {
g2D = (Graphics2D) g;
g2D.draw(rect);
}
将rect字段设置为局部变量。在执行的操作中,创建正确的rect并调用repaint()。然后将调用paintComponent()。应该是这样的
public void paintComponent(Graphics g) {
g2D = (Graphics2D) g;
g2D.draw(rect);
}
还要考虑<代码> Super .PultCug(g)。还考虑<代码> Super .PultCug(g)< /C>。