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