我正在尝试使用布尔标志基于按钮单击来绘制图形。之前,我在 ShapeGUI 类中将布尔值设置为公共静态布尔类型,并在 ShapeListener 中使用 Shape.draw 调用它,虽然它需要大约 10 秒才能生成绘图。
现在我在 ShapeListener 类本身中设置布尔标志。现在它要么不重绘,要么很慢。当我单击按钮时,如何使绘图立即出现?
public class ShapeGUI extends JFrame
{
public static final int WIDTH = 500;
public static final int HEIGHT = 500;
public ShapeGUI()
{
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//setLayout(new FlowLayout());
setLocationRelativeTo(null);
JMenuBar menu = new JMenuBar();
JMenu file = new JMenu("File");
menu.add(file);
JMenuItem save = new JMenuItem("Save Information");
JMenuItem exit = new JMenuItem("Exit");
file.add(save);
file.add(exit);
setJMenuBar(menu);
ShapeListener test = new ShapeListener();
JButton button = new JButton("Hello");
test.setBackground(Color.CYAN);
button.addActionListener(new ShapeListener());
test.add(button);
add(test);
//followed this person's advice
//First off, your drawing should be done in a paintComponent method override that is held in a class that extends JPanel. Next, this class could have a boolean variable that the paintComponent uses to decide if it will draw a rectangle or not. The button press simply sets the boolean variable and calls repaint on the drawing JPanel.
}
}
public class ShapeListener extends JPanel implements ActionListener
{
boolean draw = false;
Shape s = new Circle();
Shape a = new Rectangle();
@Override
public void actionPerformed(ActionEvent e)
{
draw = true;
repaint();
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if(draw)
{
s.draw(g);
}
else
{
a.draw(g);
}
}
}