James Faulkner
James Faulkner

Reputation: 91

Remove JButtons using a JButton

I am creating a Who wants to be a millionaire game and have created a half and half button which I want to use in order to remove two answers which are JButtons. Here is the code for two JButtons that are answer options.

enter code here: Answer2 = new JButton("B");
    Answer2.setBackground(Color.YELLOW);
    Answer2.setHorizontalAlignment(SwingConstants.LEFT);
    Answer2.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Answer2.setBackground(Color.RED);
            Answer2.setForeground(Color.WHITE);
        }
    });
    Answer2.setBounds(220, 105, 188, 25);
    panel.add(Answer2);
    Answer1 = new JButton("A");
    Answer1.setBackground(Color.YELLOW);
    Answer1.setHorizontalAlignment(SwingConstants.LEFT);
    Answer1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Answer1.setBackground(Color.RED);
            Answer1.setForeground(Color.WHITE);
        }
    });
    Answer1.setBounds(20, 105, 188, 25);
    panel.add(Answer1);

In order to carry this out I did some and found this method and tried it but it is not working for me. Here is the code showing what I have tried to do with the half and half button

    btnNextQuestion.setBounds(296, 204, 115, 23);
    panel.add(btnNextQuestion);
    btnHalfAndHalf = new JButton("Half and half");
    btnHalfAndHalf.setForeground(new Color(0, 0, 0));
    btnHalfAndHalf.setBackground(new Color(255, 255, 51));
    btnHalfAndHalf.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            btnHalfAndHalf.remove(Answer1);
            btnHalfAndHalf.remove(Answer2);//This is the method I tried
        }
});
    btnHalfAndHalf.setBounds(22, 204, 115, 23);
    panel.add(btnHalfAndHalf); 

Please let me know what I could do in order to make it do what I intend using the code in my question. Kind Regards,

Upvotes: 0

Views: 45

Answers (2)

pianka
pianka

Reputation: 140

You can simply do

Answer1.setVisible(false);
Answer2.setVisible(false);

You don't need to remove the buttons. You can easily hide them. Or, if you prefer, in this project you can also disable the buttons.

Answer1.setEnabled(false);
Answer2.setEnabled(false);

Upvotes: 3

Vampire
Vampire

Reputation: 38629

You try to remove Answer1 and Answer2 from btnHalfAndHalf, but those are not contained in btnHalfAndHalf. Just do Answer1.setVisible(false); Answer2.setVisible(false); or Answer1.setEnabled(false); Answer2.setEnabled(false);

Upvotes: 2

Related Questions