Java Swing - 单击按钮后绘制连续的矩形

标签 java swing

我想在按下按钮后绘制一个矩形。当我第一次按下按钮时,它会绘制一个矩形。再次按下按钮后,我尝试在第一个矩形附近绘制更多矩形,但没有绘制任何内容。有人可以帮助我吗?

这是我使用的代码。非常感谢

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()只绘制一个矩形。它清除面板的背景,然后绘制矩形。

如果您想要多个矩形,那么您需要:

  1. 保留一个要绘制的矩形列表,然后每次迭代该列表并绘制矩形

  2. 将每个矩形绘制到 BufferedImage 上,然后仅绘制 BufferedImage。

查看Custom Painting Approaches了解这两种方法的工作示例。尝试两者,看看您更喜欢哪一个。

关于Java Swing - 单击按钮后绘制连续的矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36192969/

相关文章:

java - AbstractTableModel 从不同线程更新

java - 从文件读取到 JTextArea

java - 在 JPanel 中生成包含多个点的图

Java如何使用鼠标拖动来调整无边框窗口的大小?

java - JBoss 5 截断 base64 cookie 字符串的尾随 =

java - 在 Netty 中处理 Http 状态码 302 Moved Temporarily

java - 自定义 Java Swing 菜单项、菜单分隔符和菜单加速器的前景色和背景色

Java:如何禁用java中的按钮?

java - 如何使用apache poi检查excel文件中的列是否隐藏

java - hibernate 。大结果和分页