将JPanel类添加到JPanel

时间:2019-04-19 10:25:01

标签: java jframe jpanel jbutton

当我单击第一个JPanel类中的按钮时,我想添加一个JPanel类

class LaunchForm extends JPanel {
    public static JButton btnSettings;
    private ButtonActionHandler buttonActionHandler;

    LaunchForm() {
        buttonActionHandler = new ButtonActionHandler();
        setLayout(null);
        setVisible(true);
        btnSettings = new JButton();
        createButton(btnSettings, 385, 190, 191, 55, path_btnStartGame);
    }

    private void createButton(JButton button, int  x, int y, int width, int height, String filePath) {
        button.setBounds(x, y, width, height);
        button.setFocusPainted(false);
        button.setIcon(new ImageIcon(LaunchForm.class.getResource(filePath)));
        button.setBackground(bgColor);
        button.setForeground(Color.white);
        button.setVisible(true);
        button.setBorderPainted(false);
        button.setContentAreaFilled(false);
        Border emptyBorder = BorderFactory.createEmptyBorder();
        button.setBorder(emptyBorder);
        button.addActionListener(new ButtonActionHandler());
        add(button);
    }

    public class ButtonActionHandler implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            add(new SettingsPanel());
        }
    }
}

这是我的SettingsPanel,当我使用此面板启动程序时,它会正确显示。

class SettingsPanel extends JPanel {
    private JButton btnBack;

    SettingsPanel() {
        setLayout(null);
        setVisible(true);
        btnBack = new JButton();
        createButton(btnBack, 30, 30, 40, 40, path_btnLeftArrow);
    }

    private void createButton(JButton button, int  x, int y, int width, int height, String filePath) {
        button.setBounds(x, y, width, height);
        button.setFocusPainted(false);
        button.setIcon(new ImageIcon(LaunchForm.class.getResource(filePath)));
        button.setBackground(bgColor);
        button.setForeground(Color.white);
        button.setVisible(true);
        button.setBorderPainted(false);
        button.setContentAreaFilled(false);
        Border emptyBorder = BorderFactory.createEmptyBorder();
        button.setBorder(emptyBorder);
        add(button);
    }
}

但是,它不起作用。而且我不想打开一个新窗口。我只想用SettingsPanel“切换” JPanel。

因此,我们将不胜感激

0 个答案:

没有答案