将其他类的JPanel添加到JPanel

时间:2019-04-18 16:44:39

标签: java swing jframe jpanel jbutton

我想将另一个类的JPanel添加到JPanel:

retry

这是我的第二个JPanel:

class FirstPanel extends JPanel
{
private JButton button;

FirstPanel()
{
    setLayout(null);
    setVisible(true);

    button = new JButton();

    button.setBounds(x, y, width, height);
    button.setFocusPainted(false);
    button.setIcon(new ImageIcon(SecondPanel.class.getResource(filePath)));
    button.setBackground(bgColor);
    button.setForeground(Color.white);
    button.setVisible(true);

    Border emptyBorder = BorderFactory.createEmptyBorder();
    button.setBorder(emptyBorder);

    add(button);

    ButtonActionHandler buttonActionHandler = new ButtonActionHandler();

}


public class ButtonActionHandler implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        setVisible(true);
        add(new SecondJPanel());

        new SecondJPanel().setVisible(true);
    }
} }

}

通过JFrame(来自另一个类)启动第一个面板有效,但是向第一个面板添加第二个JPanel无效。

真的很感谢任何帮助

1 个答案:

答案 0 :(得分:0)

对不起,但您似乎不明白我在告诉您什么。

作曲是你的朋友。

我会这样:

public class JPanel1 extends JPanel {

    private JButton button;

    public JPanel1(ActionListener buttonListener) {
       this.button = new Button("Push me");
       this.button.addActionListener(buttonListener);
       // do what's needed to add the button to the display.
    }
}

public class JPanel2 extends JPanel {

    private JButton button;

    public JPanel2(ActionListener buttonListener) {
       this.button = new Button("Push me");
       this.button.addActionListener(buttonListener);
       // do what's needed to add the button to the display.
    }
}

public class TwoPanelFrame extends JFrame {

    public TwoPanelFrame(JPanel p1, JPanel p2) {
        // add the two panels to your frame and display.
    }
}