kuhpro
kuhpro

Reputation: 23

Although I've already set actionListener, nothing happens when the button is pressed

I'm learning GUI, and I have a problem. After spending a whole night trying to figure it out, I completely gave up. As the code shown below, I want the panel (TwoRectangle) to appear after I hit the button. However, when I pressed it, nothing happened. Can someone help me solve this problem?. Thank you!.

class TwoRectangle extends JPanel implements ActionListener {
    Point p1;
    Point p2;
    int dx;
    int dy;

    public TwoRectangle() {
        p1 = new Point (20, 40);
        p2 = new Point (60, 10);
        dx = 5;
        dy = 5;

        Timer time = new Timer(100, this);
        time.start();

    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.RED);
        g.fillRect(p1.x, p1.y, 70, 30);
        g.setColor(Color.BLUE);
        g.fillRect(p2.x, p2.y, 20, 80);

    }

    public void actionPerformed(ActionEvent e) {
        p1.x += dx;
        p2.y += dy;
        if (p1.x <= 0 || p1.x + 70 >= getWidth()) {
            dx = -dx;
        }
        if (p2.y <= 0 || p2.y + 80 >= getHeight()) {
            dy = -dy;
        }
        repaint();
    }
}

public class ObjectsAppear {
    public static void main (String args[]) {

        ObjectsAppear appear = new ObjectsAppear();
    }

    JFrame frame;
    JButton button;
    JLabel label;

    public ObjectsAppear() {

        label = new JLabel("Hit play to execute");
        button = new JButton("Play");
        JPanel north = new JPanel(new FlowLayout());
        north.add(label);
        north.add(button);


        frame = new JFrame("Window Frame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());
        frame.setSize(new Dimension(300,400));
        frame.add(north, BorderLayout.NORTH);

        // This is the code to make the panel to appear 
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                TwoRectangle display = new TwoRectangle();
                display.setBackground(Color.WHITE);
                frame.add(display, BorderLayout.CENTER);
            }
        });

        frame.setVisible(true);

    }
}

Upvotes: 2

Views: 298

Answers (1)

JB Nizet
JB Nizet

Reputation: 691913

When adding a component to a container dynamically, and the container is already visible, you need to revalidate the container.

Just add

frame.revalidate();

at the end of the actionPerformed() method.

Upvotes: 2

Related Questions