Implemeting ActionListeners

This is my first time using the swing portion of java. I am kind of stuck on implementing the ActionListners for this assignment. The goal of this project is to create a handset that resembles a phone and have the user press the buttons which in turn will display the results in the display window. I ahve completed the majority of the assignment but I need some help with the event handling part.
I believe I need to create an action listener in both the toolbar and keypad classes and have the handset class get the results and have it set in the display.
Would some please explain why I can't use (this) in a static class.
Thanks for the help
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
//This is the Display Class and it's functions
class Display extends JTextField
     public static JTextField getDisplay()
          JFormattedTextField inputField = new JFormattedTextField();
          inputField.setEditable(false);
          return inputField;
//This is the ToolBar Class and it's functions
class ToolBar extends JPanel implements ActionListener
     public static JPanel getToolBar(){
          JPanel toolBar = new JPanel();
          toolBar.setLayout(new FlowLayout());
          JButton clear = new JButton("Clear");
          JButton dial = new JButton("Dial");
          toolBar.add(clear);
          toolBar.add(dial);
          return toolBar;
     public void actionPerformed(ActionEvent event)
          JLabel clearText;
          clear.addActionListener(this);
          System.out.println("I've been clicked");
//This is the KeyPad Class and it's functions
class KeyPad extends JPanel implements ActionListener
     public static JPanel getKeyPad(){
          JPanel keyPad = new JPanel();
          keyPad.setLayout(new GridLayout(4,3));
          JButton button[] = new JButton[9];
          for(int i=0; i<button.length; i++)
          {button[i] = new JButton(Integer.toString(i+1));
          keyPad.add(button);}
          JButton asterisk = new JButton("*");
          JButton zero = new JButton("0");
          JButton pound = new JButton("#");
          keyPad.add(asterisk);
          keyPad.add(zero);
          keyPad.add(pound);
          return keyPad;
     public void actionPerformed(ActionEvent event)
          System.out.println("I've been clicked");
//This is the Handset Class and it's functions
class Handset extends JFrame
     public Handset()
          super("Handset");
          getContentPane();
          setLayout(new BorderLayout());
          add(Display.getDisplay(), BorderLayout.NORTH);
          add(KeyPad.getKeyPad(),BorderLayout.CENTER);
          add(ToolBar.getToolBar(),BorderLayout.SOUTH);
          setSize(300, 600);
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          setVisible(true);
//This is my Driver
     public static void main(String[] args)
          new Handset();

Ok I think I may be missing something really simple. I have to create 3 classes that makes up the GUI which is brought together by the handset class. I completed this but now when I am trying to implement the event handler I am stuck do to the static placements. When I remove teh static I can't call the information from my classes. Would you please help clarify this?
//This is the KeyPad Class and it's functions
class ToolBar extends JPanel implements ActionListener
     public JPanel getToolBar(){
          JPanel toolBar = new JPanel();
          toolBar.setLayout(new FlowLayout());
          JButton clear = new JButton("Clear");
          JButton dial = new JButton("Dial");
          toolBar.add(clear);
          toolBar.add(dial);
          clear.addActionListener(this);
          return toolBar;
//This is the Handset Class and it's functions
class Handset extends JFrame
     public Handset()
          super("Handset");
          getContentPane();
          setLayout(new BorderLayout());
          add(getDisplay(), BorderLayout.NORTH);
          add(KeyPad.getKeyPad(),BorderLayout.CENTER);
          add(ToolBar.getToolBar(),BorderLayout.SOUTH);
          setSize(300, 600);
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          setVisible(true);
     }

Similar Messages

  • JSF Actions and ActionListeners with Tiles and forms

    I�m having a problem trying to use the Tiles functionality in Struts 1.1 with JSF and was wondering if anyone could help me.
    I have defined a very simple header, menu, content Tile that doesn�t involve nesting of tiles (ExampleTile_content1Level.jsp).
    I have 3 JSP pages, the first testHarness.jsp is NOT built using Tiles and is just used to load some test data into a session scoped bean using an actionListener and then forward to a Tile generated page (ExampleTile3.jsp) using a hard-coded action �applicationSummary� when a commandLink is pressed. This works fine for both the action and actionListener.
    ExampleTile3.jsp contains another commandLink that is meant to forward to another tile ExampleTile2.jsp. This also works until I try to add the <h:form> � </h:form> tag around the outside of the <h:panelGrid> tags in ExampleContent1.jsp when the action and actionListener then fail to fire and I get an �Error on Page� message in Explorer the detail of which says �Error �com_sun_rave_web_ui_appbase_renderer_CommandLinkRendererer� is null or not an object�.
    However I need a form so that I can bind UI controls to data from the bean stored in the session scope. This is only a problem when I use Tiles to define the pages. Does anyone know what I am doing wrong?
    Any help would be much appreciated.
    Tiles.xml
       <definition name="example3" path="/pages/exampleTile_content1Level.jsp" >
              <put name="headerClass" value="someStyle"/>
              <put name="menuClass" value="someStyle"/>
              <put name="contentClass" value="someStyle"/>
              <put name="header-title" value="/pages/exampleHeader.jsp" />
              <put name="menu" value="/pages/exampleMenu.jsp" />
              <put name="content" value="/pages/exampleContent1.jsp" />
       </definition>
       <definition name="example2" path="/pages/exampleTile_content1Level.jsp" >
              <put name="headerClass" value="someStyle"/>
              <put name="menuClass" value="someStyle"/>
              <put name="contentClass" value="someStyle"/>
              <put name="header" value="/pages/exampleHeader.jsp" />
              <put name="menu" value="/pages/exampleHeader.jsp" />
              <put name="content" value="/pages/exampleContent2.jsp" />
       </definition>ExampleTile3.jsp
    <f:view>
         <h:form>
              <tiles:insert definition="example3" flush="false" />
         </h:form>
    </f:view> ExampleTile2.jsp
    <f:view>
         <h:form>
              <tiles:insert definition="example2" flush="false" />
         </h:form>
    </f:view> Faces-config.xml
    <navigation-rule>
        <from-view-id>/pages/testHarness.jsp</from-view-id>
           <navigation-case>
                <from-outcome>applicationSummary</from-outcome>
                <to-view-id>/pages/exampleTile3.jsp</to-view-id>
              <redirect/>
           </navigation-case>
    </navigation-rule>
    <navigation-rule>
        <from-view-id>/pages/exampleTile3.jsp</from-view-id>
           <navigation-case>
                <from-outcome>nextPage</from-outcome>
                <to-view-id>/pages/exampleTile2.jsp</to-view-id>
                <redirect/>
           </navigation-case>
    </navigation-rule> ExampleTile_content1Level.jsp
    <tiles:importAttribute scope="request"/>
    <h:panelGrid columns="1" >
         <f:subview id="header-title">
              <tiles:insert name="header-title" flush="false" />
         </f:subview>
         <f:subview id="menu">
              <tiles:insert name="menu" flush="false" />
         </f:subview>
         <f:subview id="content">
              <tiles:insert name="content" flush="false" />
         </f:subview>
    </h:panelGrid> ExampleHeader.jsp / ExampleMenu.jsp
    <tiles:importAttribute scope="request"/>
    <h:panelGrid columns="1" columnClasses="someSyle">
         <h:outputFormat value="This is the {0}.">
              <f:param value="Header / Menu as appropriate "/>         
         </h:outputFormat>
    </h:panelGrid> ExampleContent1.jsp
    <tiles:importAttribute scope="request"/>
    <h:form>     <----- Fails with this tag included but works without it.
    <h:panelGrid columns="1" >
              <h:outputFormat value="This is the {0}.">
                   <f:param value="Content on the FIRST page"/>
              </h:outputFormat>
              <h:commandLink action="nextPage" immediate="false">
                   <h:outputText value="Click to go to next page"/>
              </h:commandLink>
    </h:panelGrid>
    </h:form> ExampleContent2.jsp
    <tiles:importAttribute scope="request"/>
    <h:panelGrid columns="1" >
         <h:outputFormat value="This is the {0}.">
              <f:param value="Content on the SECOND page"/>
         </h:outputFormat>
    </h:panelGrid>

    jezzica85 wrote:
    Hi everybody,
    I want to overload a method so it can take either 2 Actions, 2 ActionListeners, or one of each. The issue with this is that I'd have to make 4 overloaded signatures and almost identical methods, like this:
    method( action, action )
    method( action, listener )
    method( listener, action )
    method( listener, listener )
    Well, if you want to support that then you are just going to have to do suffer through it, the only shortcut I can recommend is that your method(action, listener) and method(listener, action) are the same so you only have to implement 1 and just use the other as a entry point to call the one you wish to contain the code.

  • What's the difference between Action Objects and ActionListeners

    Hello,
    in the Introduction to JSF two ways handling action are demonstrated. One way is "Combining Component Data and Action Object" the other way is "Handling Events."
    What's the difference? When do I use this or that way?
    The one thing I understand is when using "Combining Component Data and Action Objects" I use the default ActionListener and I may directly access the input values.
    TIA,
    Juergen

    Hi Juergen,
    The bottomline is 'not much', only in the details to these two approaches differ.
    The ActionListener object will have events broadcast to it for a particular object by the event mechanism in JSF. You can add one to a specific component via the f:action_listener tag. This will have your listener getting events during specific points in the request processing lifecycle (you specify via your return value for getPhaseId).
    The Action class that an actionRef reference refers to an Action that will be invoked during the invoke application phase. (see pg 71).
    I would recommend using actionRefs and Action objects wherever possible and going to ActionListeners only when you need notifications during a specific phase of the request/response cycle.
    Hope this helps,
    -bd-
    http://bill.dudney.net

  • Actions and ActionListeners as parameters

    Hi everybody,
    I want to overload a method so it can take either 2 Actions, 2 ActionListeners, or one of each. The issue with this is that I'd have to make 4 overloaded signatures and almost identical methods, like this:
    method( action, action )
    method( action, listener )
    method( listener, action )
    method( listener, listener )It seems like doing it this way would result in a lot of extra code, and hence become a real pain in the neck. So, I was curious, has anyone else either tried to do this before, or do you have any ideas as to how I might be able to do this more efficiently? When I looked at the API it didn't look like Actions and ActionListeners share a root class I can use.
    Thanks,
    Jezzica85

    jezzica85 wrote:
    Hi everybody,
    I want to overload a method so it can take either 2 Actions, 2 ActionListeners, or one of each. The issue with this is that I'd have to make 4 overloaded signatures and almost identical methods, like this:
    method( action, action )
    method( action, listener )
    method( listener, action )
    method( listener, listener )
    Well, if you want to support that then you are just going to have to do suffer through it, the only shortcut I can recommend is that your method(action, listener) and method(listener, action) are the same so you only have to implement 1 and just use the other as a entry point to call the one you wish to contain the code.

  • Removing ActionListeners after unregisterKeyboardAction is called

    I have a JPanel upon which registerKeyboardAction has been setup. At some point I would like to unregister the KeyStroke and remove the ActionListener associated with it. Is there any way to remove the ActionListener for the JComponent? Please help.
    Thanks a million !

    Blackwolf, I'm aware that unregisterKeyboardAction is obsolete but there is an old app which has some problem. I guess removing the ActionListeners would fix what I assume is a memory leak problem. Please do let me know if you know a way to handle the issue.
    Thanks for following up.

  • How to implemet rulesets withn our overwring custom rules

    Hi GRC Experts,
    Recently we have done upgrade from 4.6C to ECC 6 and upgraded the VIRSA component from VIRSA 400_46C to VIRSA 400_700.
    Before upgrade we have done some custom changes in the rule set. But after upgrade, we need to get the additional ruleset from SAP for ECC6. I am afraid if I overwrite the custom changes if I implemet the additional ruleset provided by SAP. What is the best way to get the rulesets implemented without overwriting the existing custom ones?
    Awaiting your opinions and suggessions.
    Regards
    Prasanth

    Hi Prasanth,
    Your existing data will not be deleted when you upload the new ruleset. Use the Configuration, Rule Upload option which only appends the data.
    You can ignore the ALL files, since you have the data already in the system.
    Below thread gives you some light on the basic questions of an upgrade:
    Upgrade of GRC 5.2 to GRC AC 5.3
    Regards,
    Raghu

  • JButton and ActionListeners

    I would like to change the ActionListeners registered to a JButton when the user clicks on a JButton. However there is a problem with this (see below). A typical procedure would go as follows:
    1) User clicks on button
    2) Get the appropriate listener from a list of listeners
    3) Remove the current listener(s) from the button
    4) Add the new listener(s)
    However, for some reason, the instructions of the new listener class are getting called. Is there a way of preventing this and if so, can someone please guide me in the right direction?
    Stephen

    It does not seem to happen like what you have said. Please see the test code below:
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.WindowConstants;
    public class Temp extends JFrame {
         private JButton b = null;
         public Temp() {
              super("Test");
              setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
              getContentPane().setLayout(new BorderLayout());
              b = new JButton("Click Me!");
              b.addActionListener(new ActionListener1());
              getContentPane().add(b);
              pack();
              setVisible(true);
         class ActionListener1 implements ActionListener {
              public void actionPerformed(ActionEvent evt) {
                   System.out.println("Action Listener 1");
                   b.removeActionListener(this);
                   b.addActionListener(new ActionListener2());
         class ActionListener2 implements ActionListener {
              public void actionPerformed(ActionEvent evt) {
                   System.out.println("Action Listener 2");
         public static void main(String args []) {
              new Temp();
    }The first time you click the button action listener 1 code gets executed. From the second time onwards the action listener 2 code gets executed.
    Hope this helps
    Sai Pullabhotla

  • ActionListeners and ItemListener

    Hi
    I'm using some ItemListener to detect when things are selected from a list but require a button to open a new GUI window. However, when i try and compile, the compiler says i can't use ActionListeners and ItemListeners in the same class. Is this true? Any ways i can get around it?
    Cheers

    implements ItemListener and ActionListener
    gives the following error messages:
    ListTest.java:6: '{' expected
    public class ListTest extends GUIFrame implements ItemListener and ActionListener
    ^
    ListTest.java:100: '}' expected
    ^
    ListTest.java:6: ListTest should be declared abstract; it does not define itemStateChanged(java.awt.event.ItemEvent) in ListTest
    public class ListTest extends GUIFrame implements ItemListener and ActionListener
    anymore ideas?

  • ActionListeners and ActionEvents

    Alright guys I am building myself a GUI and am using ActionListeners and ActionEvents however I'm not exactly sure what these 2 things do. I know they are used for buttons seeing as all of my buttons implement them but what specifically do they do. How does the ActionListener link to the ActionEvent???

    Check this out:
    http://java.sun.com/docs/books/tutorial/uiswing/learn/index.html
    You definitely need an overview of event-based programming to get a start with Swing. Also, make sure you understand anonymous classes (a type of inner class), as they are used extensively throughout Swing (especially in sample code), and are quite confusing if you don't know what they are!
    Nick

  • Reflection, menus, and ActionListeners

    Hi everybody,
    I was doing some reading in the Java APIs and came across reflection, and it seemed like a good idea for some menus I'm implementing, but I'm not fully sure, so I'd like some advice, please, if anyone would be willing.
    I have a lot of menus on a menu bar, and each menu item on the bar pops up a different kind of window (each window is distinct and has its own constructor; they're all encapsulated objects). My original idea was to add actionListeners to each menu item like so:
    for each item:
    item.addActionListener( new ActionListener() {
    public void actionPerformed( ActionEvent e ) {
    // the constructor for a particular window
    });The issue with that approach, as I've learned, is that this repetitive call, while it works, bloats my classes, makes them almost impossible to read, and involves a lot of cutting and pasting so it's prone to mistakes.
    So...then I stumbled on reflection. From reading the API, it appears (please correct me if I'm wrong) that you can get particular methods and constructors from classes using reflection, and then call them. This would allow me to make two small overloaded methods, to cut down on the amount of code, like so:
    public JMenuItem addConstructorAction( JMenuItem item, Constructor c ) {
    item.addActionListener( new ActionListener() {
    public void actionPerformed( ActionEvent e ) {
    c.newInstance();
    return item;
    public JMenuItem addConstructorAction( JMenuItem item, Method m ) {
    item.addActionListener( new ActionListener() {
    public void actionPerformed( ActionEvent e ) {
    m.invoke( params );
    return item;
    }So, am I right that this is how reflection works, or have I misread something? If anyone could give me advice on how to use this properly or an alternate idea, I'd appreciate it.
    Thanks,
    Jezzica85
    PS -- Sorry about the indenting on the code examples; I don't know why they didn't indent, hopefully they're still readable.
    Edited by: jezzica85 on Jan 14, 2009 7:04 AM

    Well, I didn't think this would turn into a SSCCE situation, but that's OK-- I probably should have assumed that to begin with. Anyway, here's a small program that shows what I'm talking about:
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    public class MenuTest {
         public static void main(String[] args) {
              try {
                   JFrame frame = new JFrame();
                   frame.setSize( 300, 300 );
                   frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
                   JMenuBar test = new JMenuBar();
                   JMenu menu = new JMenu( "myTest" );
                   JMenuItem item = new JMenuItem( "TestWindow test" );
                   item.addActionListener( new ActionListener() {
                        public void actionPerformed( ActionEvent ex ) {
                             new TestWindow( "TestWindow" );
                   menu.add( item );
                   JMenuItem item2 = new JMenuItem( "TestWindow2 test" );
                   item2.addActionListener( new ActionListener() {
                        public void actionPerformed( ActionEvent ex ) {
                             new TestWindow2( "TestWindow2" );
                   menu.add( item2 );
                   test.add( menu );
                   frame.setJMenuBar( test );
                   frame.setVisible( true );
              } catch( Exception e ) {
                   e.printStackTrace();
                   System.exit( -1 );
    class TestWindow extends JDialog {
         public TestWindow( String title ) {
              setTitle( title );
              setSize( 300, 300 );
              setDefaultCloseOperation( JDialog.DISPOSE_ON_CLOSE );
              setVisible( true );
    class TestWindow2 extends JDialog {
         public TestWindow2( String title ) {
              setTitle( title );
              add( new JLabel( "blah" ) );
              setSize( 300, 300 );
              setDefaultCloseOperation( JDialog.DISPOSE_ON_CLOSE );
              setVisible( true );
    }Basically, each menu item calls up a different kind of window (these are very simplified obviously). In my real application I have more than 40 different windows (because the application needs to do a lot), so repeating the actionListener code can get tedious. It doesn't look like much here, but 9 lines of code (including whitespace for readability) times at least 40 menu items is more than 350 lines of code for menu items alone. That's what I'm trying to avoid.
    Thanks,
    Jezzica85

  • Change image using actionlisteners?

    Hi i've got 35 images set in a spiral, and i am trying to make it so that when a user clicks on an image, for example if the image is facing right i want it so that when the user clicks on it, the image will change and be facing down and then if they click on it again it will change to facing down, then left and so on.
    I know in order to make it so that it responds to the user clicking i will need to use actionlistener, however i'm not sure how to code it so that it knows which image has been clicked on or how to change it to the desired image???
    Can anyone help? Or give me a useful link?
    Thanks
    Paul
    heres the code i've got so far.
    package project;
    // Description:
    // Directory: c:\myjava\teaching
    // Date: 5/4/00
    // Uses:
    // Comments:  note the convenient use of the Point object for
    //  manipulating coordinates
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.lang.*;
    import javax.swing.ImageIcon;
    public class Project extends Applet implements ActionListener{
         private Image imageUp, imageDown, imageLeft, imageRight, imageSpace;
         final int N = 37;
         Image[] image = new Image[N];
         public void init(){
    setLayout(null); // Setting layout to null
             // getting all images needed
              imageUp = getImage (getDocumentBase(), "imageUp.gif");
              imageDown = getImage (getDocumentBase(), "imageDown.gif"); 
              imageLeft = getImage (getDocumentBase(), "imageLeft.gif");
              imageRight = getImage (getDocumentBase(), "imageRight.gif");
              imageSpace = getImage(getDocumentBase(), "imageSpace.gif");
              /*for(int i=0; i < N; ++i)
                   button[i] = new Button(buttonLabel);
                   g.drawImage (imageUp, 10, 10, 100, 100, this);
         public void paint (Graphics g){
              for(int i=0; i < N; ++i){
                   for(int j = 50; j <=400; j+= 100){
                        g.drawImage (imageRight,j,10,100,40, this);
                        for(int j = 40; j <=500; j+=100){
                             g.drawImage (imageUp,10,j, 40,100, this);
                             for(int j = 150; j <350; j+=100){
                                  g.drawImage(imageRight, j, 120, 100,40, this);
                                  for(int j = 150; j <=350; j+=100){
                                       g.drawImage (imageUp,120,j, 40,100, this);
                                       for(int j = 160; j <=260; j+=100){
                                            g.drawImage (imageDown,340,j, 40,100, this);
                                            for(int j = 250; j <=270; j+=100){
                                                 g.drawImage (imageUp,210,j, 40,100, this);
                                                 for(int j = 240; j <=240; j+=100){
                                                      g.drawImage (imageLeft,j,340, 100,40, this);
                                                      for(int j = 120; j <=320; j+=100){
                                                           g.drawImage (imageLeft,j,450, 100,40, this);
                                                           for(int j = 30; j <=500; j+=100){
                                                                g.drawImage (imageLeft,j,540, 100,40, this);
                                                                for(int j = 60; j <=360; j+=100){
                                                                     g.drawImage (imageDown,420,j, 40,100, this);
                                                                     for(int j = 50; j <=450; j+=100){
                                                                          g.drawImage (imageDown,525,j, 40,100, this);
         public void actionPerformed(ActionEvent arg0) {

    Well there are a number of ways to do it and it depends alot on how large the images are, how much space there can be between them, and a bunch of stuff. Also about the direction of the image - the easiest way probably is just having several different images of the same thing that are facing different ways.
    You can place them on JButtons w/o Borders, JLabels, or on JPanels. You can add ActionListeners, MouseListeners ...
    I see that you have got images left, right, etc, so then perhaps you want to try just adding the image to a JLabel and add and ActionListener to that. When clicked, change the image on the JLabel. To keep track of direction there are a number of ways ... if it's to be in order 1, 2, 3, 4 ... add the images to a 4 dim array and iterate through it 0 -> 3 and back to 0.

  • SAP components required for implemeting SAP SRM MDM

    Hi all,
    Plz let me know , the SAP components required for implemeting SAP SRM MDM , for the following points:
    · Internal catalogs hosted and maintained by buyer?
    · Internal catalogs that are maintained by vendor (vendor will be using buyer's firewall)?
    · External catalogs hosted and maintained by vendor?
    Thanks and regards
    Harish

    Hi Harish,
    The SAP components you would be needed are
    SAP MDM5.5 or 7.1
    - MDM server
    - MDIS server
    - MDSS server
    SAP SRM5.5 or 7.0
    SAP SRM-MDM business content
    WAS engine typically used for deploying sca files given by SAP for configuring MDM as catalog. Mostly was engine of SRM is used in such case.
    If you need an integration with backend system SAP PI will be used.
    refer note
    1057316 - SRM-MDM Catalog 2.0 - Installation & configuration.
    refer article for understanding mdm catalog configuration steps
    https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/10d1bde2-699f-2910-8e86-f46bfe045fdc
    Regards,
    Abhijeet
    Edited by: abhijeet more on Apr 20, 2009 1:19 PM

  • Implemet a legacy CM repository

    Hi gurus i try to implemet a legacy CM repository but i dont know how
    when i give the jdbc driver class show like this the class name error, and i do a jdbc connector in visual administrator with te same driver, i change this parameter but the error go there:
    Error al iniciar:  Can't create legacy connection: ExtEmbeddedConnection.unlock() returned false
    Error al iniciar:  Can't create legacy connection: can't retrieve database connection for desired parameters 
    somebody have any idea
    thanks
    salvatore

    resuelto

  • Issue regarding repeating ActionListeners

    I was hoping someone can provide me guidance regarding an issue I'm experiencing.
    I am working with a JFrame containing a JTable (one column with multiple rows) on one side and a JPanel on the other. The JPanel is simply a form I've created to display information utilizing the SpringLayout. The JPanel also contains multiple ActionListeners to display various types of information.
    By selecting a row in the JTable, the JPanel will refresh and display specific information regarding the selected item. For the most part, it is working, however, I found an issue I just can't seem to resolve. If I were to select 3 different rows in the JTable, the JPanel will properly refresh and display information relating to the 3 different JTable selections. However, if I were to start typing in a JTextField (in the JPanel) containing a KeyListener, the KeyEvent will repeat 3 times. If I were to select 8 different rows in the JTable and start typing in a JTextField containing a KeyListener, the KeyEvent will repeat 8 times, and so on.
    This is not only the case with the KeyListener, but also with ActionListeners. It seems like the number of rows I select in the JTable, the Listeners will repeat the same number of times.
    I initially thought it was due to multiple objects that were being created, but I changed the implemented classes to utilize singletons with the same result.
    I hope this made sense, please let me know if you'd like me to explain further.
    Anyone have any idea what may be causing this? If so, any direction or guidance would be much appreciated.
    Thank you in advance.

    jduprez,
    I really appreciate your reply. I have provided some code below which essentially gives a brief overview of where my issue is occurring.
    After reviewing the code tonight, the method: viewObjectInformation() is being called every time a row is selected. Because of that, the ObjectDetail class is being initialized exactly the same number of times a row is selected. Do you think this is the reason why I'm experiencing multiple KeyEvents?
    If so, how would you recommend initializing JTextField that represents good coding practice?
    public class ObjectTable extends JPanel implements ActionListener {
        private DefaultTableModel model = new DefaultTableModel();
        private JTable table;
        private JFrame frame;
        public ObjectTable(JFrame frame) {
            this.frame = frame;
            table = new JTable(model);
            table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            table.getSelectionModel().addListSelectionListener(new RowListener());
            JScrollPane scrollPane = new JScrollPane(table);
            add(scrollPane);
        public void addRowToTable(ImportFile importFile) {
            // code to add rows to the table
        private class RowListener implements ListSelectionListener {
            public void valueChanged(ListSelectionEvent event) {
                if (event.getValueIsAdjusting()) {
                    return;
                try {
                    ObjectDetail objectDetail = ObjectDetail.getInstance();
                    objectDetail.viewObjectInformation();
                } catch (ArrayIndexOutOfBoundsException arobe) {
                     // catch the exception
    public class ObjectDetail extends JPanel implements ActionListener {
        private static ObjectDetail instance = null;
        private JLabel objectLabel;
        private JTextField objectTextField;
        public static ObjectDetail getInstance() {
            if (instance == null) {
                instance = new ObjectDetail();
            return instance;
        protected ObjectDetail () {
            // initializations
            objectLabel = new JLabel("Object Name: ");
            objectTextField = new JTextField("", 30);
        public void viewObjectInformation() {
            objectTextField.setEditable(true);
            objectTextField.setText(obj.getName);
            objectTextField.addKeyListener(ObjectKeyListener);
            // implement layout constraints and add to layout
        KeyListener ObjectKeyListener = new KeyListener() {
            public void keyTyped(KeyEvent e) {
                logger.info("KEYTYPED: e.getKeyCode(): " + e.getKeyCode() +
                                " - e.getKeyChar(): " + e.getKeyChar());
            public void keyReleased(KeyEvent e) {
                logger.info("KEYRELEASED: e.getKeyCode(): " + e.getKeyCode() +
                                " - e.getKeyChar(): " + e.getKeyChar());
            public void keyPressed(KeyEvent e) {
                logger.info("KEYPRESSED: e.getKeyCode(): " + e.getKeyCode() +
                                " - e.getKeyChar(): " + e.getKeyChar());
    }Edited by: alexkcha on Nov 23, 2009 9:28 PM

  • Regarding nested actionlisteners

    i am relatively new to these forums...and so i have no idea if the help i am going to ask for has already been discussed or exists.....
    i am constructing a music store using swings...i am stuck on a problem where..
    when i select a category of music using the JButton ,it should display the titles of the music cds available with the store..in the form of checkbox group...on selecting the paricular title...and then clicking another JButton called"add to cart", this title should be added into a new Jframe..
    i have created the new Frame and attached it to "add to cart" button...
    i have been succesful in displaying the titles from the JButton ..but i am unable to add the selected title to the new Frame using "add to cart" button..
    i was wondering if nested actionlisteners can be used here to overcome this problem.....
    please help me out....

    1) Your "Shopping Cart" frame will need a method like "addItemToCart".
    2) In your "Main Frame" when you click on the "Add Item To Cart" button the ActionListener will simply get the selected item and then invoke the shoppingCart.addItemToCart() method.
    There is no need for nested action listeners.

Maybe you are looking for

  • Looking for the "good" calendar - Treo 755p

    Last week my Treo started cycling through the reset screens (Access and Palm). I tried soft resets and warm resets until I couldn't stand it anymore, and finally did a hard reset, wiping everything. I spent the next three days testing how things work

  • Tabular Control - Set a tab to default?

    My program currently running with tabular control, has 4 tabs, but always starts on tab 3.  Is it possible to redefine another as the default startup tab? Everytime I save and build the file, I make sure to keep it on tab 1 but doesn't help. LV7.1, L

  • Optimizing the Query  joining two tables multiple times

    Hi all, I need to formulate a query where I want to get data from two tables.Here are the table structures and sample data. Table1 id firstname lastname accountnumber 1 Sridh Peter SP456 2 Gane San SS667 3 Sway patel PP345 Table 2 id attributename at

  • Time machine backup directories are split up using a network drive

    I have my time machine drive connected to my airport extreme base station. When using the migration assistant to move my data to a new machine I noticed that the data I copied over was several months out of date, even though time machine has been run

  • N91-8GB firmware/the problems which have to be fix...

    When will nokia be removing a firmware for n91 8gb?? 1can Hard drive stoped working.it says 'hard drive not available'. 2:defragmenting hdd does not go above 3%. 3:New visualizations 4:Gallery take time to open(images too) any more problems abt n91 8