繁体   English   中英

将JPanel从其他类添加到JPanel

[英]Add JPanel from other Class to JPanel

我想将另一个类的JPanel添加到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);
    }
} }

这是我的第二个JPanel:

class SecondPanel extends JPanel
{
private JButton button;
private JLabel titleLabel;

SecondPanel()
{

    setLayout(null);
    setVisible(true);

    button = new JButton();

    button.setBounds(100, 200, 100, 200);
    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);
}

}

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

任何帮助都非常感谢

对不起,你好像不明白我告诉你的是什么。

作文是你的朋友。

我会这样做:

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.
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM