使用 JButton 删除 JButton

Remove JButtons using a JButton

我正在创建一个谁想成为百万富翁游戏,并创建了一个半按钮,我想使用它来删除两个答案,即 JButtons。这是两个作为答案选项的 JButton 的代码。

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);

为了实现这一点,我做了一些并找到了这个方法并进行了尝试,但它对我不起作用。这是显示我尝试使用 half 和 half 按钮做什么的代码

    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); 

请让我知道我可以做什么,以便使用问题中的代码使其按照我的意图进行。 亲切的问候,

您尝试从 btnHalfAndHalf 中删除 Answer1Answer2,但 btnHalfAndHalf 中不包含这些。只需 Answer1.setVisible(false); Answer2.setVisible(false);Answer1.setEnabled(false); Answer2.setEnabled(false);

你可以简单地做

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

您不需要删除按钮。您可以轻松隐藏它们。或者,如果您愿意,您也可以在此项目中禁用按钮。

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