我想在按下按钮后绘制一个矩形。当我第一次按下按钮时,它会绘制一个矩形。再次按下按钮后,我尝试在第一个矩形附近绘制更多矩形,但没有绘制任何内容。有人可以帮助我吗?
这是我使用的代码。非常感谢
class Coord{
int x = 0;
int y = 0;
}
public class DrawRectangle extends JPanel {
int x, y, width, height;
public DrawRectangle (int x, int y, int width, int height){
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
public Dimension getPreferredSize()
{
return new Dimension(this.width, this.height);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.RED);
g2.fillRect(this.x, this.y, this.width, this.height);
}
public static void main(String[] args)
{
final Coord coord = new Coord();
final JPanel center = new JPanel();
center.setLayout(null);
center.setLocation(10, 10);
center.setSize(300, 300);
JButton button = new JButton("Button");
button.setBounds(350,200,75,50);
button.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
DrawRectangle component = new DrawRectangle(coord.x, coord.y, 30, 30);
component.setLocation(coord.x, coord.y);
component.setSize(component.getPreferredSize());
center.add(component);
center.repaint();
coord.x += 30;
coord.y +=30;
}
});
JFrame frame = new JFrame();
frame.setLayout(null);
frame.add(center);
frame.add(button);
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
最佳答案
你的paintComponent()只绘制一个矩形。它清除面板的背景,然后绘制矩形。
如果您想要多个矩形,那么您需要:
保留一个要绘制的矩形列表,然后每次迭代该列表并绘制矩形
将每个矩形绘制到 BufferedImage 上,然后仅绘制 BufferedImage。
查看Custom Painting Approaches了解这两种方法的工作示例。尝试两者,看看您更喜欢哪一个。
关于Java Swing - 单击按钮后绘制连续的矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36192969/