我试图让用户选择他们想要在我的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);
    }

09-25 17:00