【问题标题】:Using AWT Buttons and detecting if clicked使用 AWT 按钮并检测是否被点击
【发布时间】:2012-07-29 21:13:40
【问题描述】:

我刚加入,很高兴来到这里~所以,今天早上(大约凌晨 2 点,但除此之外:P)我正在用 JFrame 和其他 GUI 东西做一些 Java 测试。这是我第一次使用 GUI。我正在尝试制作一个小型 Java 应用程序,它可以充当梦想的记者。但是,当我遇到无法解决的问题时,我的进度被冻结了。我的代码如下。

import java.awt.*;
import javax.swing.*;
import java.applet.*;

public class Display extends Canvas
{
    static final int WIDTH = 600;
    static final int HEIGHT = 400;
    public static String defaultEntry = "Dreams...";
    public static final String TITLE = "Dream Journal Testing";

    Button erase;

    public static void main(String[] args)
    {
        Display d = new Display();
        d.create();

    }

    public void create()
    {
        JFrame frame = new JFrame();
        System.out.println("Running");


        Panel cardOne = new Panel();
        Panel p1 = new Panel();
        Panel p2 = new Panel();
        Panel p3 = new Panel();
        Panel grid = new Panel();


        cardOne.setLayout(new BorderLayout());
        p1.setLayout(new GridLayout(2,1,3,6));
        TextArea textArea1 = new TextArea(defaultEntry);

        /*Font f1 = new Font("Courier", Font.PLAIN, 16);
        setFont(f1);*/
        Label l1 = new Label("Welcome to the Dream Journal! :)");
    Label l2 = new Label("Type your dream below:");
    p1.add(l1);
    p1.add(l2);



    p2.add(textArea1);

    p3.setLayout(new FlowLayout(FlowLayout.CENTER));

    Button ok = new Button("Save");
    erase = new Button("Erase");
    p3.add(erase);
    p3.add(ok);


    cardOne.add("North",p1);
    cardOne.add("Center",p2);
    cardOne.add("South",p3);

    frame.add(cardOne);
    //frame.add(cardOne);
    //frame.setLocationRelativeTo(null);
    frame.pack();
    frame.setTitle(TITLE);
    frame.setSize(WIDTH, HEIGHT);
    frame.setResizable(false);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    System.out.println(textArea1.getText());

}

/*public boolean handleEvent(Event evt)
{
    if(evt.target == erase)
    {
        System.out.println("it works");
        return true;
    }

    else return super.handleEvent(evt);
}
*/  
public boolean action(Event evt, Object arg)
{
    if("Erase".equals(arg))
    {
        System.out.println("hello");
        //textArea1.setText("");
    }
    return true;
}   
}

我的问题是我无法弄清楚如何制作它,所以如果按下“擦除”AWT 按钮,系统将打印一行(作为测试)。我努力了 公共布尔操作(事件 evt,对象 arg) 和 公共布尔句柄事件,但都不起作用。有人对我这个 Java 菜鸟有什么建议吗?谢谢!! :)

【问题讨论】:

    标签: java events user-interface button awt


    【解决方案1】:

    你需要实现ActionListner

    public class Display extends Canvas implements ActionListener
    

    并将自己添加到您的按钮中:

      erase.addActionListener(this);
    

    然后实现所需的方法:

    public void actionPerformed(ActionEvent event) {
        //do stuff
    }
    

    欲了解更多信息,请查看this tutorial on creating ActionListeners。 您会发现这种可观察模式在 Java GUI 中被广泛使用。


    几个高水平的批评:

    1. 当有类似但更新(阅读:更灵活)的 Swing 组件(即JButton)时,您正在使用许多较旧的 AWT 组件(即Button)。 Take a look at this 快速了解差异。
    2. 您实现的事件模型在 1997 年被修改为我上面建议的可观察模式。如果您想了解更多信息,请you can read this

    【讨论】:

    • 感谢您的回复。实现后,布尔操作或布尔句柄事件会起作用吗?
    【解决方案2】:

    一种方法是向按钮添加一个动作监听器(例如,用于 Save)。另一种方法是创建一个Action(例如用于Erase)。


    除非必要,否则不要将 Swing 与 AWT 组件混合使用。此时甚至不值得学习如何使用 AWT 组件,仅使用 Swing 以获得最佳结果和最佳帮助。

    这是应用程序的一个版本。使用所有 Swing 组件。

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class Display 
    {
        static final int WIDTH = 600;
        static final int HEIGHT = 400;
        public static String defaultEntry = "Dreams...";
        public static final String TITLE = "Dream Journal Testing";
    
        JButton erase;
    
        public static void main(String[] args)
        {
            Display d = new Display();
            d.create();
        }
    
        public void create()
        {
            JFrame frame = new JFrame();
            System.out.println("Running");
    
            JPanel cardOne = new JPanel();
            JPanel p1 = new JPanel();
            JPanel p2 = new JPanel();
            JPanel p3 = new JPanel();
    
            cardOne.setLayout(new BorderLayout());
            p1.setLayout(new GridLayout(2,1,3,6));
            JTextArea textArea1 = new JTextArea(defaultEntry);
    
            JLabel l1 = new JLabel("Welcome to the Dream Journal! :)");
            JLabel l2 = new JLabel("Type your dream below:");
            p1.add(l1);
            p1.add(l2);
    
            p2.add(textArea1);
    
            p3.setLayout(new FlowLayout(FlowLayout.CENTER));
    
            JButton ok = new JButton("Save");
            ok.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent ae) {
                    System.out.println("Do " + ae.getActionCommand());
                }
            });
            erase = new JButton(new EraseAction());
            p3.add(erase);
            p3.add(ok);
    
            // Use the constants
            cardOne.add(BorderLayout.PAGE_START,p1);
            cardOne.add(BorderLayout.CENTER,p2);
            cardOne.add(BorderLayout.PAGE_END,p3);
    
            frame.add(cardOne);
            frame.pack();
            frame.setTitle(TITLE);
            frame.setSize(WIDTH, HEIGHT);
            frame.setResizable(false);
            frame.setLocationByPlatform(true);
            frame.setVisible(true);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
            System.out.println(textArea1.getText());
        }
    }
    
    class EraseAction extends AbstractAction {
    
        EraseAction() {
            super("Erase");
        }
    
        @Override
        public void actionPerformed(ActionEvent arg0) {
            System.out.println("Do " + arg0.getActionCommand());
        }
    }
    

    【讨论】:

    • 虽然它不是一个直接的答案,但它是相关且信息丰富的,特别是对于像我这样的人,刚刚开始。感谢您的回复!
    • 不客气。我在编辑中更改了一些内容以将其升级为“答案”。 :)
    【解决方案3】:

    首先让我解释一下事件处理程序的基础......

    -首先有Event Source,当在Event Source上发生任何动作时,Event Object被抛出到call back方法

    - Call Back 方法是 Listener(接口)中的方法,由@987654326 需要实现 @ 实现了这个监听器。

    - 当对事件源执行操作时,此回调方法中的语句将指示需要做什么。

    例如:

    假设

      Event Source - Button
      When Clicked - Event object is thrown at the call back method
      Call back method - actionPerformed(ActionEvent e) inside ActionListener.
    

    现在你的情况:

    现在这可以通过两种方式完成.....

    1.让你Display实现ActionListener,然后注册button ActionListener,最后实现ActionListener的抽象方法 actionPerformed()

    例如:

        public class Display extends Canvas implements ActionListener{
    
    
        public Display(){
    
        // Your code....
    
           setComponent();            // Initializing the state of Components 
         }
    
    
        public void setComponent(){
    
            // Your code.........
    
           Button b = new Button("Click");
           b.addActionListener(this);        // Registering the button.
    
           // Your code..........
    
              }
    
        public void actionPerformed(ActionEvent event) {
    
           // Do here whatever you want on the Button Click
    
         }
    
    
      }
    

    2. 使用Anonymous 类。

    -匿名类同时声明和初始化。

    -匿名类必须实现或扩展只有一个interfaceclass分别。

    您的 Display 类不会在这里实现 ActionListener....

    public class Display extends Canvas {
    
    
        public Display(){
    
        // Your code....
    
           setComponent();            // Initializing the state of Components 
         }
    
    
        public void setComponent(){
    
            // Your code.........
    
           Button b = new Button("Click");
                                           // Registering the button and Implementing it
    
            b.addActionListener(new ActionListener(){
    
              public void actionPerformed(ActionEvent event) {
    
                    // Do here whatever you want on the Button Click
                }
    
    
             }); 
    
           // Your code..........
    
              }
    
    
    
    
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-08
      • 2013-05-09
      • 2013-07-26
      • 1970-01-01
      • 2011-02-16
      • 1970-01-01
      • 1970-01-01
      • 2018-06-12
      相关资源
      最近更新 更多