首页 > 解决方案 > 将 JPanel 类添加到 JPanel

问题描述

当我单击第一个 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。

所以,任何帮助将不胜感激

标签: javaswingjframejpaneljbutton

解决方案


推荐阅读