【问题标题】:Java Swing - draw consecutive rectangles after clicking a buttonJava Swing - 单击按钮后绘制连续的矩形
【发布时间】:2016-03-25 00:23:53
【问题描述】:

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

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

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); } }

【问题讨论】:

    标签: java swing


    【解决方案1】:

    您的paintComponent() 只绘制一个矩形。它清除面板的背景,然后绘制矩形。

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-30
      • 2016-06-02
      • 1970-01-01
      • 2016-02-15
      • 1970-01-01
      相关资源
      最近更新 更多