Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / GUI / February 2004

Tip: Looking for answers? Try searching our database.

multiple listeners

Thread view: 
The Chief - 25 Feb 2004 03:31 GMT
Hi, I'm new to Java and some help here would be greatly appreciated.

My homework is to create a program where you can add() numbers (and
store them internally) into an array, then sort() the numbers (from
smallest to largest), print() them - no matter sorted or not. And also
an option to search() for a specific number in the array. The methods
are easy but I want to do everything with gui. I've set up the whole
layout and now I have to add the listeners for ALL the buttons - they
are four. The problem is that I don't know how to create multiple
listeners - one for each button - since every button is doing a
different work - add, sort, print, search.

Here's my code so far:

//import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JTextArea;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.JTextField;

public class Frame extends JFrame
{
    private ActionListener listener;
   
    public Frame()
    {   
        createPanel();
        pack();
    }
   
    private void createPanel()
    {
   
        class ButtonListener implements ActionListener
        {
            public void actionPerformed(ActionEvent event)
            {   
                < code for one of the buttons >
            }
        }
       
        // PRINT TEXT AREA
        final JTextArea textArea = new JTextArea(7,50);
        textArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(textArea);
       
        //Frame Creation
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(scrollPane);
        frame.pack();
        frame.show();
       
        //Creation of panels.
        JPanel controlPanel = new JPanel();
        JPanel personalPanel= new JPanel();
        JPanel salaryPanel=new JPanel();
       
        // ARRAY MANIPULATION ELEMENTS
       
            // ADD # TO ARRAY
        final JTextField addField=new JTextField(3);
        JButton addButton=new JButton("Add # to Array");
           
            // SORT THE ARRAY
        JButton sortButton=new JButton("Sort the Array");
       
            // PRINT THE ARRAY
        JButton printButton=new JButton("Print the Array");
   
        // ARRAY SEARCH ELEMENTS
   
            // ENTER # TO SEARCH FOR
        final JTextField searchField=new JTextField(3);
   
            // FIND # IN ARRAY
        JButton findButton=new JButton("Find # in Array");
        ActionListener listener= new ButtonListener();
        findButton.addActionListener(listener); // Add listener
       
        //Array Manipulation Add
        personalPanel.setBorder(new TitledBorder(new EtchedBorder(), "Array
Manipulation"));
        personalPanel.add(addField);
        personalPanel.add(addButton);
        personalPanel.add(sortButton);
        personalPanel.add(printButton);

        //Array Search Add
        controlPanel.setBorder(new TitledBorder(new EtchedBorder(), "Array
Search"));
        controlPanel.add(searchField);
        controlPanel.add(findButton);

        getContentPane().add(personalPanel,BorderLayout.CENTER);
        getContentPane().add(controlPanel,BorderLayout.SOUTH);
    }
}

I tried to create another inner class for the second listener but it
wouldn't let me! Any suggestions?

Thanks in advance!
Thomas Weidenfeller - 25 Feb 2004 08:31 GMT
> My homework [...]
> I tried to create another inner class for the second listener but it
> wouldn't let me! Any suggestions?

Try again. Carefully read the exact error message "it" (whatever "it" is
...) gives you. Read it again and again until you understand the error
message. And yes, it has a meaning, it is not there for pure
entertainment purposes. You also might want to consider to show the
message to other people, e.g. your tutor, teacher or professor.

/Thomas
The Chief - 25 Feb 2004 21:50 GMT
> Thomas Weidenfeller wrote:
> Try again. Carefully read the exact error message "it" (whatever "it" is
[quoted text clipped - 4 lines]
>
> /Thomas

Thanks. It was really my fault. I didn't pay attention to the error that
"it" (the compiler - i use CodeWarrior) gave me. So I tried again and
this time everything worked great. I learnt my lesson, tho. :) Thanks again.
Andrew Thompson - 25 Feb 2004 10:11 GMT
"The Chief" ...
> Hi, I'm new to Java and some help here would be greatly appreciated.
>
[quoted text clipped - 3 lines]
> an option to search() for a specific number in the array. The methods
> are easy but I want to do everything with gui.

Don't.  Your instructor is teaching you
this way for a reason.  Too many folks
rush into writing an applet as soon as
they have 'HelloWrold' working..

I had a look over you code, compiled
it, saw it fail, began to fix it.. and realised
I could toss this code and write fresh stuff
quicker than I could correct what you have.

Stick with your instructor for the moment
and lay off the GUI's, if you want to go
'above and beyond' on your homework,
make sure your non-GUI classes are made
in an 'OO' way (so you can later wrap a GUI
around them easily) and that you put good
comments.

HTH

--
Andrew Thompson
* http://www.PhySci.org/ Open-source software suite
* http://www.PhySci.org/codes/ Web & IT Help
* http://www.1point1C.org/ Science & Technology
The Chief - 25 Feb 2004 22:19 GMT
> Andrew Thompson wrote:
> Don't.  Your instructor is teaching you
> this way for a reason.  Too many folks
> rush into writing an applet as soon as
> they have 'HelloWrold' working..

Actually, ever since we started Java (I'm still in High School) we've
been doing stuff that is console driven. Our teacher wanted us to get
the concepts first before we go into the graphics. So, we started doing
applets and applications couple of weeks ago and this is the first
assignment since then. He told us that if we don't feel comfortable with
GUI we can do it console driven but he'd give some extra credit if we
make it graphical. So, that's why I went this way - I really need the
credit 'cause I screwed up on couple of tests before. Plus, I don't
think it's that difficult - just some trouble with the button listeners
but I found my mistake and it's all good now.

> I had a look over you code, compiled
> it, saw it fail, began to fix it.. and realised
> I could toss this code and write fresh stuff
> quicker than I could correct what you have.

Of course, I'm not saying that my code is awesome - I know it's not. You
might find lots of things easy but it's not the same here, believe me.
These are my first steps into programming and I spend a lot of time
looking at the API, trying to figure out what is what and how to use it.

> Stick with your instructor for the moment
> and lay off the GUI's, if you want to go
[quoted text clipped - 3 lines]
> around them easily) and that you put good
> comments.

Thanks for the advice. I'm trying to do my best. I'm still doing this
assignment in GUI, tho. :) At least now I know how to make multiple
listeners for every component. :)

Can you give me a tip on how to make just *one* inner class ( that'd
implement ActionListener ) instead of making one for each of the
buttons. I'm thinking of making "if" checks in the actionPerformed
method that would check which button was pressed but the problem is I
don't know how to check for a button!?

I don't know if I was clear enough but still.. Thanks again! :)

> HTH
>
[quoted text clipped - 3 lines]
> * http://www.PhySci.org/codes/ Web & IT Help
> * http://www.1point1C.org/ Science & Technology
Andrew Thompson - 25 Feb 2004 22:39 GMT
"The Chief" ...
> > Andrew Thompson wrote:
> > Don't.  Your instructor is teaching you
[quoted text clipped - 5 lines]
> been doing stuff that is console driven. Our teacher wanted us to get
> the concepts first before we go into the graphics.

...give that teacher an apple from me.   :-)

> So, we started doing
> applets and applications couple of weeks ago and this is the first
> assignment since then. He told us that if we don't feel comfortable with
> GUI we can do it console driven but he'd give some extra credit if we
> make it graphical. So, that's why I went this way - I really need the
> credit 'cause I screwed up on couple of tests before.

(chuckles)  OK, that may not be the truth,
but if it's not, it's a lie that's amusing enough
to get you some extra credit this end.

> Thanks for the advice. I'm trying to do my best. I'm still doing this
> assignment in GUI, tho. :) At least now I know how to make multiple
[quoted text clipped - 5 lines]
> method that would check which button was pressed but the problem is I
> don't know how to check for a button!?

I would avoid the inner class entirely,
but that's me, they mess with my head.

I have an example that describes (what I
feel is) a better way to go.
http://www.physci.org/launcher.jsp#SampleDialog

Click the link and you can see the source,
the button at the top of the source page
shows the GUI.

This example implements an ActionListener
(line 9) to detect events on Buttons db1 and
db2 (line 40,41) that when you click them,
gets detected and acted on in the actionPerformed
method (line 55).

It means that a _single_ listener can deal
with _all_ the buttons.  Have a look over
it and see if it clears up anything for you..

--
Andrew Thompson
* http://www.PhySci.org/ Open-source software suite
* http://www.PhySci.org/codes/ Web & IT Help
* http://www.1point1C.org/ Science & Technology
The Chief - 26 Feb 2004 00:35 GMT
> ...give that teacher an apple from me.   :-)

When we started I thought that was the better way to go too. Actually,
the whole class agreed on this one.

> (chuckles)  OK, that may not be the truth,
> but if it's not, it's a lie that's amusing enough
> to get you some extra credit this end.

No, I'm not lying. He said if we make it with GUI he'd give us a few
points extra.

Thanks for the link. That was really helpful. It'll make my code a lot
simpler now. I knew that four inner classes would look gross. What if I
had to put 10 buttons? *LOL*
Andrew Harker - 25 Feb 2004 22:58 GMT
[snip]

> Can you give me a tip on how to make just *one* inner class ( that'd
> implement ActionListener ) instead of making one for each of the
> buttons. I'm thinking of making "if" checks in the actionPerformed
> method that would check which button was pressed but the problem is I
> don't know how to check for a button!?

o Look at ActionEvent ( needs more supporting code )
  but why try and make an OO prog. monolithlic

o One inner class does not mean you have to have one
  instance.  Create a class that is 'customised' by
  params to do what you want

o In your prog. it looks like anonymous class might
  be more useful, eg
    buttonHello.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
    helloWorld();
      }
    });

o Better really to separate out your design so you have
  GUI controller talking to your data model which notifies
  your display  :-)

Signature

Andrew

The Chief - 26 Feb 2004 00:39 GMT
> o In your prog. it looks like anonymous class might
>   be more useful, eg
[quoted text clipped - 3 lines]
>       }
>     });

I read about anonymous clsses in the book we use (Big Java - by Cay
Horstmann) but I never thought about them until now. :) I could try that
too. Thanks!

> o Better really to separate out your design so you have
>   GUI controller talking to your data model which notifies
>   your display  :-)

I'll certainly try to do that. It'll clear my code a lot. Or at least
make it easier to read. :) Thanks.


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.