Добавить JPanel из другого класса в JPanel - PullRequest
0 голосов
/ 18 апреля 2019

Я бы хотел добавить 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 к первой - нет.

Любая помощь очень ценится

1 Ответ

0 голосов
/ 18 апреля 2019

Извините, но вы, похоже, не понимаете, о чем я вам говорю.

Композиция твой друг.

Я бы сделал это так:

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