虽然我已经设置了actionListener,但按下按钮时没有任何反应

时间:2015-08-23 07:04:12

标签: java swing user-interface jbutton actionlistener

我正在学习GUI,我遇到了问题。花了整整一夜试图搞清楚后,我完全放弃了。如下面所示的代码,我想在按下按钮后显示面板(TwoRectangle)。然而,当我按下它时,什么也没发生。有人可以帮我解决这个问题吗?谢谢!。

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

    }
}

1 个答案:

答案 0 :(得分:2)

当动态地向容器添加组件并且容器已经可见时,您需要重新验证容器。

添加

frame.revalidate();

actionPerformed()方法的末尾。