【问题标题】:Buttons in Java [closed]Java中的按钮[关闭]
【发布时间】:2013-06-16 23:55:23
【问题描述】:

这是我的代码的一部分,没有实际的主类,因为它工作正常。我正在尝试编写一个程序,如果您按是(item3),它会说“您知道书名吗?”,但是如果您按否(item4),它会询问“您想还书吗”。到目前为止,无论我按下哪个按钮,它都会返回“你知道书名吗?”。我知道这是因为我在这里将 isClicked 更改为 true:'private boolean isClicked = true;'但我不知道如何改变它,让它做我想做的事。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Welcome extends JFrame {
    private JLabel title1, title2; 
    private JButton item3, item4;

    public Welcome(){
        super("Welcome to Andrew's Library");
        setLayout(new FlowLayout());
        setBackground(Color.RED);   

        boolean isClicked = false;
        title1 = new JLabel("Welcome to Andrew's Library!!!");
        title2 = new JLabel("Would you like to check out a book?");
        item3 = new JButton("YES");
        item4 = new JButton("NO");

        add(title1);
        add(title2);
        add(item3);
        add(item4);

        HandlerClass handler = new HandlerClass();

        item3.addActionListener(handler);
        item4.addActionListener(handler);
    }

    private class HandlerClass implements ActionListener{
        private boolean isClicked = true;

        public void actionPerformed(ActionEvent event){

            if(isClicked){
                title1.setText("Do you know the title of the book?");
                title2.setText(null);       
            } else {
                title1.setText(null);
                title2.setText(null);   
                item3.setVisible(false);
                item4.setText("Do you want to return a book?");
            }
        }
    }           
}

【问题讨论】:

  • ((item3) labelReference) 没有意义。
  • 完全取决于你的意图,这并不明显。您使用的语法是“强制转换”,内部括号内的内容应该是类名(类型)而不是变量名。说明您希望通过该声明实现的目标。
  • 好的,您现在应该通过 cmets 了解您不应该在 JButtons 上使用 MouseListener,而应该使用 ActionListener。您是否进行了这些更改?您应该明白,既然您将侦听器添加到 JButtons,您不应该尝试将源转换为 JLabel。
  • item3JButton,但是您尝试通过 JLabel 进行投射,这些从一开始就不兼容。 JButton 也没有 screen2 方法,因此即使将其转换为 JButton,它仍然无法编译...
  • 什么是“被点击”?您的事件侦听器应检查事件,获取源以查看单击了哪个按钮。或者,创建两个事件处理程序:每个按钮一个。

标签: java eclipse swing


【解决方案1】:

也许试试这个?取ActionEvent参数,看看source是否等于JButton。

private class HandlerClass implements ActionListener{
  private boolean isClicked = true;
  public void actionPerformed(ActionEvent event){
    if(isClicked){
        title1.setText("Do you know the title of the book?");
        /** TODO uncomment here
        if(item3.equals(event.getSource())
          System.out.println("item3 pressed");
        else
          System.out.println("item4 pressed");
        //*/
    } else {...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-09
    • 2010-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多