Executing an actionlistener in separate class

Hi all,
This is my first question on the Java forum. Hope I express myself clearly and I hope that someone can help me.
I have created two classes (i.e. modified files that I found in Java books) - one which creates the user interface using JFrame (a text field and menu structure) and a second class which is basically the action listener for when the "menuFileLoad" button is pressed in the application.
I would like to move the code for all "actionlisteners" to separate classes to make the code more transparent.
I've moved the code for the action listener for the "menuFileLoad" button to the separate class "alistener".
The code compiles well, but the action in the alistener class is not performed. It should put "Another text" in a text field. For test purposes, I've also put
"System.out.println ("dada");" in the action listener and this is executed well.
Has it something to do with the accessibility of the "TextField" ?
This is the class that builds up the GUI
import java.awt.*;
import java.awt.event.*;
import java.lang.Object;
import java.awt.Container;
import javax.swing.JFileChooser;
* Sample application using Frame.
* @author
* @version 1.00 08/09/10
public class Getstring_ArrayFrame extends Frame {
     * The constructor.
     public TextField text = new TextField(20);
     public Getstring_ArrayFrame() {
        MenuBar menuBar = new MenuBar();
        Menu menuFile = new Menu();
        MenuItem menuFileExit = new MenuItem();
        MenuItem menuFileLoad = new MenuItem();
        MenuItem menuFileParse = new MenuItem();
        Menu menuFileTwo = new Menu();
        MenuItem menuFileDo = new MenuItem();
        menuFile.setLabel("File");
        menuFileExit.setLabel("Exit");
        menuFileLoad.setLabel("Load");
        menuFileDo.setLabel("Import Tool");
        menuFileParse.setLabel("Parse");
        menuFileTwo.setLabel("Tools");
        add(text);
        // Add action listener.for the menu button
        menuFileExit.addActionListener
            new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    Getstring_ArrayFrame.this.windowClosed();
// DIT IS HEM - DE EERSTE ECHTE ACTION LISTENER
       menuFileLoad.addActionListener (new alistener ());
           // new ActionListener() {
             //   public void actionPerformed(ActionEvent e) {
               // text.setText ("Eerste tekstje, joepie. Misschien nu nog den xml erbij krijgen");
               // text.setBackground(Color.black);
               // text.setForeground(Color.white);
menuFileParse.addActionListener
            new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                text.setText ("Opnieuw een tekstje, met tevens ook al een nieuwe knop.");
                //text.setBackground(Color.black);
                // text.setForeground(Color.white);
        menuFile.add(menuFileExit);
        menuFile.add(menuFileLoad);
        menuFile.add(menuFileParse);
        menuFileTwo.add(menuFileDo);
        menuBar.add(menuFile);
        menuBar.add(menuFileTwo);
        setTitle("Getstring_Array");
        setMenuBar(menuBar);
        setSize(new Dimension(400, 400));
        // Add window listener.
        this.addWindowListener
            new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    Getstring_ArrayFrame.this.windowClosed();
     * Shutdown procedure when run as an application.
    protected void windowClosed() {
         // TODO: Check if it is safe to close the application
        // Exit application.
        System.exit(0);
}==> This is the alistener class
import java.awt.*;
import java.awt.event.*;
import java.lang.Object;
import java.awt.Container;
import javax.swing.JFileChooser;
public class alistener implements ActionListener {
     TextField text = new TextField(20);
public alistener () {
public void actionPerformed(ActionEvent e) {
              System.out.println ("dada");
               text.setText ("Another text.");
               text.setBackground(Color.black);
               text.setForeground(Color.white);
}

I don't know AWT, just Swing, but it appears that your listener needs a reference to the GUI which may be passed perhaps in the Listener's constructor, and the GUI needs public methods to allow the listener to change things -- but to limit this ability so as not to compromise encapsulation. This should work the same with AWT For instance:
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JComponent;
import javax.swing.JTextField;
public class SwingTest
  private JPanel mainPanel = new JPanel();
  private JTextField textfield = new JTextField(20);
  public SwingTest()
    textfield.setEditable(false);
    JButton testListenerBtn = new JButton("Test Listener");
    testListenerBtn.addActionListener(new SwingTestListener(this));
    mainPanel.add(textfield);
    mainPanel.add(testListenerBtn);
  // public methods to allow the listener to change things,
  // but limit this ability to only what we want to let it change
  public void textfieldSetText(String text)
    textfield.setText(text);
  public void textSetBackground(Color color)
    textfield.setBackground(color);
  public void textSetForeGround(Color color)
    textfield.setForeground(color);
  public JComponent getComponent()
    return mainPanel;
  private static void createAndShowUI()
    JFrame frame = new JFrame("SwingTest");
    frame.getContentPane().add(new SwingTest().getComponent());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  public static void main(String[] args)
    java.awt.EventQueue.invokeLater(new Runnable()
      public void run()
        createAndShowUI();
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SwingTestListener implements ActionListener
  private SwingTest swingtest;
  public SwingTestListener(SwingTest swingtest)
    this.swingtest = swingtest;
  public void actionPerformed(ActionEvent arg0)
    swingtest.textfieldSetText("This Listener works!");
    swingtest.textSetBackground(Color.black);
    swingtest.textSetForeGround(Color.white);
}Edited by: Encephalopathic on Nov 5, 2008 12:27 AM

Similar Messages

  • Listen for an events for Swing objects in a separate class?

    Hi all, sorry if this is in the wrong section of the forum but since this is a problem I am having with a Swing based project I thought i'd come here for help. Essentially i have nested panels in separate classes for the sake of clarity and to follow the ideas of OO based development. I have JPanels that have buttons and other components that will trigger events. I wish for these events to effect other panels, in the Hierachy of my program:
    MainFrame(MainPanel(LeftPanel, RightPanel, CanvasPanel))
    Sorry I couldnt indent to show the hierarchy. Here LeftPanel, RightPanel and CanvasPanel are objects that are created in the MainPanel. For example i want an event to trigger a method in another class e.g. LeftPanel has a button that will call a method in CanvasPanel. I have tried creating an EventListner in the MainPanel that would determine the source and then send off a method to the relevant class, but the only listeners that respond are the ones relevant to the components of class. Can I have events that will be listened to over the complete scope of the program? or is there another way to have a component that can call a method in the class that as an object, it has been created in.
    Just as an example LeftPanel has a component to select the paint tool (its a simple drawing program) that will change a color attribute in the CanvasPanel object. Of course I realize i could have one massive Class with everything declared in it, but I'd rather learn if it is possible to do it this way!
    Thanks in advance for any help you can offer
    Lawrence
    Edited by: insertjokehere on Apr 15, 2008 12:24 PM

    Thanks for the response, ive added ActionListneres in the class where the component is, and in an external class. The Listeners work inside the class, but not in the external class
    import java.awt.event.ActionEvent;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.ActionListener;
    public class LeftPanel extends JPanel implements ActionListener {  
        /* Constructing JButtons, null until usage of the constructor */
        JButton pencilBut;
        JButton eraserBut;
        JButton textBut;
        JButton copyBut;
        JButton ssincBut;
        JButton ssdecBut;
        ActionListener a = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.print("\nNot supported yet.");
        /* The Top Panel contains the title of program */
        public LeftPanel(Dimension d){
            /* Sets up the layout for the Panel */
            BoxLayout blo = new BoxLayout(this,BoxLayout.Y_AXIS);
            this.setLayout(blo);
            /* Sets Up the Appearance of the Panel */
            this.setMinimumSize(d);
            this.setBackground(Color.RED);
            this.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
            /* Pencil Tool */
            pencilBut = new JButton("Pencil");
            pencilBut.setAlignmentX(Component.CENTER_ALIGNMENT);
            pencilBut.setActionCommand("pencil");
            pencilBut.addActionListener(a);
            this.add(pencilBut);
            /* Eraser Tool */
            eraserBut = new JButton("Eraser");
            eraserBut.setAlignmentX(Component.CENTER_ALIGNMENT);
            eraserBut.addActionListener(a);
            this.add(eraserBut);
            /* Text Tool */
            textBut = new JButton("Text");
            textBut.setAlignmentX(Component.CENTER_ALIGNMENT);
            textBut.addActionListener(a);
            this.add(textBut);
            /* Copy Previous Page */
            copyBut = new JButton("Copy Page");
            copyBut.setAlignmentX(Component.CENTER_ALIGNMENT);
            copyBut.addActionListener(a);
            this.add(copyBut);
            /* Stroke Size Increase */
            ssincBut = new JButton("Inc");
            ssincBut.setAlignmentX(Component.CENTER_ALIGNMENT);
            ssincBut.addActionListener(a);
            this.add(ssincBut);
            /* Stroke Size Decrease */
            ssdecBut = new JButton("Dec");
            ssdecBut.setAlignmentX(Component.CENTER_ALIGNMENT);
            ssdecBut.addActionListener(a);
            this.add(ssdecBut);
            System.out.print("\nLeftPanel Completed");
        public void actionPerformed(ActionEvent e) {
            System.out.print("\nAction Performed");
        }But this is not picked up in my external class here
    import java.awt.event.ActionEvent;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.ActionListener;
    public class MainPanel extends JPanel implements ActionListener {
        /* Creates a new the main JPanel that is used in the FlipBookFrame to contain all of the elements */
        public MainPanel(){
            /* TopPanel constraints*/
            tpcs.gridx = 1;
            tpcs.gridy = 0;
            tpcs.gridwidth = 1;
            tpcs.gridheight = 1;
            tpcs.fill = GridBagConstraints.BOTH;
            tpcs.weightx = 0.0;
            tpcs.weighty = 1.0;
            /* LeftPanel Constraints*/
            lpcs.gridx = 0;
            lpcs.gridy = 0;
            lpcs.gridwidth = 1;
            lpcs.gridheight = 3;
            lpcs.fill = GridBagConstraints.BOTH;
            lpcs.weightx = 1.0;
            lpcs.weighty = 1.0;
            /* CentrePanel Constraints*/
            cpcs.gridx = 1;
            cpcs.gridy = 1;
            cpcs.gridwidth = 1;
            cpcs.gridheight = 1;
            cpcs.fill = GridBagConstraints.NONE;
            cpcs.weightx = 0.0;
            cpcs.weighty = 0.0;
            /* RightPanel Constraints*/
            rpcs.gridx = 2;
            rpcs.gridy = 0;
            rpcs.gridwidth = 1;
            rpcs.gridheight = 3;
            rpcs.fill = GridBagConstraints.BOTH;
            rpcs.weightx = 1.0;
            rpcs.weighty = 1.0;
            /* BottomPanel Constraints*/
            bpcs.gridx = 1;
            bpcs.gridy = 2;
            bpcs.gridwidth = 1;
            bpcs.gridheight = 1;
            bpcs.fill = GridBagConstraints.BOTH;
            bpcs.weightx = 0.0;
            bpcs.weighty = 1.0;   
            this.setLayout(gblo);   //Sets the Layout of the panel to a GridBagLayout
            this.add(tp, tpcs); //Adds the TopPanel to the MainPanel using the TopPanel layout
            this.add(lp, lpcs); //Adds the LeftPanel to the MainPanel using the LeftPanel layout
            this.add(cp, cpcs); //Adds the CanvasPanel to the MainPanel using the CanvasPanel layout
            this.add(rp, rpcs); //Adds the RightPanel to the MainPanel using the RightPanel layout
            this.add(bp, bpcs); //Adds the BottomPanel to the MainPanel using the BottomPanel layout
            gblo.layoutContainer(this); //Lays Out the Container
        public PanelSizes getPanelSizes(){
            return ps;
        public void actionPerformed(ActionEvent e) {
            System.out.print("\nExternal Class finds event!");
            /*String command = e.getActionCommand();
            if (command.equals("pencil")){
                System.out.print("\nYESSSSSSSSSSSSSSSSSSSSS!");
        /* Create of objects using the PanelSizes funtions for defining the */
        PanelSizes ps = new PanelSizes();   //Creates a new PanelSizes object for sizing the panel
        CanvasPanel cp = new CanvasPanel(ps.getCentrePanelDimension()); //Creates a new Canvas Panel
        TopPanel tp = new TopPanel(ps.getHorizontalPanelDimension()); //Creates the TopPanel
        BottomPanel bp = new BottomPanel(ps.getHorizontalPanelDimension()); //Creates the BottomPanel
        LeftPanel lp = new LeftPanel(ps.getVerticalPanelDimension()); //Creates the LeftPanel
        RightPanel rp = new RightPanel(ps.getVerticalPanelDimension());   //Creates the RightPanel
        /* I have chosen to create individual constraints for each panel to allow for adding of all
         components a the end of the constructor. This will use slightly more memory but gives clarity
         in the code */
        GridBagConstraints cpcs = new GridBagConstraints();
        GridBagConstraints tpcs = new GridBagConstraints();
        GridBagConstraints bpcs = new GridBagConstraints();
        GridBagConstraints lpcs = new GridBagConstraints();   
        GridBagConstraints rpcs = new GridBagConstraints();
        GridBagLayout gblo = new GridBagLayout();
    }Any help will be greatly appreciated :-)

  • Clarification of JAR file and separate classes

    Hi all,
    I wanted to clarify a basic question. When do we club all classes to make a JAR file? For instance, in a web app with servlets, had all the servlet classes been put into a single JAR file, would that work? I know that woudn't but why?
    Is JAR file like a single executable (.exe) file? So, when (which type of applications) do we need single JAR and when separate classes?
    thanks much

    Thanks, I've gone thru it. So, sounds like JAR file can be used for invoking app thru command line or from some other app or even running applet in a browser. It can not be used for a servlet or jsp application. Am I right?

  • Moving buttons and their listeners to separate classes

    Hi
    I am trying to move out buttons and their listeners to separate classes, but when I do so, the program stops working. When I click on the button they dont react, probably the listeners doesent listens as the action performe prints out testprints.
    In other words, I have huge troubles with do my gui object oriented. I doesent seem to be able to move out relevant listener methods and their components to separate classes.
    Here is the code for one add button that I have tried to write in a separate class:
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.sql.SQLException;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    import javax.swing.JButton;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import se.cs.DB.DBMovie;
    import se.cs.inputvalidation.PatternsMovie;
    import se.cs.main.Main;
    import se.cs.main.MessageArea;
    public class ButtonAddMovie {
         private DBMovie init = new DBMovie();
         private ComboBoxesMovie comboBoxesMovie = new ComboBoxesMovie();
         private TextFieldsMovie textFieldsMovie = new TextFieldsMovie();
         private PatternsMovie patternsMovie = new PatternsMovie();
         private MessageArea messageArea = new MessageArea();
         private Pattern patternYear;
         private Pattern patternSection;
         private Pattern patternExFields;
         private Matcher matcherYear;
         private Matcher matcherSection;
         private Matcher matcherTotalEx;
         private Matcher matcherExIn;
         private Matcher matcherExOut;
         private String genreString;
         // Initializes the button components
         private JButton addButton = new JButton("Add");
         public ButtonAddMovie() {
              listener();
         public void listener() {
              addButton.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        addButton(e);
         public void addButton(ActionEvent e) {
              genreString = comboBoxesMovie.convertGenreIndex();
              regex();
         public void regex() {
              patternYear = Pattern.compile(patternsMovie.getYEAR_FIELD());
              patternSection = Pattern.compile(patternsMovie.getSECTION_FIELD());
              patternExFields = Pattern.compile(patternsMovie.getExFields());
              matcherYear = patternYear.matcher(textFieldsMovie.getTextYear());
              matcherSection = patternSection.matcher(textFieldsMovie.getTextYear());
              matcherTotalEx = patternExFields.matcher(textFieldsMovie
                        .getTextTotalEx());
              matcherExIn = patternExFields.matcher(textFieldsMovie.getTextExIn());
              matcherExOut = patternExFields.matcher(textFieldsMovie.getTextExOut());
              if (matcherYear.matches() && matcherSection.matches()
                        && matcherTotalEx.matches() && matcherExIn.matches()
                        && matcherExOut.matches()) {
                   messageArea.getMessageArea().setText("");
                   callInsertStatement();
                   JOptionPane.showMessageDialog(null, this.messageDialog(),
                             "Movie added", JOptionPane.INFORMATION_MESSAGE);
              else if (!matcherYear.matches()) {
                   messageArea.getMessageArea().setText(
                             "The input for year field does not match.\n"
                                       + "You have to enter 4 digits.");
              else if (!matcherSection.matches()) {
                   messageArea.getMessageArea().setText(
                             "The input for section field does not match.\n"
                                       + "You have to enter 1-4 digits.");
              else if (!matcherTotalEx.matches()) {
                   messageArea.getMessageArea().setText(
                             "The input for total ex field does not match.\n"
                                       + "You have to enter 1.");
              else if (!matcherExIn.matches()) {
                   messageArea.getMessageArea().setText(
                             "The input for ex in does not match.\n"
                                       + "You have to enter 1 digit.");
              else if (!matcherExOut.matches()) {
                   messageArea.getMessageArea().setText(
                             "The input  for ex out does not match.\n"
                                       + "You have to enter 1 digits.");
         public void callInsertStatement() {
              try {
                   init.insertStatement(textFieldsMovie.getTextTitle(),
                             textFieldsMovie.getTextYear(), genreString, comboBoxesMovie
                                       .convertGradeIndex(), textFieldsMovie
                                       .getTextSection(),
                             textFieldsMovie.getTextTotalEx(), textFieldsMovie
                                       .getTextExIn(), textFieldsMovie.getTextExOut());
              } catch (SQLException ex) {
                   ex.printStackTrace();
         public String messageDialog() {
              int grade = comboBoxesMovie.getGradeBox().getSelectedIndex() + 1;
              String title = textFieldsMovie.getTitleField().getText();
              String year = textFieldsMovie.getYearField().getText();
              String section = textFieldsMovie.getSectionField().getText();
              String totalEx = textFieldsMovie.getTotalExField().getText();
              String exIn = textFieldsMovie.getExInField().getText();
              String exOut = textFieldsMovie.getExOutField().getText();
              return "\n" + "Title: " + title + "\n" + "Year: " + year + "\n"
                        + "Genre: " + comboBoxesMovie.convertGenreIndex() + "\n"
                        + "Grade: " + grade + "\n" + "Section: " + section + "\n"
                        + "Total ex.: " + totalEx + "\n" + "Ex. in: " + exIn + "\n"
                        + "Ex. out: " + exOut + "\n";
          * Gets the addButton
          * @return addButton
         public JButton getAddButton() {
              return addButton;
         }

    I said "don't" cross-post and that the discussion has already been started in the "New To Java" forum.
    If you have two discussions going on then people waste time answering because they don't know what has already been suggested.

  • Using a Separate Class

    Hey, everybody. I'm learning Java through a text and it instructed me to write a class that contains several methods for generating random numbers and characters. It then instructed me to write a class containing a main method that calls one of the methods in this separate class. I know that you can't write two classes in one file, so I would appreciate it if someone could help by telling me how I'm supposed to make this work. Here are the two separate classes:
    1  public class RandomCharacter {
    2    /** Generate a random character between ch1 and ch2 */
    3    public static char getRandomCharacter(char ch1, char ch2) {
    4      return (char)(ch1 + Math.random() * (ch2 - ch1 + 1));
    5    }
    6
    7    /** Generate a random lowercase letter */
    8    public static char getRandomLowerCaseLetter() {
    9      return getRandomCharacter('a', 'z');
    10    }
    11
    12    /** Generate a random uppercase letter */
    13    public static char getRandomUpperCaseLetter() {
    14      return getRandomCharacter('A', 'Z');
    15    }
    16
    17    /** Generate a random digit character */
    18    public static char getRandomDigitCharacter() {
    19      return getRandomCharacter('0', '9');
    20    }
    21
    22    /** Generate a random character */
    23    public static char getRandomCharacter()  {
    24      return getRandomCharacter('\u0000', '\uFFFF');
    25    }
    26  }
    1  public class TestRandomCharacter {
    2    /** Main method */
    3    public static void main(String args[]) {
    4      final int NUMBER_OF_CHARS = 175;
    5      final int CHARS_PER_LINE = 25;
    6
    7      // Print random characters between '!' and '~', 25 chars per line
    8      for (int i = 0; i < NUMBER_OF_CHARS; i++) {
    9        char ch = RandomCharacter.getRandomLowerCaseLetter() ;
    10        if ((i + 1) % CHARS_PER_LINE == 0)
    11          System.out.println(ch);
    12        else
    13          System.out.print(ch);
    14      }
    15    }
    16  }

    So I put both of the files in a package called getrandom, then compiled the public class with the functions and tried to compile the class with the main function. This is what I got from the compiler:
    colton-ogdens-macbook:getrandom coltonogden$ javac TestRandomCharacter.java
    TestRandomCharacter.java:10: cannot find symbol
    symbol : variable RandomCharacter
    location: class getrandom.TestRandomCharacter
         char ch = RandomCharacter.getRandomLowerCaseLetter();
    ^
    1 error
    Here are the two source code files again:
    package getrandom;
    public class RandomCharacter {
         public static char getRandomCharacter(char ch1, char ch2) {
            return (char)(ch1 + Math.random() * (ch2 - ch1 + 1));
         public static char getRandomLowerCaseLetter() {
            return getRandomCharacter('a', 'z');
         public static char getRandomUpperCaseLetter() {
            return getRandomCharacter('A', 'Z');
         public static char getRandomDigitCharacter() {
            return getRandomCharacter();
         public static char getRandomCharacter() {
            return getRandomCharacter('\u0000', '\uFFFF');
    package getrandom;
    public class TestRandomCharacter {
         public static void main(String[] args) {
            final int NUMBER_OF_CHARS = 175;
            final int CHARS_PER_LINE = 25;
            for (int i = 0; i < NUMBER_OF_CHARS; i++) {
               char ch = RandomCharacter.getRandomLowerCaseLetter();
               if ((i + 1) % CHARS_PER_LINE == 0)
                  System.out.println(ch);
               else
                  System.out.print(ch);
    }It's exactly how they are given in the text, and with no explanation on packages or anything of the sort, which is strange. I put them both in the same directory, called also getrandom. What I suspect is that TestRandomCharacter isn't getting the class RandomCharacter, or I haven't created an instance of that class in TestRandomCharacter, but then why would the text write them out like this, expecting me to be able to compile them? I find it obscure.

  • How to restructure this code into separate classes?

    I have C# code that initializes a force feedback joystick and plays an effect file(vibrates the joystick). I have turn the console application into library
    code to make a dll so that I can use it in LabVIEW. 
    Right now all the code is written under one class, so went I put the dll in LabVIEW I can only select that one class. labVIEW guy told me that I need to
    restructure my C# code into separate classes. Each class that I want to access from LabVIEW needs to marked as public. Then I can instantiate that class in LabVIEW using a constructor, and call methods and set properties of that class using invoke nodes and
    property nodes.
    How can I do this correctly? I tried changing some of them into classes but doesn't work. Can you guys take a look at the code to see if it is even possible
    to break the code into separate classes? Also, if it is possible can you guide me, suggest some reading/video, etc.
    Thank you
    using System;
    using System.Drawing;
    using System.Collections;
    using System.Windows.Forms;
    using Microsoft.DirectX.DirectInput;
    namespace JoystickProject
    /// <summary>
    /// Summary description for Form1.
    /// </summary>
    public class Form1 : System.Windows.Forms.Form
    private System.Windows.Forms.Label label1;
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.Container components = null;
    private Device device = null;
    private bool running = true;
    private ArrayList effectList = new ArrayList();
    private string joyState = "";
    public bool InitializeInput()
    // Create our joystick device
    foreach(DeviceInstance di in Manager.GetDevices(DeviceClass.GameControl,
    EnumDevicesFlags.AttachedOnly | EnumDevicesFlags.ForceFeeback))
    // Pick the first attached joystick we see
    device = new Device(di.InstanceGuid);
    break;
    if (device == null) // We couldn't find a joystick
    return false;
    device.SetDataFormat(DeviceDataFormat.Joystick);
    device.SetCooperativeLevel(this, CooperativeLevelFlags.Exclusive | CooperativeLevelFlags.Background);
    device.Properties.AxisModeAbsolute = true;
    device.Properties.AutoCenter = false;
    device.Acquire();
    // Enumerate any axes
    foreach(DeviceObjectInstance doi in device.Objects)
    if ((doi.ObjectId & (int)DeviceObjectTypeFlags.Axis) != 0)
    // We found an axis, set the range to a max of 10,000
    device.Properties.SetRange(ParameterHow.ById,
    doi.ObjectId, new InputRange(-5000, 5000));
    // Load our feedback file
    EffectList effects = null;
    effects = device.GetEffects(@"C:\MyEffectFile.ffe",
    FileEffectsFlags.ModifyIfNeeded);
    foreach(FileEffect fe in effects)
    EffectObject myEffect = new EffectObject(fe.EffectGuid, fe.EffectStruct,
    device);
    myEffect.Download();
    effectList.Add(myEffect);
    while(running)
    UpdateInputState();
    Application.DoEvents();
    return true;
    public void PlayEffects()
    // See if our effects are playing.
    foreach(EffectObject myEffect in effectList)
    //if (button0pressed == true)
    //MessageBox.Show("Button Pressed.");
    // myEffect.Start(1, EffectStartFlags.NoDownload);
    if (!myEffect.EffectStatus.Playing)
    // If not, play them
    myEffect.Start(1, EffectStartFlags.NoDownload);
    //button0pressed = true;
    protected override void OnClosed(EventArgs e)
    running = false;
    private void UpdateInputState()
    PlayEffects();
    // Check the joystick state
    JoystickState state = device.CurrentJoystickState;
    device.Poll();
    joyState = "Using JoystickState: \r\n";
    joyState += device.Properties.ProductName;
    joyState += "\n";
    joyState += device.ForceFeedbackState;
    joyState += "\n";
    joyState += state.ToString();
    byte[] buttons = state.GetButtons();
    for(int i = 0; i < buttons.Length; i++)
    joyState += string.Format("Button {0} {1}\r\n", i, buttons[i] != 0 ? "Pressed" : "Not Pressed");
    label1.Text = joyState;
    //if(buttons[0] != 0)
    //button0pressed = true;
    public Form1()
    // Required for Windows Form Designer support
    InitializeComponent();
    // TODO: Add any constructor code after InitializeComponent call
    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    protected override void Dispose( bool disposing )
    if( disposing )
    if (components != null)
    components.Dispose();
    base.Dispose( disposing );
    #region Windows Form Designer generated code
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    public void InitializeComponent()
    this.label1 = new System.Windows.Forms.Label();
    this.SuspendLayout();
    // label1
    this.label1.BackColor = System.Drawing.SystemColors.ActiveCaptionText;
    this.label1.Location = new System.Drawing.Point(8, 8);
    this.label1.Name = "label1";
    this.label1.Size = new System.Drawing.Size(272, 488);
    this.label1.TabIndex = 0;
    // Form1
    this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
    this.BackColor = System.Drawing.SystemColors.ControlText;
    this.ClientSize = new System.Drawing.Size(288, 502);
    this.Controls.AddRange(new System.Windows.Forms.Control[] {
    this.label1});
    this.Name = "Form1";
    this.Text = "Joystick Stuff";
    this.ResumeLayout(false);
    #endregion
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    using (Form1 frm = new Form1())
    frm.Show();
    if (!frm.InitializeInput())
    MessageBox.Show("Couldn't find a joystick.");

    Imho he means the following.
    Your class has performs two tasks:
    Controlling the joystick.
    Managing the joystick with a form.
    So I would recommend, that you separate the WinForm from the joystick code. E.g.
    namespace JoystickCtlLib
    public class JoystickControl
    private Device device = null;
    private bool running = true;
    private ArrayList effectList = new ArrayList();
    private string joyState = "";
    public string State { get { return this.joyState; } }
    public bool InitializeInput() { return true; }
    public void PlayEffects() { }
    private void UpdateInputState() { }
    So that your joystick class does not reference or uses any winform or button.
    btw, there is a thing which is more important than that: Your polling the device in the main thread of your application. This will block your main application. Imho this should be a job for a thread like background worker.

  • How to Call a method from a separate class...?

    Hi there...
    I have a class name HMSCon which has a method named con...
    method con is the one the loads the jdbc driver and establishes the connection....Now!I have a separate class file named TAQueries,this is where i am going to write my SQL Statements...any idea how to use my variables from HMSCon to my TAQueries class???
    here's my code:
    public class HMSCon{
    public static void con(){
    try{
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    String url="jdbc:odbc:;DRIVER=Microsoft Access Driver (*.mdb);DBQ=" +
    "E:/samer/HardwareMonitoringSystem/src/hms/pkg/hmsData.mdb";
    Connection cn = DriverManager.getConnection(url,"Admin", "asian01");
    }catch(Exception s){
    System.err.print(s);}
    here's my seperate class file TAQueries,i put an error message below..
    class TAInfoQueries{
    public void insertNewTA(String TAID,String Fname,String Mname, String Lname,String Age,
    String Bdate,String Haddress,String ContactNo){
    // Statement stmt=cn.createStatement(); ERROR: Cannot find symbol cn.
    // stmt.executeUpdate("INSERT INTO TechnicalAssistants VALUES('sdfas','sdfsdf','sdfdsf','sdfdsf',3,04/13/04,'asdf','asdfsdf')");
    // stmt.close();
    }

    You can try the below code, but it's a bad idea to use staitc member for connection:(
    public class HMSCon{
    static Connection cn;
    static{
    con();
    public static void con(){
    try{
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    String url="jdbc:odbc:;DRIVER=Microsoft Access Driver (*.mdb);DBQ=" +
    "E:/samer/HardwareMonitoringSystem/src/hms/pkg/hmsData.mdb";
    cn = DriverManager.getConnection(url,"Admin", "asian01");
    }catch(Exception s){
    System.err.print(s);}
    here's my seperate class file TAQueries,i put an error message below..
    class TAInfoQueries{
    public void insertNewTA(String TAID,String Fname,String Mname, String Lname,String Age,
    String Bdate,String Haddress,String ContactNo){
    // Statement stmt=HMSCon.cn.createStatement(); ERROR: Cannot find symbol cn.
    // stmt.executeUpdate("INSERT INTO TechnicalAssistants VALUES('sdfas','sdfsdf','sdfdsf','sdfdsf',3,04/13/04,'asdf','asdfsdf')");
    // stmt.close();
    }

  • How to execute the method of a class loaded

    Hi,
    I have to execute the method of com.common.helper.EANCRatingHelper" + version
    version may be 1,2, etc
    if version = 1 the class is com.common.helper.EANCRatingHelper1;
    Iam able to load the class using following code.But iam unable to execute the method of the above class
    Can anybody help me how to execute the method of the class loaded.
    Following is the code
    String version = getHelperClassVersion(requestDate);
    String helperClass = "com.redroller.common.carriers.eanc.helper.EANCRatingHelper" + version;
    Class eancRatingHelper = Class.forName(helperClass);
    eancRatingHelper.newInstance();
    eancRatingHelper.saveRating(); This is not executing throwing an error no method.
    Thanks

    eancRatingHelper.newInstance();Ok, that creates an instance, but you just threw it away. You need to save the return of that.
    Object helper = eancRatingHelper.newInstance();
    eancRatingHelper.saveRating(); This is not executing throwing an error no method.Of course. eancRatingHelper is a Class object, not an instance of your EANCRatingHelper object. The "helper" object I created above is (though it is only of type "Object" right now) -- you have to cast it to the desired class, and then call the method on that.
    Hopefully EANCRatingHelper1 and 2 share a common interface, or you're up the creek.

  • Send a mail to manager in execute method of my eventhandler class.

    Hi everyone,
    I want send an email in execute method of my eventhandler class.
    How can I do this?
    Thanks
    Regards.

    You can use JavaMail, or tcEmailOperations and the NotificationResolver to send email notification. Not sure what help you are looking on this.
    -Bikash

  • Executing a command using Runtime Class

    How to execute a command on a differnet machine with different ipaddress using Runtime Class
    My code is
    String[] cmd = new String[3];
    cmd[0] = "192.1...../c:/WINNT/system32/cmd.exe" ;
    cmd[1] = "/C" ;
    cmd[2] = args[0];
    Runtime rt = Runtime.getRuntime();
    System.out.println("Execing " + cmd[0] + " " + cmd[1]
    + " " + cmd[2]);
    Process proc = rt.exec(cmd);
    // any error???
    int exitVal = proc.waitFor();
    System.out.println("ExitValue: " + exitVal);
    This is not Working

    I have same issue. Actually when I use cmd.exe /c set in java code and if I run the java code in DOS propmt, it retrieves all latest user Environment variable values. But if I run the code in windows batch file, it is not retrieveing the latest user environment values until I reboot my computer, Do you know how to get user environment value with out rebooting machine??????

  • Bug? Unable to add ActionListener using Anonymous class.

    Hi,
    I come accross one strange behaviour while adding ActionListener to RCF component.
    I am trying to add the ActionListener in the managed bean using the Anonymous.
    We can add the actionListener to a button using following methods. I am talking about the the first case. Only this case is not working. Rest other 2 cases are working properly.
    Case 1:
    class MyClass {
         RichCommmandButton btnTest = new RichCommmandButton();
         public MyClass(){
              btnTest.addActionListener(new ActionListener(){
                   public void processAction(ActionEvent event){
    Case 2:
    class MyClass implements ActionListener {
         RichCommmandButton btnTest = new RichCommmandButton();
         public void processAction(ActionEvent event){
    <af:button binding="#{myClassBean.btnTest}" actionListener="#{myClassBean.processAction}"/>
    Case 3:
    class MyClass implements ActionListener {
         RichCommmandButton btnTest = new RichCommmandButton();
         public void addActionLister(){
              //Use EL to add processAction(). Create MethodBinding
              FacesContext facesContext = FacesContext.getCurrentInstance();
    ELContext elContext = facesContext.getELContext();
    ExpressionFactory exprfactory = facesContext.getApplication().getExpressionFactory();
              MethodExpression actionListener =
    exprfactory.createMethodExpression(elContext, "#{myClassBean.processAction}", null, new Class[] { ActionEvent.class });
              btnTest.setActionListener(actionListener);
         public void processAction(ActionEvent event){
    Java has provided good way to use the Anonymous classes while adding the listeners. It should work with the RCF also.
    Some how i found the case 1 usefull, as i can have as many buttons in my screen and i can add the actionListener in one method. Also it is easy to read. I dont have to see the JSPX page to find the associated actionListener method.
    Is it a bug or i am wrong at some point?
    Any sujjestions are welcome.
    - Sujay.

    Hello Sujay,
    As I said in my previous reply, you can try with request scope. In JSF you shouldn't use the binding attribute very often. I agree that anonymous class is nice, but don't forget that you might be dealing with client state saving here so it cannot be perfectly compared with Swing that maintains everything in RAM. What I think happens with you currently is the following:
    1. Bean is created and the button instance as well. The ActionListener is added to the button;
    2. The view is rendered and while it is, the binding attribute is evaluated, resulting in the get method of your bean being called;
    3. Since the method returns something different than null, the button instance created in 1. get used in the component tree;
    4. The tree's state is saved on the client, since your class isn't a StateHolder, nor Serializable, the StateManager doesn't know how to deal with it so it gets discarded from the saved state and maybe from the component itself (would have to debug the render view phase to be sure);
    5. The postback request arrives, the tree is restored. When the handler reaches the button, it call the bean that returns the same instance that was used in the previous tree (since not request scoped), which is BAD because the remaining of the tree is not made of the same object instances, but rather new deserialized ones. The component then gets updated from the client state saved in 4, this might also be where the listener get removed (again debugging would tell you this, but I would tend more with the previous possibility). Note that with a request scoped bean you would have to add the listener during the first get method call (by checking if the component is null) or in the constructor as you're doing right now. It would be a very clean way and you could give the request bean (and thus the listener) access to the conversation scoped bean through injection which is very nice as well.
    6. The invoke application phase occurs and the listener is no longer there.
    Btw, this isn't a rich client issue, more a specification one. I'm curious if it works in a simple JSF RI application, if it does then I guess it would be a bug in Trinidad and/or rich client state handling architecture (using FacesBean).
    Regards,
    ~ Simon

  • How to trigger an ActionListener in different class on click of a tree node

    Hi guyz,
    There are three panels inside my main Frame
    -->TopPanel,MiddlePanel and BottomPanel. I have a tree structure inside a panel. This panel along with couple more panels is in MiddlePanel. My main class is "mainClass.java". Inside that i have an actionListener for a specific button. I need to trigger that actionListener when i click one of the tree nodes in the panel i specified before. The problem is that my MiddlePanel is itself a different ".java" file which is being called in my "mainClass" when a specific button is clicked. There are different buttons in my "mainClass" file and for each one i am creating different MiddlePanels depending on the buttons clicked.
    So, if i click the tree node, i need to remove the MiddlePanel and recreate the MiddlePanel(One that will be created when a different button in the mainClass file is clicked). i.e., i need to trigger the actionListener for that corresponding button. Is there a way to do it?

    use this code to call different panel by selecting tree node.....ok
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.awt.*;
    import java.sql.SQLException;
    import javax.swing.event.*;
    class MainTree extends JFrame
    private static final long serialVersionUID = 1L;
         CardLayout cl = new CardLayout();
         JPanel panel = new JPanel(cl);
    public MainTree() throws Exception
    JPanel blankPanel = new JPanel();
    blankPanel.setBorder(BorderFactory.createTitledBorder("Blank Panel"));
    panel.add(blankPanel,"0");
    panel.add(blankPanel,BorderLayout.CENTER);
         panel.setPreferredSize(new Dimension(800, 100));
         setSize(1000, 700);
    setLocationRelativeTo(null);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    // getContentPane().setLayout(new GridLayout(1,2));
    getContentPane().setLayout(new BorderLayout());
    ConfigTree test = new ConfigTree();
    DefaultMutableTreeNode mainTree = (DefaultMutableTreeNode)test.buildTree();
    JTree tree = new JTree(mainTree);
    tree.setCellRenderer(new DefaultTreeCellRenderer(){
    private static final long serialVersionUID = 1L;
         public Component getTreeCellRendererComponent(JTree tree,Object value,
    boolean sel,boolean expanded,boolean leaf,int row,boolean hasFocus){
    JLabel lbl = (JLabel)super.getTreeCellRendererComponent(tree,value,sel,expanded,leaf,row,hasFocus);
    NodeWithID node = (NodeWithID)((DefaultMutableTreeNode)value).getUserObject();
    if(node.icon != null)lbl.setIcon(node.icon);
    return lbl;
    getContentPane().add(new JScrollPane(tree));
    loadCardPanels((DefaultMutableTreeNode)((DefaultTreeModel)tree.getModel()).getRoot());
    getContentPane().add(panel,BorderLayout.EAST);
         getContentPane().add(blankPanel,BorderLayout.WEST);
    // getContentPane().add(panel);
    tree.addTreeSelectionListener(new TreeSelectionListener(){
    public void valueChanged(TreeSelectionEvent tse){
    NodeWithID node =(NodeWithID)((DefaultMutableTreeNode)((TreePath)tse.getPath())
    .getLastPathComponent()).getUserObject();
    if(node.nodePanel != null)
    String cardLayoutID = node.ID;
    cl.show(panel,cardLayoutID);
    cl.show(panel,"0");
    public void loadCardPanels(DefaultMutableTreeNode dmtn)
    for(int x = 0; x < dmtn.getChildCount(); x++)
    if(((DefaultMutableTreeNode)dmtn.getChildAt(x)).isLeaf() == false)
    loadCardPanels((DefaultMutableTreeNode)dmtn.getChildAt(x));
    NodeWithID node = (NodeWithID)((DefaultMutableTreeNode)dmtn.getChildAt(x)).getUserObject();
    if(node.nodePanel != null)
    String cardLayoutID = node.ID;
    panel.add(cardLayoutID,node.nodePanel);
    public static void main(String[] args) throws Exception{new MainTree().setVisible(true);}
    class ConfigTree
    public Object buildTree() throws Exception
    NodeWithID n0 = new NodeWithID("HelpDesk","");
    NodeWithID n1 = new NodeWithID("Administrator",n0.nodeName);
    NodeWithID n2 = new NodeWithID("Report Form",n1.nodeName,new Tree().getContentPane());
    NodeWithID n3 = new NodeWithID("Create User",n2.nodeName,new JPanel());
    NodeWithID n4 = new NodeWithID("Unlock User",n2.nodeName,new unlockui().getContentPane());
    NodeWithID n5 = new NodeWithID("List User",n2.nodeName,new JPanel());
    NodeWithID n6 = new NodeWithID("Assign Role",n2.nodeName,new AssignRole());
    NodeWithID n9 = new NodeWithID("Operator",n1.nodeName,new JPanel());
    NodeWithID n10 = new NodeWithID("Create Ticket",n9.nodeName,new JPanel());
    NodeWithID n11 = new NodeWithID("My Ticket",n9.nodeName,new JPanel());
    NodeWithID n12 = new NodeWithID("All Ticket",n9.nodeName,new JPanel());
    NodeWithID n13 = new NodeWithID("Event Viewer",n1.nodeName,new JPanel());
    DefaultMutableTreeNode top = new DefaultMutableTreeNode(n0);
    DefaultMutableTreeNode branch1 = new DefaultMutableTreeNode(n1);
    top.add(branch1);
    DefaultMutableTreeNode node1_b1 = new DefaultMutableTreeNode(n2);
    DefaultMutableTreeNode n1_node1_b1 = new DefaultMutableTreeNode(n3);
    DefaultMutableTreeNode n2_node1_b1 = new DefaultMutableTreeNode(n4);
    DefaultMutableTreeNode n3_node1_b1 = new DefaultMutableTreeNode(n5);
    DefaultMutableTreeNode n4_node1_b1 = new DefaultMutableTreeNode(n6);
    branch1.add(node1_b1);
    branch1.add(n1_node1_b1);
    branch1.add(n2_node1_b1);
    branch1.add(n3_node1_b1);
    branch1.add(n4_node1_b1);
    DefaultMutableTreeNode node4_b1 = new DefaultMutableTreeNode(n9);
    DefaultMutableTreeNode n1_node4_b1 = new DefaultMutableTreeNode(n10);
    DefaultMutableTreeNode n2_node4_b1 = new DefaultMutableTreeNode(n11);
    DefaultMutableTreeNode n3_node4_b1 = new DefaultMutableTreeNode(n12);
    node4_b1.add(n1_node4_b1);
    node4_b1.add(n2_node4_b1);
    node4_b1.add(n3_node4_b1);
    DefaultMutableTreeNode node5_b1 = new DefaultMutableTreeNode(n13);
    branch1.add(node1_b1);
    branch1.add(node4_b1);
    branch1.add(node5_b1);
    return top;
    class NodeWithID
    String nodeName;
    String ID;
    JPanel nodePanel;
    ImageIcon icon;
    public NodeWithID(String nn,String parentName)
    nodeName = nn;
    ID = parentName+" - "+nodeName;
    public NodeWithID(String nn,String parentName,Container container)
    this(nn,parentName);
    nodePanel = (JPanel) container;
    nodePanel.setBorder(BorderFactory.createTitledBorder(ID + " Panel"));
    public NodeWithID(String nn,String parentName,JPanel p, ImageIcon i)
    this(nn,parentName,p);
    icon = i;
    public String toString(){return nodeName;}
    }

  • Looking for an add in to separate classes in distinct files

    I'm working on a old program. .cs files are used to store multiples classes.
    Do you know a visual studio extension able to split multiple classes .cs files in separate files ?
    Tanks for help
    Laurent

    Hi Laurent,
    Maybe the re-sharper is what you want to get.
    Reference:
    http://stackoverflow.com/questions/2652901/text-manipulation-split-classes-in-a-single-file-into-mulitple-files
    In addition, since it is not the VS IDE usage issue, I am moving your question to the moderator forum ("Where is the forum for..?"). The owner of the forum will direct you to a right forum.
    Best Regards,
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • ActionListener and Inner Class Issue

    When I add ".addActionListener()" to buttons and create an inner class to listen/handle the action, my main class does not display the GUI. If I remove the ".addActionListener()" from the buttons and the inner class, the GUI displays. Below is my code. Anyone know what is wrong with my code?
    package projects.web;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class AppletGUI{
         // JButtons
         JButton addButton = new JButton("Add");
         JButton removeButton = new JButton("Remove");
         JButton saveButton = new JButton("Save");
         JButton cancelButton = new JButton("Cancel");
         // JPanels
         JPanel containerPanel = new JPanel();
         JPanel optionsPanel = new JPanel();
         JPanel thumbnailPanel = new JPanel();
         JPanel selectionPanel = new JPanel();
         // JScrollPane
         JScrollPane thumbnailScroll;
         public AppletGUI(JRootPane topContainer){
              // Add actionListener
              addButton.addActionListener(new ButtonHandler());
              removeButton.addActionListener(new ButtonHandler());
              saveButton.addActionListener(new ButtonHandler());
              cancelButton.addActionListener(new ButtonHandler());
              // Set border layout
              containerPanel.setLayout(new BorderLayout());
              // Add buttons to target panels
              optionsPanel.add(addButton);
              optionsPanel.add(removeButton);
              selectionPanel.add(saveButton);
              selectionPanel.add(cancelButton);
              // Set size and color of thumbnail panel
              thumbnailPanel.setPreferredSize(new Dimension (600,500));
              thumbnailPanel.setBackground(Color.white);
              thumbnailPanel.setBorder(new LineBorder(Color.black));
              // Add thumbnail panel to scrollpane
              thumbnailScroll = new JScrollPane(thumbnailPanel);
              // Set background color of scrollPane
              thumbnailScroll.setBackground(Color.white);
              // Add subpanels to containerPanel
              containerPanel.add(optionsPanel, BorderLayout.NORTH);
              containerPanel.add(thumbnailScroll, BorderLayout.CENTER);
              containerPanel.add(selectionPanel, BorderLayout.SOUTH);
              // Add containerPanel to rootPane's contentPane
              topContainer.getContentPane().add(containerPanel);
         } // end constructor
         class ButtonHandler implements ActionListener{
              public void actionPerformed(ActionEvent event){
                   new FileBrowser();
              } // end actionPerformed method
         } // end inner class ActionHandler
    } // end AppletGUI class package projects.web;
    import java.awt.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.filechooser.*;
    public class FileBrowser{
         JFileChooser fileChooser = new JFileChooser();
         public FileBrowser(){
              int fileChooserOption = fileChooser.showOpenDialog(null);
         } // end constructor
    } // end class fileBrowser

    Encephalopathic wrote:
    Dan: When it doesn't display, what happens? Do you see any error messages? Also, please take a look at your other thread in this same forum as it has relevance to our conversations in the java-forums.org about whether to add GUIs to root containers or the other way around. /PeteI fiddled with the code some more and it seems that the problem is the inner code. When I changed from the inner class to the main class implementing ActionListener and had the main class implement the actionPerformed method, the GUI displayed and JFileChooser worked as well. I've add this version of the code at the bottom of this message.
    To answer your question: When it doesn't display, what happens? -- The web page loads and is blank. And there are no error messages.
    I took a look at the other thread is this forum (the one relates to our conversation in the other forum); the problem may be the way I've add the GUI. I'll try it the other way and see what happens.
    Thanks,
    Dan
    package projects.web;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class AppletGUI implements ActionListener{
         // JButtons
         JButton addButton = new JButton("Add");
         JButton removeButton = new JButton("Remove");
         JButton saveButton = new JButton("Save");
         JButton cancelButton = new JButton("Cancel");
         // JPanels
         JPanel containerPanel = new JPanel();
         JPanel optionsPanel = new JPanel();
         JPanel thumbnailPanel = new JPanel();
         JPanel selectionPanel = new JPanel();
         // JScrollPane
         JScrollPane thumbnailScroll;
         public AppletGUI(JRootPane topContainer){
              // Add actionListener
              addButton.addActionListener(this);
              removeButton.addActionListener(new ButtonHandler());
              saveButton.addActionListener(new ButtonHandler());
              cancelButton.addActionListener(new ButtonHandler());
              // Set border layout
              containerPanel.setLayout(new BorderLayout());
              // Add buttons to target panels
              optionsPanel.add(addButton);
              optionsPanel.add(removeButton);
              selectionPanel.add(saveButton);
              selectionPanel.add(cancelButton);
              // Set size and color of thumbnail panel
              thumbnailPanel.setPreferredSize(new Dimension (600,500));
              thumbnailPanel.setBackground(Color.white);
              thumbnailPanel.setBorder(new LineBorder(Color.black));
              // Add thumbnail panel to scrollpane
              thumbnailScroll = new JScrollPane(thumbnailPanel);
              // Set background color of scrollPane
              thumbnailScroll.setBackground(Color.white);
              // Add subpanels to containerPanel
              containerPanel.add(optionsPanel, BorderLayout.NORTH);
              containerPanel.add(thumbnailScroll, BorderLayout.CENTER);
              containerPanel.add(selectionPanel, BorderLayout.SOUTH);
              // Add containerPanel to rootPane's contentPane
              topContainer.getContentPane().add(containerPanel);
         } // end constructor
         public void actionPerformed(ActionEvent event){
                   new FileBrowser();
              } // end actionPerformed method
         class ButtonHandler implements ActionListener{
              public void actionPerformed(ActionEvent event){
                   new FileBrowser();
              } // end actionPerformed method
         } // end inner class ActionHandler
    } // end AppletGUI class

  • ActionListener as nested class, anonymous class etc.

    I'm programing my own text editor and im trying to decide in what way to implement an ActionListener for JMenuItems.
    I've got 3 possible ideas of how to implement it.
    First way is to implement the ActionListener in the same class as the JMenu and use a switch statement or a fairly long if-else statement.
    Second way is to create nested classes for each ActoinEvent.
    public class OuterClass {
         //Some random code here...
         private class ActionClass implements ActionListener{
              public void actionPerformed(ActionEvent e) {
                   //Random code.
    }And final way is creating anonymous classes adding ActionListeners for each JMenuItem.
    menuItem.addActionListener(new AbstractAction(){
    public void actionPerformed(ActionEvent e) {
    });But i can't decide on wich of these are the moste correct and accepted way.
    Could someone point me to the right direction?
    Edited by: Idono on Jun 3, 2010 7:36 PM

    the only time you would do the first one would be if you wanted several ActionListeners to do the EXACT SAME THING.
    Then you just write the "actionClass" one time, and have each Component use it.
    private class ActionClass implements ActionListener{
              public void actionPerformed(ActionEvent e) {
                   //Random code.
    menuItem.addActionListener(new ActionClass());
    menuItem1.addActionListener(new ActionClass());
    menuItem2.addActionListener(new ActionClass());
    menuItem3.addActionListener(new ActionClass());But (as the other person mentioned) usually you use anonymous classes because each component has different actions.
    menuItem.addActionListener(new AbstractAction(){
    public void actionPerformed(ActionEvent e) { ... }
    menuItem1.addActionListener(new AbstractAction(){
    public void actionPerformed(ActionEvent e) { ... }
    menuItem2.addActionListener(new AbstractAction(){
    public void actionPerformed(ActionEvent e) { ... }
    });

Maybe you are looking for

  • Remote Update Manager Error.

    Hi all, I'm receiving the following errors in the RemoteUpdateManager log.  I can't get this to clear up.  Did a full re-sync of our Adobe Update Server twice, to be sure it wasn't a corrupted file or download at our end. 01/10/13 10:30:27:181 | [INF

  • Adobe RoboHelp 9 and Adobe Acrobat X Pro

    Hi there. I am currently using Adobe RoboHelp 9 and Adobe Acrobat X Pro (windows) can you please tell me which is the lastest version I can upgrade too and the name of the current version as well.  Cost as well.  thanks

  • Current item Background Color

    Hello Friends, I am facing some problem in changing the bachgroud color of the selected field in block, Basically i want to make visible the current field in a record,not the enire record but just the current item. thanks to all;

  • Gr based iv in miro

    Dear Forum, I have 2 scenario to seek advice. 1) gr based iv is ticked in PO. if GR not made yet, during miro with reference to PO, line item not editable and grey out, correct? 2) gr based iv is ticked in PO. if GR made already, during miro with ref

  • Moving from an old graphite AP to Time Capsule

    I'm about to replace my AP graphite with Time Capsule. Will I be able to simply integrate into (adopt) my existing network name, etc. Or, if I have to define a new network, can I set it up while the old one is running? Or, should I switch off the old