对java中的awt和swing感到困惑

时间:2015-03-19 17:35:19

标签: java swing layout-manager null-layout-manager

我在java中使用SWING和AWT组件。我对它的布局感到困惑。我添加了一个面板并使用setBounds()在该面板中添加按钮,然后将此面板添加到使用流布局的框架中。但面板无法显示自己..这是我的代码:

public class MainWindow implements ActionListener {
    private JFrame frame;
    private JPanel panel;
    private JButton play;
    private JButton exit;

    public MainWindow() {
        frame = new JFrame();
        panel = new JPanel();

        play = new JButton(new ImageIcon("button.png"));
        exit = new JButton(new ImageIcon("exit.png"));

        panel.setLayout(null);
        play.setBounds(200, 200, 90, 40);
        exit.setBounds(200, 300, 90, 40);
        panel.setBackground(new Color(45, 204, 112));
        play.addActionListener(this);
        exit.addActionListener(this);
        panel.add(play);
        panel.add(exit);

        Container cont = frame.getContentPane();
        cont.setLayout(new FlowLayout());
        cont.add(panel);

        frame.setSize(800, 700);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

0 个答案:

没有答案