2016-03-24 16 views
0

ボタンを押した後に長方形を描きたい。ボタンを初めて押すと、四角形が描かれます。私は、もう一度ボタンを押した後、最初のものに隣接する長方形を描こうとしていますが、何も描画されていません。誰か助けてくれますか?Java Swing - ボタンをクリックした後に連続した長方形を描く

これは私が使用するコードです。しか1つの四角形を描画します

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

答えて

4

あなたのpaintComponent()ありがとうございました。パネルの背景をクリアしてから矩形を描画します。

あなたが複数の長方形をしたいなら、あなたはどちらかを行う必要があります。

  1. は上に各矩形を描画

  2. を描画して、リストを介して、時間を反復して四角形を描画する四角形のリストを保持BufferedImageを作成し、次にBufferedImageをペイントします。

これらのアプローチの両方の実例については、Custom Painting Approachesを参照してください。両方を試して、より好きなものを見てください。

関連する問題