Domanda

I'm making a program with 2 JButton, however I have a MyFrame class and the buttons are in a different class named KnoppenPanel. The problem is, when I do this I will get a JButton in a JButton. So I have my 2 buttons and another Button surrounding these. How do I solve this?

MyFrame:

public class MyFrame extends JFrame {

    Uithangbord u = new Uithangbord();
    KnoppenPanel kp = new KnoppenPanel();

    public MyFrame() {
        setLayout(new FlowLayout());

        add(u);
        add(kp);

        setSize(280, 180);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
}

public class KnoppenPanel extends JButton implements ActionListener {
private JButton b, b2;
private JPanel p1;

Uithangbord bord = new Uithangbord();

public KnoppenPanel() {
    p1 = new JPanel();
    add(p1);

    b = new JButton("Open");
    p1.add(b);
    b.addActionListener(this);

    b2 = new JButton("Gesloten");
    p1.add(b2);
    b2.addActionListener(this);
}

public void actionPerformed(ActionEvent event) {
    JButton knop = (JButton)(event.getSource());
    if (knop == b) {
        b.setEnabled(false);
        b2.setEnabled(true);
        bord.maakOpen();
    }
    if (knop == b2) {
        b2.setEnabled(false);
        b.setEnabled(true);
        bord.maakGesloten();
    }
}
}
È stato utile?

Soluzione

You class is extending JButton. Then when you add your JPanel (with 2 JButton) you are adding this in a JButton.

I think what do you want is the KnoppenPanel have only the 2 JButtons then you just need to change:

public class KnoppenPanel extends JButton implements ActionListener {

By

public class KnoppenPanel extends JPanel implements ActionListener {

If you do this change, you can also directly add the JButton in the KnoppenPanel like that:

public KnoppenPanel() {

    b = new JButton("Open");
    add(b);
    b.addActionListener(this);

    b2 = new JButton("Gesloten");
    add(b2);
    b2.addActionListener(this);
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top