[英]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. 我正在创建一个谁想成为百万富翁游戏,并创建了一个半按钮,我想使用该按钮来删除两个答案,即JButton。 Here is the code for two JButtons that are answer options.
这是两个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);
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,
亲切的问候,
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);
You try to remove Answer1
and Answer2
from btnHalfAndHalf
, but those are not contained in btnHalfAndHalf
. 您尝试删除
Answer1
和Answer2
从btnHalfAndHalf
,但这些都是不包含在btnHalfAndHalf
。 Just do Answer1.setVisible(false); Answer2.setVisible(false);
只要做
Answer1.setVisible(false); Answer2.setVisible(false);
Answer1.setVisible(false); Answer2.setVisible(false);
or Answer1.setEnabled(false); Answer2.setEnabled(false);
或
Answer1.setEnabled(false); Answer2.setEnabled(false);
Answer1.setEnabled(false); Answer2.setEnabled(false);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.