繁体   English   中英

使用JButton删除JButton

[英]Remove JButtons using a JButton

我正在创建一个谁想成为百万富翁游戏,并创建了一个半按钮,我想使用该按钮来删除两个答案,即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);

您尝试删除Answer1Answer2btnHalfAndHalf ,但这些都是不包含在btnHalfAndHalf 只要做Answer1.setVisible(false); Answer2.setVisible(false); Answer1.setVisible(false); Answer2.setVisible(false); Answer1.setEnabled(false); Answer2.setEnabled(false); Answer1.setEnabled(false); Answer2.setEnabled(false);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM