我正在创建一个“谁想成为百万富翁”游戏,并创建了一个半按钮,我想使用它来删除两个 JButton 答案。以下是两个作为答案选项的 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);
为了实现这一点,我做了一些,找到了这个方法并尝试了它,但它对我不起作用。下面的代码显示了我尝试对半按钮执行的操作
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);
请让我知道我可以做什么,以便使用我的问题中的代码实现我想要的功能。 亲切的问候,
最佳答案
你可以简单地做
Answer1.setVisible(false);
Answer2.setVisible(false);
您不需要删除按钮。您可以轻松隐藏它们。或者,如果您愿意,在此项目中您也可以禁用这些按钮。
Answer1.setEnabled(false);
Answer2.setEnabled(false);
关于java - 使用 JButton 删除 JButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36458789/