0

I just joined, and am glad to be here~ So, this morning (at like 2am, but thats besides the point :P ) I was doing a little bit of Java tests with JFrame and other GUI stuff. This is my first time working with GUIs. I was trying to make a little java app that would act as a dream journaller. However, my progress was frozen when I encountered a problem i could not solve. My code is as follows.

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;
}   
}

The problem i have is I am not able to figure out how to make it so if the "Erase" AWT button is pushed, the system will print a line (as a test). I have tried public boolean action(Event evt, Object arg) And public boolean handleEvent, but neither worked. Anyone have any suggestions for the Java noob that is me? Thanks!! :)

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
MichaelK
  • 185
  • 1
  • 10

3 Answers3

2

One way is to add an action listener to the button (e.g. for Save). Another way is to create an Action (e.g. for Erase).


Don't mix Swing with AWT components unless it is necessary. It is not worth even learning how to use AWT components at this point in time, use Swing only for best results and best help.

Here is a version of the app. using all Swing components.

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());
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
2

First let me explain you the Funda of Event Handler....

- First of all there are Event Source, when any action take place on the Event Source, an Event Object is thrown to the call back method.

- Call Back method is the method inside the Listener (Interface) which is needed to be implemented by the Class that implements this Listener.

- The statements inside this call back method will dictate whats needed to be done, when the action is done on the Event Source.

Eg:

Assume

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

Now your case :

Now this can be done in 2 ways.....

1. Let you Display class implements the ActionListener, then Register the button with the ActionListener, and finally implement the abstract method actionPerformed() of ActionListener.

Eg:

    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. Use Anonymous class.

- Anonymous class are declared and initialized simultaneously.

- Anonymous class must implement or extend to only one interface or class resp.

Your Display class will NOT implement ActionListener here....

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..........

          }




  }
Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75
1

You need to implement ActionListner :

public class Display extends Canvas implements ActionListener

and add yourself to your button as such:

  erase.addActionListener(this);

and then implement the required method:

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

For more info, check out this tutorial on creating ActionListeners. You'll find that this observable pattern is widely used the in Java GUI.


A couple high level critiques:

  1. You are using many older AWT components (ie Button) when there are similar, but newer (read: more flexible) Swing components available (ie JButton). Take a look at this for a quick explanation on the difference.
  2. The event model that you have implemented was revamped in 1997 to the observable pattern that I suggested above. If you would like to learn more, you can read this.
Community
  • 1
  • 1
akf
  • 38,619
  • 8
  • 86
  • 96
  • Thank you for your reply. After implementing this, would the boolean action or boolean handleEvent work? – MichaelK Aug 01 '12 at 01:38