InnerClass Actionlistener problem

hello,
i am stuck on this piece of code and i think somebody here will be able to help me out :).
i have these classes.
ButtonPanel, Test.
in the buttonpanel i have a few buttons, but the actionlistener is an innerClass in Test.
when i want to add one of my actionlisteners in my ButtonPanel class the compiler cannot resolve symbol.
this is a snippet of code:
the buttons in buttonpanel class:
btnStart = new JButton("Start");
btnStart.addActionListener(new startActionListener());
btnStop = new JButton("Stop");
btnStop.addActionListener(new stopActionListener());
btnTest = new JButton("Test");
btnTest.addActionListener(new testActionListener());
The actionlisteners in Test class:
public class startActionListener implements ActionListener{
          public void actionPerformed(ActionEvent e){
               java.awt.Toolkit.getDefaultToolkit().beep();//werkt niet
     public class stopActionListener implements ActionListener{
          public void actionPerformed(ActionEvent e){
               java.awt.Toolkit.getDefaultToolkit().beep();//werkt niet
     public class testActionListener implements ActionListener{
          public void actionPerformed(ActionEvent e){
               java.awt.Toolkit.getDefaultToolkit().beep();//werkt niet
so basically its just how do use actionlisteners in the class that extends from the JFrame, in stead of in de ButtonPanel class where the buttons are?

There are several options.
If the classes don't at all refer to the class their nested in (as your examples seem to be), then just make them top-level, and refer to them anywhere you want.
Or you could create anonymous inner classes, with identical functonality, in your ButtonPanel.
Or you could add the listeners in a different place (say in a method of Test).
The way you should go, depends on the details of the implementation.
When you post code, please wrap it in [code][/code] tags.

Similar Messages

  • ActionListener Problem - Event not triggering properly

    Hello,
    I have slight problem ith action listeners. Below is an exercise from a book on java i'm reading. I have constructed rectangle with 3 circles inside.
    When the button in one panel is pushed the colors of these cicles should change from green,black,black to black,yellow,black to black,black,red and start over.
    When the button is clicked the event isn't triggered. However when I push the button and click the frame of the window the colors change.
    I would be grateful if anyone could explain why this is happening?
    // Zepang
    import javax.swing.*;
    import java.awt.*;
    public class Pp415
         public static void main(String [] args)
              JFrame frame = new JFrame("Traffic Lights");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              Prime panel = new Prime();
              frame.getContentPane().add(panel);
              frame.pack();
              frame.setVisible(true);
         JButton lightButton = new JButton("Change the Lights!");
         lightButton.addActionListener(this);
         buttonLight.add(lightButton);
            add(buttonLight);
         add(light);
         int color = 0;
         public void actionPerformed (ActionEvent event)
              Color g = light.getGreenLight();
              Color y=  light.getYellowLight();
              Color r=  light.getRedLight();
              if (g.equals(Color.green))
                   light.setGreenLight(Color.black);
                   light.setYellowLight(Color.yellow);
              if (y.equals(Color.yellow))
                   light.setYellowLight(Color.black);
                   light.setRedLight(Color.red);
              if (r.equals(Color.red))
                   light.setRedLight(Color.black);
                   light.setGreenLight(Color.green);
    import javax.swing.*;
    import java.awt.*;
    class TrafficLight extends JPanel
         Color redLight = Color.black;
         Color yellowLight = Color.black;
         Color greenLight = Color.green;
    public TrafficLight()
         setBackground(Color.black);
         setPreferredSize(new Dimension (200,300));
      public void setRedLight(Color c)
         redLight = c;
      public void setYellowLight(Color c)
         yellowLight = c;
      public void setGreenLight(Color c)
         greenLight = c;
      public Color getRedLight()
      return redLight;
      public Color getGreenLight()
      return greenLight;
      public Color getYellowLight()
      return yellowLight;
      public void paintComponent(Graphics page)
         final int C = 25;
         page.setColor(Color.blue);
         page.fillRect(C, C, 100, 250);
         page.setColor(greenLight);
         page.fillOval(C+10,C+5,80,80);
         page.setColor(yellowLight);
         page.fillOval(C+10,C+90,80,80);
         page.setColor(redLight);
         page.fillOval(C+10,C+170,80,80);
    }Edited by: Zepang on Dec 4, 2008 4:24 PM
    Edited by: Zepang on Dec 4, 2008 4:25 PM

    I don't in general do GUI stuff. But I can see for sure that you're never telling the system that it needs to repaint when you change state. That's why it doesn't show up until you cause an external event causing it to repaint itself, such as resizing the frame or dragging another window across the window.

  • ActionListener problem with the String and TextField in different packages.

    i have the following string in the first file. This String text is changing values with the execution of the file
    class Baby {
    public static String Update="";
    void tata() {
    Update="Connecting...";
    Update="Authenticating...";
    Update="Getting data...";
    ....I want with the help (obviously) by an Action Listener to update constantly the value of a TextField. The Action Listener and the TextField are located both in another file and class.
    UpdateTextField.addActionListener(actionListener);
    UpdateTextField.setText(Baby.Update);Is it possible? I cant find a solution.
    Any help would be appreciated.

    Well that is really something... If it wasn't for the<tt> Click here and press <Enter>, </tt>the GUI would have been soooo counter-ituitive. :)
    I was actually trying to steer OP away from the ActionEvents in the first place. Frankly, I just see no need for it in his app. I was thinking along the lines of ...
    import javax.swing.*;
    public class Test
      JLabel label;
      public Test(){
        label = new JLabel("Initializing...");
        JFrame f = new JFrame();
        f.getContentPane().add(label, "Center");
        f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
        f.setBounds(0, 0, 200, 60);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
        LongProcess process = new LongProcess();
        process.start();
      class LongProcess extends Thread
        int[] waitTimes = new int[]{
          2000, 500, 2000, 500, 5000, 1000};
        String[] operations = new String[]{
          "Starting", "Connecting", "Connected",
          "Reading", "Processing", "Done"};
        public void run(){
          try{
            for(int i = 0; i < waitTimes.length; i++){
              sleep(waitTimes);
    updateLabel(i);
    catch(InterruptedException ioe){
    ioe.printStackTrace();
    updateLabel(operations.length-1);
    protected void updateLabel(final int index){
    SwingUtilities.invokeLater(new Runnable(){
    public void run(){
    label.setText(operations[index] + "...");
    public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    new Test();
    }... see how this approach rids the application from any Events being fired? See how OP can put his network connections and file reads on a separate thread -- then update the JLabel via SwingUtilities.invokeLater()? In my opinion, this would be a much better outline to OP's situation.
    Disclaimer: I'm not saying this is the only approach, I'm sure there are other solutions -- and may even be better than this.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Actionlistener problem very urgent

    please i need help urgently,
    my bill and clear buttons works alright but when i click the clear button and the text is cleared the bill button does not work any more. please help!!!

    Ditto. I'll be gald to help but you aven't given me anything to go on.

  • JComboBox, ItemListener, ActionListener questions

    Hallo,
    I have some troubles with a JComboBox:
    I add an ActionListener and an ItemListener to it.
    1.ActionListener problems: if the combo is editable then entering value in the editor and clicling Enter fires 2 actionEvents
    with the combo as source. The difference I noticedbetween them is the actionCommand value:
    "comboBoxChanged"(as from normal select) and "comboBoxEdited"(because of changed value in editor)
    2. ItemListener problem: everything is OK selecting with mouse but if I type text/editable again/ and press enter only the
    ActionListener is called(yes, KeyListener in editor will help). The users also want to point a value with the mouse and press enter on it.
    Again only the action is called.
    Now the questions:
    1.Can I rely on the texts in actionCommand? What should I compare them to if "Yes"/are they localized?/
    2. Is there an easier way then adding a KeyListener to the editor and list component of the combo to catch the Enter if ActionListener cannot be used?
    Thanks in advance
    Mike

    About my question 1: in source of JComboBox these text values seem to be hard-coded.
    So I will use them for now. But I still would appreciate other ideas.
    Thanks
    Mike

  • Question about GridBagConstraints

    Hi,
    As the title of this thread suggests, I have some issued with the GridBagConstraints. I try to set the width and height of a JPanel (that uses said GridBagConstraints), but the JPanel decides to do it in its own way. Instead of listening to my suggestion (see me setting the size of descriptionPanel in my code in the second piece of code), it sets the size of my TlsProblem to the size of the JLabel (see theDescription in MyMain) I put in it.
    Here is my code. First the main:
    import javax.swing.*;
    import java.awt.*;
    public class MyMain {
         static int WIDTH = 1280;
         static int HEIGHT = 800;
         public static void main(String[] args) {
              JFrame frame = new JFrame();
              Container pane = frame.getContentPane();
              frame.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setTitle("ProblemPainter");
              Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
              frame.setBounds (0, 0, dimension.width, dimension.height - 200);
              String theOrganization = "Organization name";
              String theDescription = "10:09:30 ERR expected string or buffer, but that is not everyting, as this problem description is extremely long. And as I am chatty, I add some more length";
              String theIdentifier = "3549";
              String theSeverity = "ERR";
              String theLink = "https://foo.domain.us/mon/index.php?fuseaction=orgtree_monitor_check.dsp_edit&mc_id=3549&org_id=17";
              String theTimeStamp = "10:09:30";
              String theCollector = "28";
              Problem problem = new Problem (theOrganization, theDescription, theIdentifier,
                        theSeverity, theLink, theTimeStamp, theCollector);
              TlsProblem tlsProblem = new TlsProblem (problem);
              frame.add(tlsProblem);
              // frame.pack();
              frame.setVisible(true);
    }Next the code of TlsProblem, that seems to have a life of its own:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TlsProblem extends JPanel
                                implements ActionListener {
         Problem problem;
         JLabel organization;
         JLabel description;
         JLabel timeStamp;
         JLabel severity;
         JButton status;
         JButton csd;
         JButton engineer;
         static int WIDTH = 1280;
         static int HEIGHT = 800;
         static int INSETS = 2;
         public TlsProblem (Problem theProblem) {
              problem = theProblem;
              organization = new JLabel("Organization: " + problem.getOrganization(), SwingConstants.LEFT);
              description = new JLabel("Description: " + problem.getDescription(), SwingConstants.LEFT);
              timeStamp = new JLabel(problem.getTimeStamp(), SwingConstants.LEFT);
              timeStamp.setAlignmentX(Component.CENTER_ALIGNMENT);
              severity = new JLabel(problem.getSeverity(), SwingConstants.LEFT);
              severity.setAlignmentX(Component.CENTER_ALIGNMENT);
              status = new JButton (problem.getState());
              status.setAlignmentX(SwingConstants.CENTER);
              csd = new JButton ("CSD: ");
              csd.setHorizontalAlignment(SwingConstants.LEFT);
              engineer = new JButton ("Beheer: ");
              engineer.setHorizontalAlignment(SwingConstants.LEFT);
              setUp();
         private void setUp () {
              JComponent component = createComponent();
              add(component);
              setVisible (true);
         private JComponent createComponent () {
              JPanel panel = new JPanel();
              panel.setBackground(Color.WHITE);
              panel.setSize(WIDTH, HEIGHT/10);
              logState ("createComponent: panel has dimension " + panel.getSize());
              panel.setLayout(new GridBagLayout());
              panel.setBorder(BorderFactory.createRaisedBevelBorder());
              GridBagConstraints constraints = new GridBagConstraints();
              // Organization name. Fill up available space horizontal
              constraints.fill = GridBagConstraints.HORIZONTAL;
              constraints.gridx = 0;
              constraints.gridy = 0;
              constraints.gridheight = 1;
              constraints.gridwidth = 2; // Take up 2 columns of space
              panel.add(organization, constraints);
              // Description of the problem. Fill up space both horizontal and vertical
              JPanel descriptionPanel = new JPanel();
              descriptionPanel.setOpaque(false);
              descriptionPanel.setSize(WIDTH/4, HEIGHT/10);
              logState ("createComponent: descriptionPanel has dimension " + descriptionPanel.getSize());
              constraints.fill = GridBagConstraints.BOTH;
              constraints.gridx = 0;
              constraints.gridy = 1;
              constraints.gridwidth = 2;
              constraints.gridheight = 2;// Take up 2 rows of space
              descriptionPanel.add(description);
              panel.add(descriptionPanel, constraints);
              logState ("createComponent: panel has dimension " + panel.getSize());
              // Time stamp of creation of the problem
              constraints.fill = GridBagConstraints.HORIZONTAL;
              constraints.gridx = 3;
              constraints.gridy = 0;
              constraints.gridwidth = 1;
              constraints.gridheight = 1;
              panel.add(timeStamp, constraints);
              // Severity of the problem
              constraints.gridx = 3;
              constraints.gridy = 1;
              constraints.gridwidth = 1;
              constraints.gridheight = 1;
              panel.add(severity, constraints);
              // Status of the problem
              constraints.gridx = 3;
              constraints.gridy = 2;
              constraints.gridwidth = 1;
              constraints.gridheight = 1;
              panel.add(status, constraints);
              // CSD engineer following the problem
              constraints.gridx = 4;
              constraints.gridy = 0;
              constraints.gridwidth = 1;
              constraints.gridheight = 1;
              panel.add(csd, constraints);
              // Administrator engineer following the problem
              constraints.gridx = 4;
              constraints.gridy = 1;
              constraints.gridwidth = 1;
              constraints.gridheight = 1;
              panel.add(engineer, constraints);
              return panel;
         public void actionPerformed(ActionEvent event) {
              String command = event.getActionCommand();
         public void logState (String text) {
              System.out.println ("TlsProblem." + text);
    public class Problem extends JPanel {
         private String organization;
         private String description;
         private String identifier;
         private String link;
         private String severity;
         private String state;
         private String timeStamp;
         private String collector;
         private int width;
         private int height;
         public Problem (String theOrganization, String theDescription, String theIdentifier,
                   String theSeverity, String theLink, String theTimeStamp, String theCollector) {
              organization = theOrganization;
              description  = theDescription;
              identifier   = theIdentifier;
              severity     = theSeverity;
              link         = theLink;
              timeStamp    = theTimeStamp;
              collector    = theCollector;
              state = NEW;
         public String getOrganization () {
              return organization;
         public String getDescription () {
              return description;
         public String getIdentifier () {
              return identifier;
         public String getSeverity () {
              return severity;
         public String getState () {
              return state;
         public String getTimeStamp () {
              return timeStamp;
         public String getCollector () {
              return collector;
         public String getLink () {
              return link;
    }What do I need to change in this code so I can set the size of the elements of my TlsProblem to my hearths content?
    TIA
    Abel

    class TlsProblem extends JPanel  implements ActionListener {
        static int WIDTH = Toolkit.getDefaultToolkit().getScreenSize().width;
        static int HEIGHT = Toolkit.getDefaultToolkit().getScreenSize().height;
        private JComponent createComponent() {
            JPanel panel = new JPanel();
            panel.setBackground(Color.WHITE);
            panel.setPreferredSize(new Dimension(WIDTH-20, HEIGHT / 5));
            logState("createComponent: panel has dimension " + panel.getPreferredSize());
            panel.setLayout(new GridBagLayout());
            panel.setBorder(BorderFactory.createRaisedBevelBorder());
            GridBagConstraints constraints = new GridBagConstraints();
            // Organization name. Fill up available space horizontal
            constraints.fill = GridBagConstraints.HORIZONTAL;
            constraints.gridx = 0;
            constraints.gridy = 0;
            constraints.gridheight = 1;
            constraints.gridwidth = 2; // Take up 2 columns of space
            constraints.weightx = constraints.gridwidth;
            constraints.weighty = constraints.gridheight;
            panel.add(organization, constraints);
            // Description of the problem. Fill up space both horizontal and vertical
            JPanel descriptionPanel = new JPanel();
            descriptionPanel.setOpaque(false);
            descriptionPanel.setPreferredSize(new Dimension(WIDTH / 2, HEIGHT / 10));
            logState("createComponent: descriptionPanel has dimension " + descriptionPanel.getPreferredSize());
            constraints.fill = GridBagConstraints.BOTH;
            constraints.gridx = 0;
            constraints.gridy = 1;
            constraints.gridwidth = 2;
            constraints.gridheight = 2;// Take up 2 rows of space
            constraints.weightx = constraints.gridwidth;
            constraints.weighty = constraints.gridheight;
            description.setPreferredSize(descriptionPanel.getPreferredSize());
            description.setText("<html>"+description.getText());
            descriptionPanel.add(description);
            panel.add(descriptionPanel, constraints);
            logState("createComponent: panel has dimension " + panel.getPreferredSize());
            // Time stamp of creation of the problem
            constraints.fill = GridBagConstraints.HORIZONTAL;
            constraints.gridx = 3;
            constraints.gridy = 0;
            constraints.gridwidth = 1;
            constraints.gridheight = 1;
            constraints.weightx = constraints.gridwidth;
            constraints.weighty = constraints.gridheight;
            panel.add(timeStamp, constraints);
            // Severity of the problem
            constraints.gridx = 3;
            constraints.gridy = 1;
            constraints.gridwidth = 1;
            constraints.gridheight = 1;
            constraints.weightx = constraints.gridwidth;
            constraints.weighty = constraints.gridheight;
            panel.add(severity, constraints);
            // Status of the problem
            constraints.gridx = 3;
            constraints.gridy = 2;
            constraints.gridwidth = 1;
            constraints.gridheight = 1;
            constraints.weightx = constraints.gridwidth;
            constraints.weighty = constraints.gridheight;
            panel.add(status, constraints);
            // CSD engineer following the problem
            constraints.gridx = 4;
            constraints.gridy = 0;
            constraints.gridwidth = 1;
            constraints.gridheight = 1;
            constraints.weightx = constraints.gridwidth;
            constraints.weighty = constraints.gridheight;
            panel.add(csd, constraints);
            // Administrator engineer following the problem
            constraints.gridx = 4;
            constraints.gridy = 1;
            constraints.gridwidth = 1;
            constraints.gridheight = 1;
            constraints.weightx = constraints.gridwidth;
            constraints.weighty = constraints.gridheight;
            panel.add(engineer, constraints);
            return panel;
    }

  • Facing problem inside the implementation of ActionListener

    Hi, I don't understand what the problem is. Please go through the following code. The explanation of the problem is documented.
    Any kind of help is appreciated.
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import javax.swing.JButton;
    import java.awt.BorderLayout;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.JOptionPane;
    * Class Test is intended for receiving a String input from the user and
    * manipulating the input string later in some other methods. So the input
    * string has to be stored for later use.
    * Whenever an action takes place in JTextField or JButton (OK button) component,
    * the corresponding ActionListener's actionPerformed() method assigns the
    * user input to 'userInput' referene variable. This was assured when I placed
    *              JOptionPane.showMessageDialog(frame, userInput);
    * right after the assignment statement. But when I cut and pasted the above
    * statement right after the getUserInput() method call (in constructor's body)
    * it showed null string.
    * WHY & HOW this happens?
    * I could have implemented this application with the help of JOptionPane's
    * showInputDialog() method. But I just want to know what the problem is if
    * I have tried in this way.
    public class Test {
         * String that the user types
        private String userInput;
         * Text field that contains the user input.
        private JTextField inputTextField;
         * Frame that contains all other components
        private JFrame frame;
        public Test() {
            prepareFrame();
            getUserInput();
            // shows null, why?????
            JOptionPane.showMessageDialog(frame, userInput);
            // some other methods goes here that uses the input string....
            // methodA();
            // methodB();
         * Creates the frame and sets some of its properties.
        private void prepareFrame() {
            frame = new JFrame("Experiment with ActionListener");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(500, 300);
            frame.setVisible(false);
         * Receives user input and stores the reference to user input in userInput.
        private void getUserInput() {
            // Create sub-components
            JLabel promptLabel = new JLabel("Enter a string: ");
            inputTextField = new JTextField(20);
            JButton okButton = new JButton("OK");
            JButton cancelButton = new JButton("Cancel");
            // Add listeners
            inputTextField.addActionListener(new TextFieldHandler());
            okButton.addActionListener(new OkButtonHandler());
            cancelButton.addActionListener(new CancelButtonHandler());
            // Create a panel to contain the sub-components
            JPanel panel = new JPanel();
            // Add the sub-components to the panel
            panel.add(promptLabel);
            panel.add(inputTextField);
            panel.add(okButton);
            panel.add(cancelButton);
            frame.add(panel, BorderLayout.NORTH);
            frame.validate();
            frame.setVisible(true);
         * Event handler for text field that contains user input.
        private class TextFieldHandler
                implements ActionListener {
            public void actionPerformed(ActionEvent event) {
                userInput = event.getActionCommand();
                // works fine if the user input is shown here.
                // JOptionPane.showMessageDialog(frame, userInput);
         * Event handler for OK button
        private class OkButtonHandler
                implements ActionListener {
            public void actionPerformed(ActionEvent event) {
                userInput = inputTextField.getText();
                // works fine if the user input is shown here.
                // JOptionPane.showMessageDialog(frame, userInput);
         * Event handler for Cancel button
        private class CancelButtonHandler
                implements ActionListener {
            public void actionPerformed(ActionEvent event) {
                System.exit(0);
        public static void main(String[] args) {
            new Test();
    }

    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import javax.swing.JButton;
    import java.awt.BorderLayout;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.JOptionPane;
    public class T {
        private String userInput;
        private JTextField inputTextField;
        private JFrame frame;
        public T() {
            prepareFrame();
            getUserInput();
            // shows null, why?????
            // userInput is null because it has not been given a value
            // you can give it a value in the declaration as a member
            // variable above or here in your class constructor
            System.out.println("userInput = " + userInput);
            JOptionPane.showMessageDialog(frame, userInput);
            // some other methods goes here that uses the input string....
            // methodA();
            // methodB();
        private void prepareFrame() {
            frame = new JFrame("Experiment with ActionListener");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(500, 300);
            frame.setVisible(false);
        private void getUserInput() {
            // Create sub-components
            JLabel promptLabel = new JLabel("Enter a string: ");
            inputTextField = new JTextField(20);
            JButton okButton = new JButton("OK");
            JButton cancelButton = new JButton("Cancel");
            // Add listeners
            inputTextField.addActionListener(new TextFieldHandler());
            okButton.addActionListener(new OkButtonHandler());
            cancelButton.addActionListener(new CancelButtonHandler());
            // Create a panel to contain the sub-components
            JPanel panel = new JPanel();
            // Add the sub-components to the panel
            panel.add(promptLabel);
            panel.add(inputTextField);
            panel.add(okButton);
            panel.add(cancelButton);
            frame.add(panel, BorderLayout.NORTH);
            frame.validate();
            frame.setVisible(true);
        private class TextFieldHandler implements ActionListener {
            public void actionPerformed(ActionEvent event) {
                // userInput is given a value here so it is no longer null
                userInput = event.getActionCommand();
                // works fine if the user input is shown here.
                System.out.println("userInput = " + userInput);
                JOptionPane.showMessageDialog(frame, userInput);
        private class OkButtonHandler implements ActionListener {
            public void actionPerformed(ActionEvent event) {
                // userInput is given a value here so it is no longer null
                userInput = inputTextField.getText();
                // works fine if the user input is shown here.
                System.out.println("userInput = " + userInput);
                JOptionPane.showMessageDialog(frame, userInput);
        private class CancelButtonHandler implements ActionListener {
            public void actionPerformed(ActionEvent event) {
                System.exit(0);
        public static void main(String[] args) {
            new T();
    }

  • Problem disabling JButton in ActionListener after setText of JLabel

    What i want is when i click View to see the label say "Viewing ..." and in the same time the btnView (View Button) to be disabled.
    I want the same with the other 2 buttons.
    My problem is in ActionListener of the button. It only half works.
    I cannot disable (setEnabled(false)) the button after it is pressed and showing the JLabel.
    The code i cannot run is the 3 buttons setEnabled (2 in comments).
    Any light?
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    class BTester extends JFrame implements ActionListener { 
         JButton btnView, btnBook, btnSearch;
         BTester(){     //Constructor
              JPanel p = new JPanel();
         JButton btnView = new JButton( "View" );
         btnView.setActionCommand( "View" );
         btnView.addActionListener(this);
         JButton btnBook = new JButton( "Book" );
         btnBook.setActionCommand( "Book" );
         btnBook.addActionListener(this);
         JButton btnSearch = new JButton( "Search" );
         btnSearch.setActionCommand( "Search" );
         btnSearch.addActionListener(this);
         p.add(btnView);
         p.add(btnBook);
         p.add(btnSearch);
         getContentPane().add(show, "North"); //put text up
    getContentPane().add(p, "South"); //put panel of buttons down
    setSize(400,200);
    setVisible(true);
    setTitle("INITIAL BUTTON TESTER");
    show.setFont(new Font("Tahoma",Font.BOLD,20));
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     
         //actionPerformed implemented (overrided)
         public void actionPerformed( ActionEvent ae) {
    String actionName = ae.getActionCommand().trim();
    if( actionName.equals( "View" ) ) {
    show.setText("Viewing ...");
         btnView.setEnabled(false); // The line of problem
    //btnBook.setEnabled(true);
    //btnSearch.setEnabled(true);
    else if( actionName.equals( "Book" ) ) {
    show.setText("Booking ...");
    //btnView.setEnabled(true);
    //btnBook.setEnabled(false);
    //btnSearch.setEnabled(true);
    else if( actionName.equals( "Search" ) ) {
    show.setText("Searching ...");
    //btnView.setEnabled(true);
    //btnBook.setEnabled(true);
    //btnSearch.setEnabled(false);
    } //end actionPerformed
         private JLabel show = new JLabel( "Press a button ... " );
    public static void main(String[] args) { 
         new BTester();
    } // End BTester class

    1. Use code formatting when posting code.
    2. You have a Null Pointer Exception since in your constructor you create the JButtons and assign them to a local variable instead of the class member.
    Change this
    JButton btnView = new JButton( "View" );to:
    btnView = new JButton( "View" );

  • Problem in subclass with ActionListener

    Hello,
    I need to program two forms which are identical except for the actions their buttons should do and some other minor differences, therefore I made a superclass for one of the forms and then extended it to build the other form. I messed up and wrote the ActionListener's as inner classes inside the superclass. Now, the buttons in the subclass react exactly the same as the buttons in the superclass. A solution I can think of is to forget about extending the class and making a different class for each form, but this would mean having two different classes with very similar code, therefore I'm sure there is a more elegant solution. Any ideas?
    Thank you,
    Alfredo

    I believe that writing the ActionListeners as separate classes won't fix the problem, since the same ActionListeners would be called for each of the forms. The problem is how do I make the buttons in the subclass call different ActionListeners from the ones in the superclass.

  • Newbie: ActionListener visibility problem

    Hello,
    i'm new to java, and i'm working on a simple small project.
    I've got a problem with the visability of an object.
    Maybe you have a look at my code:
    Used Class
    public class System1T1P extends xyz {
    public void switchOn() {
    // Important READ HERE
    // Important READ HERE
    // Important READ HERE
    System.out.print("old"); // for debug
    // Important READ HERE
    // Important READ HERE
    // Important READ HERE
    public void start() {
    public void update() {
    // has to be implementated
    class TimerListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                 update();
    Timer oTimer = new javax.swing.Timer(1000, new TimerListener());
    }Main Class
    public class GUI_1T1P extends GUI_General {
         // System
         private System1T1P oSys1T1P = new System1T1P() {
              public void update() {
              public void switchOn() {
                   // Important READ HERE
                   // Important READ HERE
                   // Important READ HERE
                   System.out.print("mimi"); // for debug it returns something else
                   // Important READ HERE
                   // Important READ HERE
                   // Important READ HERE
         // Screen Size
         GraphicsEnvironment oGraphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
         Rectangle oRectangle_ScreenSize = oGraphicsEnvironment.getMaximumWindowBounds();
         // Gui
         JFrame oJFrame;
         JButton oJButton_exit;
         JButton oJButton_on;
         JButton oJButton_running;
         GC_1T1P oGC_1T1P;
         public GUI_1T1P() {
              // Important READ HERE
              // Important READ HERE
              // Important READ HERE
              oSys1T1P.switchOn(); // Returns "mimi" to out
              // Important READ HERE
              // Important READ HERE
              // Important READ HERE
              oJFrame = new JFrame("System 1T1P");
              oJFrame.getContentPane().setLayout(null);
              oJFrame.addWindowListener(new WindowListener() {
                   public void windowClosed(WindowEvent arg0) {}
                   public void windowActivated(WindowEvent e) {}
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
                   public void windowDeactivated(WindowEvent e) {}
                   public void windowDeiconified(WindowEvent e) {}
                   public void windowIconified(WindowEvent e) {}
                   public void windowOpened(WindowEvent e) {}
              oJButton_exit = new JButton("Hide");
              oJButton_exit.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent arg0) {
                        hide(); // works without problems
              oJButton_on = new JButton("Activate");
              oJButton_on.addActionListener( new ActionListener() {
                   public void actionPerformed(ActionEvent arg0) {
                        // IMPORTANT This is the Problem
                        GUI_1T1P.this.oSys1T1P.switchOn(); // returns "old" instead of "mimi"
                        // seems to be a completely diffrent instance of oSys1T1P
                        // oSys1T1P.switchOn(); // returns also "old"
              oJButton_running = new JButton("Run");
              oJButton_running.addActionListener( new ActionListener() {
                   public void actionPerformed(ActionEvent arg0) {
                        // IMPORTANT This is the Problem
                        GUI_1T1P.this.oSys1T1P.start(); // also uses the wrong instance
                        // oSys1T1P.start(); // also uses the wrong instance
              // set positions
              // add elements to window
              // finalize
              oJFrame.pack();
              // init window
         public void hide() {
              oJFrame.setVisible(false);
    }maybe its easy to you but i'm researching for it about two days ...
    thank you for reading and answering.
    Nem

    okay then i ask it in the short way
    public class MyClass extends AbstractClass {
        // System
        private AnyClass objectOfAnyClass = new AnyClass() {       
            public void aFunction() { // this is a redefined function
                 System.out.print("new output"); //This was System.out.print("old output"); before
    void bFunc() {
       objectOfAnyClass.aFunction(); //By calling aFunction here it prints "new output"
            ActionListener al = new ActionListener() {
                public void actionPerformed(ActionEvent arg0) {
                     objectOfAnyClass.aFunction(); // if i call it from here it prints "old output"
    // Part where al is used
    }  My question is simply: why does it print "old output" inside of the actionlistener?
    Thanks and sorry ;(
    Edited by: Nemcija on Nov 12, 2008 5:53 AM

  • Problem with ActionListener firing multiple times

    I have a GUI class, GUIView, with a no-arg constructor and a static getInstance() method.
    The GUI class has a JButton called btnB1 with a method:
         void addB1Listener(ActionListener al){
              btnB1.addActionListener(al);
         }The Controller class has an instance of the GUI and the Model.
    The Controller has a constructor which assigns a new ActionListener to the JButton from the GUI.
    private GUI m_gui;
         FTController(GUIView view){
              m_gui = view;
              m_gui.addButtonListener(new AddButtonListener());
         }The Controller has an inner class:
    class AddButtonListener implements ActionListener{
              @Override
              public void actionPerformed(ActionEvent e) {
                          // do stuff
    }The model has a constructor which accepts a GUIView.
    My main method setups instances of the objects:
         private GUIView view;
         private Model model;
         private Controller controller;
         public static void main(String [] args){
              view = GUIView.getInstance();
              model = new Model(view);
              controller = new Controller(view);
         }This action listener for btnB1 is firing multiple times, but I don't understand why.
    Edited by: user10199598 on Jan 9, 2012 2:56 PM

    Here is the actual Controller class
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.IOException;
    import javax.swing.JOptionPane;
    import com.esri.arcgis.carto.FeatureLayer;
    import com.esri.arcgis.carto.IActiveView;
    import com.esri.arcgis.carto.Map;
    import com.esri.arcgis.interop.AutomationException;
    public class FTController{
         private FTView m_arraView;
         private FTModel m_arraModel;
         private Map m_map;
         FTController(FTView view, FTModel model, Map map){
              m_arraView = view;
              m_arraModel = model;
              m_map = map;
              m_arraView.addPointListener(new AddPointListener());
              m_arraView.addExitListener(new AddExitListener());
              m_arraView.addResetListener(new AddResetListener());
         public FTView getM_arraView() {
              return m_arraView;
         // Inner class used as the ActionListener for the btnAddPoint in FTView
         class AddPointListener implements ActionListener {
              @Override
              public void actionPerformed(ActionEvent e) {
                   FeatureLayer fl = (FeatureLayer) m_arraModel.getLayerByName("arra_field_teams", m_map);
                   try {
                        // Start the process to add a new feature point
                        m_arraModel.addPoint(fl, (IActiveView) m_map.getActiveView());
                        // Reset and dispose of the ARRA Field Teams form.
                        m_arraView.getCboTeam().setSelectedIndex(0);
                        m_arraView.getCboAgency().setSelectedIndex(0);
                        m_arraView.getTxtLatitude().setText("");
                        m_arraView.getTxtLongitude().setText("");
                        m_arraView.getTxtGridL().setText("");
                        m_arraView.getTxtGridN().setText("");
                        m_arraView.getTxtQuadrant().setText("");
                        m_arraView.getFtf3IC().setText("0.002");
                        m_arraView.getFtf3FC().setText("0.002");
                        m_arraView.getFtf3IO().setText("0.002");
                        m_arraView.getFtf3FO().setText("0.002");
                        m_arraView.getFtfAgxCartridge().setText("0.000");
                        m_arraView.getFtfBGCM().setText("50.000");
                        m_arraView.getFtfBGURHR().setText("0.002");
                        m_arraView.getTxtTimeOfReading().setText("");
                        m_arraView.dispose();
                        // Refresh the map window
                        m_map.getActiveView().refresh();
                   } catch (AutomationException e1) {
                        e1.printStackTrace();
                   } catch (IOException e1) {
                        e1.printStackTrace();
         } // end AddPointListener
         // Inner class used as the ActionListener for the btnExit in FTView
         class AddExitListener implements ActionListener{
              @Override
              public void actionPerformed(ActionEvent e) {
                   m_arraView.getCboTeam().setSelectedIndex(0);
                   m_arraView.getCboAgency().setSelectedIndex(0);
                   m_arraView.getTxtLatitude().setText("");
                   m_arraView.getTxtLongitude().setText("");
                   m_arraView.getTxtGridL().setText("");
                   m_arraView.getTxtGridN().setText("");
                   m_arraView.getTxtQuadrant().setText("");
                   m_arraView.getFtf3IC().setText("0.002");
                   m_arraView.getFtf3FC().setText("0.002");
                   m_arraView.getFtf3IO().setText("0.002");
                   m_arraView.getFtf3FO().setText("0.002");
                   m_arraView.getFtfAgxCartridge().setText("0.000");
                   m_arraView.getFtfBGCM().setText("50.000");
                   m_arraView.getFtfBGURHR().setText("0.002");
                   m_arraView.getTxtTimeOfReading().setText("");
                   m_arraView.dispose();
         } // end AddExitListener
         // Inner class used as the ActionListner for the btnReset in FTView
         class AddResetListener implements ActionListener{
              @Override
              public void actionPerformed(ActionEvent e) {
                   FeatureLayer fl = (FeatureLayer) m_arraModel.getLayerByName("field_teams", m_map);
                   try {
                        // Actually, "Reset" is deleting all features from the shapefile, poor choice of labels.
                        m_arraModel.resetFeatures(fl, (IActiveView) m_map.getActiveView(), (Map) m_map);
                        // Refresh the map window
                        m_map.getActiveView().refresh();
                   } catch (AutomationException e1) {
                        e1.printStackTrace();
                   } catch (IOException e1) {
                        e1.printStackTrace();
    }Here is where the application starts:
    import java.awt.event.MouseEvent;
    import java.io.IOException;
    import java.text.DecimalFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    import com.esri.arcgis.addins.desktop.Tool;
    import com.esri.arcgis.arcmap.Application;
    import com.esri.arcgis.arcmapui.IMxDocument;
    import com.esri.arcgis.arcmapui.MxDocument;
    import com.esri.arcgis.carto.IActiveView;
    import com.esri.arcgis.carto.IFeatureLayer;
    import com.esri.arcgis.carto.Map;
    import com.esri.arcgis.framework.IApplication;
    import com.esri.arcgis.geodatabase.Feature;
    import com.esri.arcgis.geodatabase.IFeatureClass;
    import com.esri.arcgis.geometry.Point;
    import com.esri.arcgis.interop.AutomationException;
    public class FTTool extends Tool {
         private IApplication app;
         private IActiveView av;
         private IMxDocument mxDocument;
         private Map map;
         private FTView arraView;
         private FTModel model;
         private FTController controller;
         private int left;
         private int top;
          * Called when the tool is activated by clicking it.
          * @exception java.io.IOException if there are interop problems.
          * @exception com.esri.arcgis.interop.AutomationException if the component throws an ArcObjects exception.
         @Override
         public void activate() throws IOException, AutomationException {
         @Override
         public void init(IApplication app) throws IOException, AutomationException {
              this.app = app;
              try {
                 try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                   } catch (ClassNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                   } catch (InstantiationException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                   } catch (IllegalAccessException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                   } catch (UnsupportedLookAndFeelException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                   // Initialize our map document, map and active view
                   mxDocument = (IMxDocument)app.getDocument();
                   av = mxDocument.getActiveView();
                   map = (Map)mxDocument.getMaps().getItem(0);
                   // Get an instance of the ARRAView JFrame, and setup the model and controller for this tool add-in
                   arraView = FTView.getInstance();
    //               arraView.addWindowListener(arraView);
                   // Set up the model and controller objects
                   model = new FTModel(arraView);
                   controller = new FTController(arraView, model, map);
              } catch (AutomationException e) {
                   e.printStackTrace();
              } catch (IOException e) {
                   e.printStackTrace();
         @Override
         public void mousePressed(MouseEvent mouseEvent) {
              super.mousePressed(mouseEvent);
              // Cast IMxDocument into MxDocument so we can get the Parent which returns an Application
              MxDocument mxd = (MxDocument)mxDocument;
              Application application;
              // Create an Application object so we can get the left and top properties of the window
              //  so we can position the Field Teams GUI.
              try {
                   application = new Application(mxd.getParent());
                   left = application.getLeft() + 75;
                   top = application.getTop() + 105;
              } catch (IOException e2) {
                   e2.printStackTrace();
              try {
                   // Call the model to convert the screen coordinates to map coordinates and project the point to WGS_1984
                   Point p1 = new Point();
                   p1.putCoords((double)mouseEvent.getX(), (double)mouseEvent.getY());
                   Point p2 = (Point) model.getMapCoordinatesFromScreenCoordinates(p1, av);
                   Point point = (Point)model.handleToolMouseEvent(mouseEvent, av);
                 // Format the decimal degrees to six decimal places
                   DecimalFormat df = new DecimalFormat("#.######");
                   // Assign the point2 values to double
                   double x = point.getX();
                   double y = point.getY();
                   // Set the text of the lat/long fields.
                   arraView.getTxtLatitude().setText(df.format(y));
                   arraView.getTxtLongitude().setText(df.format(x));
                   // Set the Time of Reading text field
                   Date now = new Date();
                   SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
                   arraView.getTxtTimeOfReading().setText(sdf.format(now).toString());
                   // Determine whether the mouse click point intersects the arra_grid_quad.
                   //  If so, iterate over that feature cursor to update the gridl, gridn and quadrant fields...
                   IFeatureLayer featLayer = (IFeatureLayer) model.getLayerByName("arra_grid_quads", map);     
                   IFeatureClass featClass = featLayer.getFeatureClass();
                   Feature iFeat = (Feature) model.queryArraGridQuads(featClass, p2);
                   if(iFeat != null){
                        // Fill in the grid and quadrant values if there are any.
                        String gridl = (String) iFeat.getValue(iFeat.getFields().findField("GRID_L"));
                        String gridn = (String) iFeat.getValue(iFeat.getFields().findField("GRID_N"));
                        String quadrant = (String) iFeat.getValue(iFeat.getFields().findField("QUADRANT"));
                        arraView.getTxtGridL().setText(gridl);
                        arraView.getTxtGridN().setText(gridn);
                        arraView.getTxtQuadrant().setText(quadrant);
                   } else {
                        // Revert values back to empty string after clicking in the grid, then outside of the grid.
                        arraView.getTxtGridL().setText("");
                        arraView.getTxtGridN().setText("");
                        arraView.getTxtQuadrant().setText("");
                   // Set the Field Team Readings form to visible, or redisplay it if it is already visible
                   arraView.setBounds(left, top, 325, 675);
                   arraView.setVisible(true);
              } catch (Exception e) {
                   e.printStackTrace();
         @Override
         public boolean deactivate() throws IOException, AutomationException {
              return super.deactivate();
         @Override
         public boolean isChecked() throws IOException, AutomationException {
              return super.isChecked();
         public FTView getArraView() {
              return arraView;
         public IApplication getApp() {
              return app;
         public Map getMap() {
              return map;
         public FTModel getModel() {
              return model;
    }Is this enough?
    Edited by: user10199598 on Jan 9, 2012 3:20 PM

  • ActionListener / JTextArea Update Problem

    I have a JFrame that implements ActionListener, and the actionPerformed method looks like so:
    public void actionPerformed(ActionEvent myEvent){
         if ("abc".equals(myEvent.getActionCommand()) {
              //new window is created, etc
         } else if ("def".equals(myEvent.getActionCommand()) {
              //new window is created, etc
         someJTextArea.setText(newText);
         repaint();
    }The problem is, the newText relies on the other windows for its content, but for some unknown reason setText() is called before the new windows are closed, and also before newText has been set. I have a feeling this has something to do with the new windows launching their own threads, but I'm lost on how to wait for those windows to close before setting the text.
    Thanks for any help.

    I don't think that it's an issue of new threads being produced, since Swing GUIs and all actionPerformed code gets called on one thread, the EDT.
    More importantly to me: what exactly are your "new window"s? JFrames? If so, they likely need to be modal JDialogs. This will stop execution of any further method calls in your actionPerformed method until the dialogs have been fully dealt with.

  • Problem possibly with actionListener

    Hello,
    I am developing a GUI appplication with Java 1.4.2 and Netbeans 5. I have created a jtree whose status changes from visible to invisible. The first time that it is visible it works correctly, the second time (after making it invisible and again visible) it doesn't work at all!!I guess that the problem is related with the actionListener. Do you have any idea how can i solve it?
    Thank you.

    Try using CardLayout.
    or add the JTree to a panel, and make the panel visible/invisible.

  • Problems with writing to file, and with ActionListener.

    I have been trying to write a Payroll Division type program as my school Computer Science Project. However, I have a few problems with it...
    import java.io.IOException;
    import java.io.FileOutputStream;
    import java.io.FileInputStream;
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.util.StringTokenizer;
    import javax.swing.*;
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.event.*;
    public class Personnel implements ActionListener  {    
             JFrame GUIFrame;
             JLabel ID, Line, OKText,AnswerField;
             JTextField IDField, LineField;
             JButton OK;
             JPanel GUIPanel;
             int trialCounter=0;
             final static int employeeNumber = 7;
             final static int maxValue = ((employeeNumber*4)-1);
            //Number of employees, which would be in real life passed by the Payroll division.   
            public static String [][] sortHelp = new String [employeeNumber+1][3];    /** Creates a new instance of Personnel */       
            public Personnel() {
              GUIFrame = new JFrame("PersonnelSoft"); //create title header.
                     GUIFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                     GUIFrame.setSize(new Dimension(100, 140));
                     GUIPanel= new JPanel(new GridLayout(2, 2));
                     addWidgets();
                     GUIFrame.getRootPane().setDefaultButton(OK);
                     GUIFrame.getContentPane().add(GUIPanel, BorderLayout.CENTER);
                     GUIFrame.pack();
                    GUIFrame.getContentPane().setVisible(true);
                    GUIFrame.setVisible(true);
            private void addWidgets() {
                  ID = new JLabel ("Please enter your employee Identification Number:", SwingConstants.LEFT);
                  IDField = new JTextField ("ID", 5);
                  Line = new JLabel ("Please enter the line of your payroll with which you have concerns:", SwingConstants.LEFT);
                  LineField = new JTextField ("###", 2);
                  OKText = new JLabel ("Click OK when you have verified the validity of your request", SwingConstants.LEFT);
                  OK = new JButton ("OK");
                  OK.setVerticalTextPosition(AbstractButton.CENTER);
                  OK.setMnemonic(KeyEvent.VK_I);
                  AnswerField = new JLabel("The Result of your Querie will go here", SwingConstants.LEFT);
                  GUIPanel.add(ID);
                  GUIPanel.add(IDField);
                  GUIPanel.add(Line);
                  GUIPanel.add(LineField);
                  GUIPanel.add(OKText);
                  GUIPanel.add(OK);
                  GUIPanel.add(AnswerField);
                  OK.addActionListener(this);
                  ID.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
                  OKText.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
                  Line.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
            public static void ArrayCreate() throws IOException {   
              //creates a employeeNumber x 3 array, which will hold all data neccessary for future sorting by employee ID number.      
              int counter = 2;      
              int empCounter = 1;      
              String save;
              //avoid having to waste memory calculating this value every time the for loop begins 
              FileInputStream inFile = new FileInputStream("C:\\Documents and Settings\\Abraham\\humanresource4\\src\\humanresource4\\HR.txt"); 
              BufferedReader in = new BufferedReader(new InputStreamReader(inFile));
              String line;
                    line = in.readLine();
                    StringTokenizer st = new StringTokenizer(line);
                    save = st.nextToken();
                    sortHelp[0][0] = save;
                    sortHelp[0][2] = save;
                    while (st.hasMoreTokens()) {
                    save = st.nextToken();   
                    sortHelp[0][1] = save;
                    while (counter <= maxValue) {
                    line = in.readLine();
                    if (((counter - 1) % 4) == 0) {
                    st = new StringTokenizer(line);
                    sortHelp[empCounter][0] = st.nextToken();
                    sortHelp[empCounter][2] = sortHelp[empCounter][0];
                    while (st.hasMoreTokens()) {
                    save = st.nextToken();   
                    sortHelp[empCounter][1] = save;
                    empCounter++;
                    counter++;
                 public static String[] joinString() {
                      String[] tempStorage = new String[employeeNumber+1];
                      int counter;
                      for (counter = 0; counter <= employeeNumber; counter++) {
                           tempStorage[counter] = (sortHelp[counter][1] + sortHelp[counter][0]);
                      return (tempStorage);
                 public static String[] sortEm(String[] array, int len)
                     java.util.Arrays.sort(array);
                     return array;
                 public static void splitString(String[] splitString){
                    int counter;
                    for (counter = 0; counter <= employeeNumber; counter++){
                         sortHelp[counter][0]=splitString[counter].substring( 5 );
                         sortHelp[counter][1]=splitString[counter].substring(0,5);
                 void setLabel(String newText) {
                     AnswerField.setText(newText);
                 void writetoHR(String local) throws IOException {
                      FileOutputStream outFile = new FileOutputStream ("C:\\Documents and Settings\\Abraham\\humanresource4\\src\\humanresource4\\HR2.txt");
                       BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outFile));
                       out.write(local+"the preceding employee number is not in our database, but has submitted a request. Please sort out the issue");
                       System.exit(0);
                 public void actionPerformed(ActionEvent e){
                      boolean flag=false;
                      String local=IDField.getText();
                      int i=0;
                      while((i<=employeeNumber)&&(flag==false)){
                           if (sortHelp[1]==local) {
                   flag=true;
              i++;
         trialCounter++;
         if (trialCounter>=3)
              writetoHR(local);
         if (flag==false)
              setLabel("Your ID number does not exist in our records. Verify your ID and try again.");
         else {
              switch (LineField.getText())
              case 04:
                   setLabel("Your pay is calculated by multiplying your working hours by the amount per hour. If both of these fields are satisfactory to you, please contact humanresource");
                   break;
              case 03:
                   setLabel("Hourly amount was calculated by the system, by dividing your yearly pay 26 and then 80.");
                   break;
              case 07:
                   setLabel("Overtime pay was calculated by multiplying regular hourly pay by 1.1");
                   break;
              case 06:
                   setLabel("The overtime hourly pay was multiplied by the amount of overtime hours.");
                   break;
              case 10:
                   setLabel("For holiday hours, your pay is increased by 25%.");
                   break;
              case 09:
                   setLabel("The holiday hourly pay was multiplied by your amount of holiday hours.");
                   break;
              case 11:
                   setLabel("Your total pay was calculated by adding all the separate types of payment to your name.");
                   break;
              case 17:
                   setLabel("Your net pay was found by subtracting the amount withheld from your account");
                   break;
              case 19:
                   setLabel("Your sick hours remaining were taken from a pool of 96 hours.");
                   break;
              default:
                   setLabel("Please contact humanresource.");
              break;
    private static void CreateAndShowGUI() {
    JFrame.setDefaultLookAndFeelDecorated(true);
    Personnel GUI = new Personnel();
         public static void main(String[] args) throws IOException {
              String[] temporary = new String[employeeNumber];
              ArrayCreate();
    temporary = joinString();
    temporary = sortEm(temporary, employeeNumber);
    splitString(temporary);
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    CreateAndShowGUI();
    int row;
    int column;
         for (row = 0; row < (employeeNumber); row++) {    // verify proper output by ArrayCreate splitString
    for (column = 0; column <= 2; column++) {
    System.out.print(sortHelp[row][column]);
    System.out.print(' ');
    System.out.print(' ');
    System.out.println();
    1) It does not permit me to switch on a String. How do I solve that?
    2)How would I throw an exception (IO) within actionperformed?
    3)Generally, if cut it down to everything except the writing to a file part, the actionperformed script causes an error... why?
    Thanks in advance.
    And sorry for the relative lameness of my question...
    ---abe---

    Thank you very much. That did solve almost all the problems that I had...
    I just have one more problem.
    First (here's the new code):
    import java.io.IOException;
    import java.io.FileOutputStream;
    import java.io.FileInputStream;
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.util.StringTokenizer;
    import javax.swing.*;
    import java.util.*;
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.event.*;
      public class Personnel implements ActionListener  {    
             JFrame GUIFrame;
              JLabel ID, Line, OKText,AnswerField;
               JTextField IDField, LineField;
               JButton OK;
               JPanel GUIPanel;
               int trialCounter=0;
         final static int employeeNumber = 7;
         final static int maxValue = ((employeeNumber*4)-1);
                public static String [][] sortHelp = new String [employeeNumber+1][3];   
         public Personnel() {
              GUIFrame = new JFrame("PersonnelSoft"); //create title header.
             GUIFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             GUIFrame.setSize(new Dimension(100, 140));
             GUIPanel= new JPanel(new GridLayout(2, 2));
             addWidgets();
             GUIFrame.getRootPane().setDefaultButton(OK);
             GUIFrame.getContentPane().add(GUIPanel, BorderLayout.CENTER);
             GUIFrame.pack();
            GUIFrame.getContentPane().setVisible(true);
            GUIFrame.setVisible(true);
            private void addWidgets() {
                  ID = new JLabel ("Please enter your employee Identification Number:", SwingConstants.LEFT);
                  IDField = new JTextField ("ID", 5);
                  Line = new JLabel ("Please enter the line of your payroll with which you have concerns:", SwingConstants.LEFT);
                  LineField = new JTextField ("###", 2);
                  OKText = new JLabel ("Click OK when you have verified the validity of your request", SwingConstants.LEFT);
                  OK = new JButton ("OK");
                  OK.setVerticalTextPosition(AbstractButton.CENTER);
                  OK.setMnemonic(KeyEvent.VK_I);
                  AnswerField = new JLabel("The Result of your Querie will go here", SwingConstants.LEFT);
                  GUIPanel.add(ID);
                  GUIPanel.add(IDField);
                  GUIPanel.add(Line);
                  GUIPanel.add(LineField);
                  GUIPanel.add(OKText);
                  GUIPanel.add(OK);
                  GUIPanel.add(AnswerField);
                  OK.addActionListener(this);
                  ID.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
                  OKText.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
                  Line.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
            public static void ArrayCreate() throws IOException {   
              int counter = 2;      
              int empCounter = 1;      
              String save;
              FileInputStream inFile = new FileInputStream("C:\\Documents and Settings\\Abraham\\humanresource4\\src\\humanresource4\\HR.txt"); 
              BufferedReader in = new BufferedReader(new InputStreamReader(inFile));
              String line;
                    line = in.readLine();
                    StringTokenizer st = new StringTokenizer(line);
                    save = st.nextToken();
                    sortHelp[0][0] = save;
                    sortHelp[0][2] = save;
                    while (st.hasMoreTokens()) {
                    save = st.nextToken();   
                    sortHelp[0][1] = save;
                    while (counter <= maxValue) {
                    line = in.readLine();
                    if (((counter - 1) % 4) == 0) {
                    st = new StringTokenizer(line);
                    sortHelp[empCounter][0] = st.nextToken();
                    sortHelp[empCounter][2] = sortHelp[empCounter][0];
                    while (st.hasMoreTokens()) {
                    save = st.nextToken();   
                    sortHelp[empCounter][1] = save;
                    empCounter++;
                    counter++;
                 public static String[] joinString() {
                      String[] tempStorage = new String[employeeNumber+1];
                      int counter;
                      for (counter = 0; counter <= employeeNumber; counter++) {
                           tempStorage[counter] = (sortHelp[counter][1] + sortHelp[counter][0]);
                      return (tempStorage);
                 public static String[] sortEm(String[] array, int len)
                     java.util.Arrays.sort(array);
                     return array;
                 public static void splitString(String[] splitString){
                    int counter;
                    for (counter = 0; counter <= employeeNumber; counter++){
                         sortHelp[counter][0]=splitString[counter].substring( 5 );
                         sortHelp[counter][1]=splitString[counter].substring(0,5);
                 void setLabel(String newText) {
                     AnswerField.setText(newText);
                 void writetoHR(String local) throws IOException {
                      FileOutputStream outFile = new FileOutputStream ("C:\\Documents and Settings\\Abraham\\humanresource4\\src\\humanresource4\\HR2.txt");
                       BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outFile));
                       out.write(local+"the preceding employee number is not in our database, but has submitted a request. Please sort out the issue");
                       System.exit(0);
                 public void actionPerformed(ActionEvent e){
                      boolean flag=false;
                      String local=IDField.getText();
                      local trim();
                      int i=0;
                      while((i<employeeNumber)&&(flag==false)){
                           if (sortHelp[1]==local) {
                   flag=true;
              else {
         i++;
         trialCounter++;
         if (trialCounter>=3)
              try {
                   writetoHR(local);
              } catch (IOException exception) {
    setLabel("We are sorry. The program has encountered an unexpected error and must now close");
              } finally {
         if (flag==false)
              setLabel("Your ID number does not exist in our records. Verify your ID and try again.");
         else {
              final Map m = new HashMap();
              m.put("04","Your pay is calculated by multiplying your working hours by the amount per hour. If both of these fields are satisfactory to you, please contact humanresource.");
              m.put("03", "Hourly amount was calculated by the system, by dividing your yearly pay 26 and then 80.");
              m.put("07", "Overtime pay was calculated by multiplying regular hourly pay by 1.1");
              m.put("06", "The overtime hourly pay was multiplied by the amount of overtime hours.");
              m.put("10", "For holiday hours, your pay is increased by 25%.");
              m.put("09", "The holiday hourly pay was multiplied by your amount of holiday hours.");
              m.put("11", "Your total pay was calculated by adding all the separate types of payment to your name.");
              m.put("17", "Your net pay was found by subtracting the amount withheld from your account.");
              m.put("19", "Your sick hours remaining were taken from a pool of 96 hours.");
    setLabel(m.get(LineField.getText()));
    private static void CreateAndShowGUI() {
    JFrame.setDefaultLookAndFeelDecorated(true);
    Personnel GUI = new Personnel();
    public static void main(String[] args) throws IOException {
              String[] temporary = new String[employeeNumber];
              ArrayCreate();
    temporary = joinString();
    temporary = sortEm(temporary, employeeNumber);
    splitString(temporary);
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    CreateAndShowGUI();
    int row;
    int column;
         for (row = 0; row < (employeeNumber); row++) {    // verify proper output by ArrayCreate splitString
    for (column = 0; column <= 2; column++) {
    System.out.print(sortHelp[row][column]);
    System.out.print(' ');
    System.out.print(' ');
    System.out.println();
    Now that code above produces two errors. First of all.
    local trim();produces the error:
    Syntax error, insert "AssignmentOperator ArrayInitializer" to complete ArrayInitializerAssignementSecondly, if I take that into comments, the line
    setLabel(m.get(LineField.getText()));Produces the error:
    The method setLabel(String) in the type Personnel is not applicable for the arguments (Object)If anybody could help me solve these, I would be sincerely thankfull.
    Now, before anybody asks as to why I want to trim the String in the first place, it is due to the fact that I compare it to another String that is without whitespaces. Thus the field that DOES have whitespaces was preventing me from launching into the if loop:
    if (sortHelp[1]==local) {
                   flag=true;
    (within actionperformed) Or at least that's my explanation as to why the loop never launched. If it is wrong, can somebody please explain?)
    I apologize for the horrible indentation and lack of comments. This is an unfinished version.. I'll be adding the comments last (won't that be a joy), as well as looking for things to cut down on and make the program more efficient.
    Anyways,
    Thanks in Advance,
    ---abe---

  • Problems with actionListener

    Hi, I'm having som problems with getSource.
    I realize that actionPerformed doesn't recognize the JButtons because of the scope, but as far as I can tell, I have done it like the examples I have followed.
    package gui;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class NumericPanel extends JPanel implements ActionListener {
         public NumericPanel(){
              setLayout(new GridLayout(4,3));
              //Generating Buttons
            JButton b1 = new JButton("1");
            JButton b2 = new JButton("2");
            JButton b3 = new JButton("3");
            JButton b4 = new JButton("4");
            JButton b5 = new JButton("5");
            JButton b6 = new JButton("6");
            JButton b7 = new JButton("7");
            JButton b8 = new JButton("8");
            JButton b9 = new JButton("9");
            JButton bClear = new JButton("Clear");
            JButton b0 = new JButton("0");
            JButton bEnter = new JButton("Enter");
            setLayout(new GridLayout(4,3));
            add(b1);
            add(b2);
            add(b3);
            add(b4);
            add(b5);
            add(b6);
            add(b7);
            add(b8);
            add(b9);
            add(bClear);
            add(b0);
            add(bEnter);
            b1.addActionListener(this);
            b2.addActionListener(this);
            b3.addActionListener(this);
            b4.addActionListener(this);
            b5.addActionListener(this);
            b6.addActionListener(this);
            b7.addActionListener(this);
            b8.addActionListener(this);
            b9.addActionListener(this);
            b0.addActionListener(this);
            bEnter.addActionListener(this);
            bClear.addActionListener(this);
         public void actionPerformed(ActionEvent e){
              Object button = e.getSource();
              if(button = b1){ // Says it doesn't recognize b1 - how am I supposed to do this??!
    }

    I have done it like the examples I have followed.Check out the example in the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/button.html]How to Use Buttons which uses the "action command" instead of checking the button.
    An even better way is to write generic code when possible so you con't have to check which button was clicked as demonstrated in this simple example:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=609795
    You can always use multiple listeners, one for the numbers on one for the other buttons.

Maybe you are looking for

  • HT201250 how do I get Time Machine to back up files (e.g. iPhoto) stored on an external hard drive?

    Installed a new 3TB external hard drive for Time Machine.  I have 2 other external hard drives attached to my iMac that contain iTunes and iPhoto.  How can I point Time Machine to those external drives to include in the backup?

  • Help: Itouch not responding

    One of my friends 'borrowed' my IPod Touch. He said he tried to update something on it from his PC and it came unplugged in the middle of it. I have no clue what he was doing or what he was trying to install, and I dont think he knows either. ****, I

  • Poster on SMP

    Hi guys, sadly i do have one problem right now with strobe media playback. When i set the poster parameter to an absolute path of an image file, it works smoothly and SMP does show that picture in advance of playing the media file. But when i do want

  • I cannot open firefox, error states entry point not found

    I can not open firefox, I downloaded an update and ever since, when I try to open I get the error message "no entry point found" What should I do? == This happened == Every time Firefox opened == today == == User Agent == Mozilla/4.0 (compatible; MSI

  • TV Message Center Wont turn off!!!

    The most useless and frustrating app in the entire thinkvantage package has got to be the Message Center. With the latest updated version, it seems to have developed a mind of it's own. Removed from the startup menus for all users, and the preference