Spliting GUI code to multiple classes

Hi All...
I am trying to design a large scale GUI, and after reading several MVC articles I still have some question on writing the GUI code.
for flexability I split the code to classes:
1) How can I notify on event(exp: actionPerformed), to other widgets located in separated classes which not visible(I attached a code describing this issue, every class would be in separated class)
Note
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
class BaseComp1 implements ActionListener{
    JButton button1;
    public void actionPerformed(ActionEvent e){
        // notify DrawingArea instance, an action performed
class BaseComp2 implements ActionListener{
    JButton button2;
    public void actionPerformed(ActionEvent e){
        // notify DrawingArea instance, an action performed
public class MainComp{ 
    BaseComp1 base1 ;
    BaseComp2 base2;
    public MainComp(){
        base1 = new BaseComp1();
        base2 = new BaseComp2();
public class drawingArea{
    public void drawStuff(){  // draw stuff when actionPerform in one of BaseComp* instance
public class GUI{
    drawingArea drawing;
    MainComp mainComp;
    public GUI(){       // need to connect BaseComp* instances in MainComp instance to
                        // notify drawingArea on actionPerform event
        drawing = new drawingArea();
        mainComp = new MainComp();
}2) If a solution is available but not recommended, is the preferred coding design for large GUI is to write all of it in the same class ?? any suggestion will excepted joyfully..
I would like to thanks in advance for any help
Best Regards
YyYo
Edited by: YyYo on May 25, 2010 12:35 PM
Edited by: YyYo on May 25, 2010 12:36 PM

First of all, I think your code would improve if you don't have GUI classes implement Action or control interfaces. You may wish to have your controls in separate classes.

Similar Messages

  • Accessing the same object from multiple classes.

    For the life of me I can't workout how I can access things from classes that haven't created them.
    I don't want to have to use "new" multiple times in seperate classes as that would erase manipulated values.
    I want to be able to access and manipulate an array of objects from multiple classes without resetting the array object values. How do I create a new object then be able to use it from all classes rather than re-creating it?
    Also I need my GUI to recognize the changes my buttons are making to data and reload itself so they show up.
    All help is good help!
    regards,
    Luke Grainger

    As long as you have a headquarters it shouldn't be to painfull. You simply keep a refrence to your ShipDataBase and Arsenal and all your irrellevant stuff in Headquarters. So the start of your Headquarters class would look something like:
    public class Headquarters{
      public Arsenal arsenal;
      public ShipDatabase db;
    //constructor
      public Headquarters(){
        arsenal = new Arsenal(this, ....);
        db = new ShipDatabase(...);
    //The Arsenal class:
    public class Arsenal{
      public Headquarter hq;
      public Arsenal(Headquarter hq, ....){
        this.hq = hq;
        .Then in your ShipDatabase you should, as good programing goes, keep the arraylist as a private class variable, and then make simple public methods to access it. Methods like getShipList(), addToShipList(Ship ship)....
    So when you want to add a ship from arsenal you write:
    hq.db.addToShipList(ship);
    .Or you could of course use a more direct refrence:
    ShipDatabase db = hq.db;
    or even
    ShipList = hq.db.getShipList();
    but this requires that the shiplist in the DB is kept public....
    Hope it was comprehensive enough, and that I answered what you where wondering.
    Sjur
    PS: Initialise the array is what you do right here:
    //constructor
    shipList = new Ship[6];
    shipList[0] = new Ship("Sentry", 15, 10, "Scout");
    " " " "etc
    shipList[5] = new Ship("Sentry", 15, 10, "Scout");PPS: To make code snippets etc. more readable please read this article:
    http://forum.java.sun.com/faq.jsp#messageformat

  • How to put multiple classes in a single file?

    Hello,
    I'd like to put mutliple classes in a single file. (This
    would be useful for grouping children that are minor extensions of
    parent classes or helper classes that are used by one class only).
    When I tried to put two classes in one file, I got this error
    message:
    5006: An ActionScript file can not have more than one
    externally visible definition: Notation.editField,
    Notation.labelField1
    This is the structure I used. Thanks in advance for your
    help.

    You can declare multiple classes in a single file, but only
    one can be
    within the package declaration. All class declarations
    outside the package
    are invisible to code outside the file.
    package sample
    public class SampleClass
    class SampleClassHelper
    class SampleClassHelper2

  • Multiple classes and drawImage

    First I should start by saying I am VERY new to Java. I have written a program that
    uses multiple classes, and i would like to place boolean b =
    g.drawImage(cardPics[j],x2,yPos,50,75),this); in my class. I have passed Graphics g
    from paint. I am able to use g.drawString, etc, but when I try to drawImage, it will
    not even compile. I CAN use
    boolean b = g.drawImage(cardPics[j],x2,yPos,50,75,this); in paint outside of the
    classes, so I believe I have the image array set up right.
    This is what the compilers reads:
    cannot resolve symbol
    boolean b =g.drawImage(cardPics[j],x2,yPos,50,75,this);
    (The symbol that it is referring to is the period between g and drawImage)
    Any help is greatly appreciated.
    Thankyou
    Apryl

    The last argument to drawImage must be an ImageObserver. Therefore, for this line of code to work, it must be placed in a non-static method of a class that implements ImageObserver.

  • How to use multiple classes for each form

    Hi,
    I have created two forms using screen painter and now i want to use different classes for these two forms .
    I have declared the Sbo Connection in main class i.e. Set Application ,Connection Context() but while connecting to other classes
    for executing the code for that form SAP is not connected to that class.How to use multiple classes functionality i don't able to
    do that.Please provide some sample codes for that as it will be more helpful for me to understand.
    Thanks & Regards,
    Amit

    Hi Amit,
    In fact, its more advisable to use separate classes for every form that you use.  Have one common class, say, for eg., clsMain.cs which has all the connection and connectivity to other classes, wherein, the menu event and item event of this main class, will just be calling the menu / item event of other classes.
    The individual functionality of the child classes will be called from the item / menu event of the respective classes.
    Item event in clsMain.cs will be as below.
    private void oApplication_ItemEvent(string FormUID, ref SAPbouiCOM.ItemEvent pVal, out bool BubbleEvent)
                SAPbouiCOM.Form oForm;
                BubbleEvent = true;
                try
                    if ((pVal.FormTypeEx == "My_Form1Type") && (pVal.EventType != SAPbouiCOM.BoEventTypes.et_FORM_UNLOAD))
                        oForm = oApplication.Forms.GetForm("My_FormType", pVal.FormTypeCount);
                        NameSpace.Repots.ClsForm1.ClsForm1_ItemEvent(oApplication, oCompany, oForm, ref pVal, ref BubbleEvent);
                    if ((pVal.FormTypeEx == "My_Form2Type") && (pVal.EventType != SAPbouiCOM.BoEventTypes.et_FORM_UNLOAD))
                        oForm = oApplication.Forms.GetForm("My_FormType", pVal.FormTypeCount);
                        NameSpace.Repots.ClsForm1.ClsForm2_ItemEvent(oApplication, oCompany, oForm, ref pVal, ref BubbleEvent);
    Now, in the individual classes, you can have their respective item events, which will be called from the main class, and the respective functionalities will occur.
    Hope this helps.
    Regards,
    Satish.

  • Gui code design question ...

    Hi
    I need some designtip. Im doing a gui with tabs. Due to lots of lines of code when setting up each tab, the gui class rows is now heading towards infinity. Additionally the actionperformed method from all the buttons, jtexts and textareas on the tabs ... is also growing towards infinity.
    Simply put: I need design tips from the javamasters. Im quite bad at these kinds of design issues.
    A subquestion is also if there is any tutorials/books/howtos on how to come up with excellent designs, making the coding sweet.
    Thanks in advance !!!

    Hello,
    the topic of this thread is basically Gui code design. So, first of all, i recommend to understand the MVC-pattern, as it is the first step to get an understanding of reusable gui code. The Observer-pattern is no substitute for the MVC-pattern, but the MVC-pattern implies the Observer-pattern. Any MVC related topic will lead you in a second step to the Observer-pattern (see also The Core Java Technologies Tech Tip of January 13, 2006: http://java.sun.com/developer/JDCTechTips/2006/tt0113.html).
    Here are three classes (compiled with Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2_10-b03)), which demonstrate the Observer-pattern in a very simplified way due to the shortness of code:
    The SubjectPanel which notifies the registered ObserverPanel:
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;
    public class SubjectPanel extends JPanel {
      private JTextField textfield = new JTextField("<Type some text>");
      private ChangeListener listener;
      public SubjectPanel(ChangeListener l) {
        listener = l;
        setLayout(new BorderLayout());
        add(textfield, BorderLayout.CENTER);
        textfield.setSelectionStart(0);
        textfield.setSelectionEnd(textfield.getText().length());
        textfield.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent evt) {
            // notify the listener about the changed text
            listener.stateChanged(new ChangeEvent(textfield));
    }The ObserverPanel which wants to be notified when a change in SubjectPanel occures:
    import java.awt.BorderLayout;
    import javax.swing.BorderFactory;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;
    public class ObserverPanel extends JPanel implements ChangeListener {
      private JLabel label = new JLabel();
      public ObserverPanel() {
        label.setBorder(BorderFactory.createEtchedBorder());
        setLayout(new BorderLayout());
        add(label, BorderLayout.CENTER);
      // Implementation of ChangeListener. This method is called by SubjectPanel
      // if the text has changed.
      public void stateChanged(ChangeEvent e) {
        label.setText(((JTextField)e.getSource()).getText());
    }The main class which contains SubjectPanel and ObserverPanel (Note, that this class doesn't know anything about the communication between the embedded panels):
    import java.awt.GridLayout;
    import javax.swing.JFrame;
    import javax.swing.WindowConstants;
    public class AppFrame extends JFrame {
      private SubjectPanel subjectPanel;
      private ObserverPanel observerPanel;
      public AppFrame() {
        setTitle("Observer");
        observerPanel = new ObserverPanel();
        // By passing the ObserverPanel to the SubjectPanel
        // a "one way communication line" is established
        subjectPanel = new SubjectPanel(observerPanel);
        getContentPane().setLayout(new GridLayout());
        getContentPane().add(subjectPanel);
        getContentPane().add(observerPanel);
      public static void main(String[] args) {
        AppFrame frame = new AppFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }Please, be aware of the fact, that due to the simplification this example lacks the model which is part of the MVC-pattern. The SubjectPanel represents the Controller and the ObserverPanel the View.

  • Why do I get multiple class files from 1 java file?

    I wrote a dialog box using gridBagConstraints and another program RunPanel to run it as a java application. For the first time since playing with java, I get multiple class files from a single java file.
    This seems very strange to me and wonder if anyone else has come across this and what could possibly be the reason for it. I did a clean (in Eclipse) just to make sure it wasn't garbage and sure enough they come back again.
    I have ReconPanel.java from which I get ReconPanel.class with the addition of ReconPanel$N.class where N goes from 1 to 5.
    The same thing in RunPanel but here there is only 1 extra file, RunPanel$1.class.
    I'll include the code for RunPanel since it is relatively small:
    package ilan;
    import javax.swing.JFrame;
    public class RunPanel extends JFrame {
         private static final long serialVersionUID = 1L;
         private ReconPanel m_reconPanel = null;
         public RunPanel() {
              super();
              initialize();
          * This method initializes this
         private void initialize() {
            this.setTitle("tester");
            this.setSize(new java.awt.Dimension(138,396));
            this.addWindowListener(new java.awt.event.WindowAdapter() {
                 public void windowClosing(java.awt.event.WindowEvent e) {
                      m_reconPanel.exitPanel();
                      System.exit(0);
              m_reconPanel = new ReconPanel();
              this.getContentPane().add(m_reconPanel);
          * @param args
         public static void main(String[] args) {
              JFrame frame1 = new RunPanel();
              frame1.setVisible(true);
    }  //  @jve:decl-index=0:visual-constraint="10,10"The only thing "unusual" I do is to put a listener on the WindowClosing so that I can go back to ReconPanel and write results to the registry.
    Can anyone tell me what is going on?
    Thanks,
    Ilan

    He IIan,
    Yes, you get number of extra class files based on your number of anomyous class es used. Like in your RunPanel, you get only 1 ..$1.class file, b'coz u have used only 1 annomyous class & i.e WindowAdapter. Take a look at this code :-
    this.addWindowListener(new java.awt.event.WindowAdapter() {
                 public void windowClosing(java.awt.event.WindowEvent e) {
                      m_reconPanel.exitPanel();
                      System.exit(0);
            });Similarly, in your ReconPanel, you must have used such kind of classes 5 times, & hence u get such 5 extra classes. To avoiod such extra classes, if you can directly implement that interface or extend the class, if possible will be best. For example, for each button, u write
    button1.addActionListener(new ActionListener() {
    // Code
    });Instead, of this, its better to implement ActionListener & write
    button1.addActionListener(this);
    public void actionPerformed(ActionEvent ae) {
       if (ae.getSource() == button1) {
       // CODE
       }Likethis, you can get rid of such numerous extra class files. In IDE, if you ask to add actionEvent, it will do the first method. To get rid of it, don't add event in the properties, instead, apply the second method. The same thing applies for anyother event. The first option is worthful, if by implementing, u got to write 5 functions from which u r gonna use just 1 method.
    Hope this clears your question.
    Trupti

  • Help With Multiple Class Objects With Methods

    I am dealing with multiple classes. I am wondering why I am getting an error on this line it's by the bottom
              obj1.array() = newArray[i];
    It gives the array out of bounds. On another note I believe I can change obj1 to just like incomingArray if I wanted correct since it's just a reference because I should be able to do this method sort on any array.
    method : selSort
    input - none
    output - void
    This is where we sort the arary
    Pseudocode Code:
    1 Initialize variable oldlocation to hold spot of smallest number in original array
    2 Initialize variable smallnumber to store smallest number in original array
    3 Initialize new integer array
    4 Set new array length to length of original array
    5 Initialize variable length to store lengh of new array
    6 For i = 0 and continue till i < new array length
    6.1 Find smallest number in original array
    6.2 Put the smallest number in new array
    6.3 Remove smallest number from original array
    7 Copy contents of new array that is sorted to original array
    Basic concept is to repetitively find the smallest
    (or largest) item in the original array. Once smallest
    is found, move it to the next spot in a new array and
    remove it from the old array.
    public void selSort ()
         int oldlocation = 0;
         int smallnumber = 0;
         int [] newArray = obj1.array();
         newArray = new int [obj1.length()];
         int length = newArray.length;
         for (int i = 0; i < newArray.length; i++)
    //          System.out.println("Test 1");
              newArray[i] = obj1.sortSmall();
    //          System.out.println("Test 2");
              smallnumber = obj1.sortSmall();
    //          System.out.println("This is the smallest number " + smallnumber);
              oldlocation = obj1.location(smallnumber);
    //          System.out.println("This is the old location " + oldlocation);
    //          System.out.println("Test 3");
              obj1.removeLocation(oldlocation);
    //          System.out.println("Test 4");
         System.out.println();
         System.out.println("The sorted array looks like");
         for (int k = 0; k < newArray.length; k++)
              System.out.print(newArray[k] + " ");
         System.out.println();
         System.out.println();
         obj1.resize(newArray.length);
         for (int i = 0; i < newArray.length; i++)
              obj1.array()[i] = newArray[i];
         return;

    method : selSort
    input - none
    output - void
    This is where we sort the arary
    Pseudocode Code:
    1 Initialize variable oldlocation to hold spot of smallest number in original array
    2 Initialize variable smallnumber to store smallest number in original array
    3 Initialize new integer array
    4 Set new array length to length of original array
    5 Initialize variable length to store lengh of new array
    6 For i = 0 and continue till i < new array length
    6.1 Find smallest number in original array
    6.2 Put the smallest number in new array
    6.3 Remove smallest number from original array
    7 Copy contents of new array that is sorted to original array
    Basic concept is to repetitively find the smallest
    (or largest) item in the original array. Once smallest
    is found, move it to the next spot in a new array and
    remove it from the old array.
    public void selSort ()
         int oldlocation = 0;
         int smallnumber = 0;
         int [] newArray = obj1.array();
         newArray = new int [obj1.length()];
         int length = newArray.length;
         for (int i = 0; i < newArray.length; i++)
    //          System.out.println("Test 1");
              newArray[i] = obj1.sortSmall();
    //          System.out.println("Test 2");
              smallnumber = obj1.sortSmall();
    //          System.out.println("This is the smallest number " + smallnumber);
              oldlocation = obj1.location(smallnumber);
    //          System.out.println("This is the old location " + oldlocation);
    //          System.out.println("Test 3");
              obj1.removeLocation(oldlocation);
    //          System.out.println("Test 4");
         System.out.println();
         System.out.println("The sorted array looks like");
         for (int k = 0; k < newArray.length; k++)
              System.out.print(newArray[k] + " ");
         System.out.println();
         System.out.println();
         obj1.resize(newArray.length);
         for (int i = 0; i < newArray.length; i++)
              obj1.array() = newArray[i];
         return;

  • [svn] 1062: Adding support to DataGridColumn for multiple class names.

    Revision: 1062
    Author: [email protected]
    Date: 2008-04-01 16:27:42 -0700 (Tue, 01 Apr 2008)
    Log Message:
    Adding support to DataGridColumn for multiple class names.
    Bugs: SDK-15124
    Reviewer: Glenn Ruehle
    QA: Yes
    Ticket Links:
    http://bugs.adobe.com/jira/browse/SDK-15124
    Modified Paths:
    flex/sdk/trunk/frameworks/projects/framework/src/mx/controls/dataGridClasses/DataGridColu mn.as

    That's all well and good, but I've had more times that not where
    people want the entire program, not bits and pieces.Then you missed the whole point of that link.
    We don't want to see bits and pieces of code. We want to see an executable program, but we want an executable program the demonstrates the incorrect behaviour without all the unnecessary code. 90% of the code you posted was not related to your problem. That is we what you do to some basic debugging and remove the parts of code that are not related to the problem so we can concentrate on the code that is related to the problem.

  • Making Java GUI code open source?

    Hi I am a beginner to Java. I was wondering if this was possible.
    Say I write a calculator applet to host on my website for other users to use. Can I make just the GUI code open source so users can modify the appearance of the applet and then save the GUI code to their usernames on the web server, so the next time they logon, the changed calculator appearance will be stored on the web server already. However, the core code should remain the same so new users who sign up won't be using some else's Calculator GUI code.

    IIRC correctly, most databases support storing binary data, so they should be able to store class files. But then you'd have to extract that class file to someplace where it can run everytime. You're probably better off just storing the class files in a separate dir and whopping up a page that uses user info to determine the correct class to load.
    But I agree with malcolmmc that it doesn't make much sense to have people upload their code to your server.

  • How to compile and register a Java CFX tag with multiple class files?

    All-
    If this is the wrong forum for CFX questions, please let me
    know.
    I need to determine how to compile and register a Java CFX
    tag that contains multiple class files. One class file implements
    the CustomTag interface and the other class files implement various
    supporting classes. All of the documentation that I have found
    talks about using a single class file. I am assuming that a JAR
    file will be involved, but I am not sure of the specifics.
    Thanks in advance for your help.
    -Josh

    Yes, it will involve a jar. Use your java IDE (eclipse,
    etcetera ..) to create a jar containing all of the classes. Check
    your ide's documentation for how to create jar files. After you
    have created the jar, place the jar in the CF class path so CF will
    recognize it. For example the {cf_root}/WEB-INF/lib directory. CF
    must be restarted before it will detect the new jar. After
    restarting CF, register the CFX tag in the ColdFusion Administrator
    using the name of the class that implements the CustomTag
    interface.
    Though it is worth noting you can also instantiate java
    classes directly from ColdFusion (ie without using a CFX
    tag).

  • What is the proper way to code a "wrapper" class?

    Basically I want to replace an existing Action with a custom Action, but I want the custom Action to be able to invoke the existing Action.
    The following code works fine. I can create a custom Action using the existing action and the text on the button "paste-from-clipboard" is taken from the existing Action. So everything works great as long as the existing Action extends from AbstractAction.
    However the Action interface does not support the getKeys() method which I used to copy the key/value information from the existing action to the wrapped action. So if you try to create a button from some class that strictly implements the Action interface the key/value data in the wrapped Action will be empy and no text will appear on the button.
    So as the solution I thought I would need to override all the methods in the wrapped Action class to invoke the methods from the originalAction object. That is why all the commented code in the class is there. But then the protected methods cause a problem as the class won't compile.
    Do I just not worry about overriding those two methods? Is this a general rule when creating wrapper classes, you ignore the protected methods?
    import java.awt.*;
    import java.awt.event.*;
    import java.beans.*;
    import javax.swing.*;
    import javax.swing.text.*;
    public class WrappedAction extends AbstractAction
         private Action originalAction;
         public WrappedAction(JComponent component, KeyStroke keyStroke)
              Object key = getKeyForActionMap(component, keyStroke);
              if (key == null)
                   String message = "no input mapping for KeyStroke: " + keyStroke;
                   throw new IllegalArgumentException(message);
              originalAction = component.getActionMap().get(key);
              if (originalAction == null)
                   String message = "no Action for action key: " + key;
                   throw new IllegalArgumentException(message);
              //  Replace the existing Action with this class
              component.getActionMap().put(key, this);
              //  Copy key/value pairs to
              if (originalAction instanceof AbstractAction)
                   AbstractAction action = (AbstractAction)originalAction;
                   Object[] actionKeys = action.getKeys();
                   for (int i = 0; i < actionKeys.length; i++)
                        String actionKey = actionKeys.toString();
                        putValue(actionKey, action.getValue(actionKey));
         private Object getKeyForActionMap(JComponent component, KeyStroke keyStroke)
              for (int i = 0; i < 3; i++)
              InputMap inputMap = component.getInputMap(i);
              if (inputMap != null)
                        Object key = inputMap.get(keyStroke);
                        if (key != null)
                             return key;
              return null;
         public void invokeOriginalAction(ActionEvent e)
              originalAction.actionPerformed(e);
         public void actionPerformed(ActionEvent e)
              System.out.println("custom code here");
              invokeOriginalAction(e);
         public void addPropertyChangeListener(PropertyChangeListener listener)
              originalAction.addPropertyChangeListener(listener);
         protected Object clone()
              originalAction.clone();
         protected void firePropertyChange(String propertyName, Object oldValue, Object newValue)
              originalAction.firePropertyChange(propertyName, oldValue, newValue);
         public Object[] getKeys()
              return originalAction.getKeys();
         public PropertyChangeListener[] getPropertyChangeListeners()
              return originalAction.getPropertyChangeListeners();
         public Object getValue(String key)
              return originalAction.getValue(key);
         public boolean isEnabled()
              return originalAction.isEnabled();
         public void putValue(String key, Object newValue)
              originalAction.putValue(key, newValue);
         public void removePropertyChangeListener(PropertyChangeListener listener)
              originalAction.removePropertyChangeListener(listener);
         public void setEnabled(boolean newValue)
              originalAction.setEnabled(newValue);
         public static void main(String[] args)
              JTextArea textArea = new JTextArea(5, 30);
              JFrame frame = new JFrame("Wrapped Action");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.add(new JScrollPane(textArea), BorderLayout.NORTH);
              frame.add(new JButton(new WrappedAction(textArea, KeyStroke.getKeyStroke("control V"))));
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible( true );

    I can't get the PropertyChangeListener to fire with any source. Here is my test code. Note I am able to add the PropertyChangeListener to the "Paste Action", but I get no output when I add it to the WrappedAction. I must be missing something basic.
    import java.awt.*;
    import java.awt.event.*;
    import java.beans.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    public class WrappedAction3 implements Action, PropertyChangeListener
         private Action originalAction;
         private SwingPropertyChangeSupport changeSupport;
          *  Replace the default Action for the given KeyStroke with a custom Action
         public WrappedAction3(JComponent component, KeyStroke keyStroke)
              Object actionKey = getKeyForActionMap(component, keyStroke);
              if (actionKey == null)
                   String message = "no input mapping for KeyStroke: " + keyStroke;
                   throw new IllegalArgumentException(message);
              originalAction = component.getActionMap().get(actionKey);
              if (originalAction == null)
                   String message = "no Action for action key: " + actionKey;
                   throw new IllegalArgumentException(message);
              //  Replace the existing Action with this class
              component.getActionMap().put(actionKey, this);
              changeSupport = new SwingPropertyChangeSupport(this);
            originalAction.addPropertyChangeListener(this);
            addPropertyChangeListener(this);
          *  Search the 3 InputMaps to find the KeyStroke binding
         private Object getKeyForActionMap(JComponent component, KeyStroke keyStroke)
              for (int i = 0; i < 3; i++)
                  InputMap inputMap = component.getInputMap(i);
                  if (inputMap != null)
                        Object key = inputMap.get(keyStroke);
                        if (key != null)
                             return key;
              return null;
         public void invokeOriginalAction(ActionEvent e)
              originalAction.actionPerformed(e);
         public void actionPerformed(ActionEvent e)
              System.out.println("actionPerformed");
    //  Delegate the Action interface methods to the original Action
         public Object getValue(String key)
              return originalAction.getValue(key);
         public boolean isEnabled()
              return originalAction.isEnabled();
         public void putValue(String key, Object newValue)
              originalAction.putValue(key, newValue);
         public void setEnabled(boolean newValue)
              originalAction.setEnabled(newValue);
         public void xxxaddPropertyChangeListener(PropertyChangeListener listener)
              originalAction.addPropertyChangeListener(listener);
         public void xxxremovePropertyChangeListener(PropertyChangeListener listener)
              originalAction.removePropertyChangeListener(listener);
         public void addPropertyChangeListener(PropertyChangeListener listener)
            changeSupport.addPropertyChangeListener(listener);
        public void removePropertyChangeListener(PropertyChangeListener listener)
            changeSupport.removePropertyChangeListener(listener);
         public void propertyChange(PropertyChangeEvent evt)
             changeSupport.firePropertyChange(evt.getPropertyName(), evt.getOldValue(), evt.getNewValue());
         public static void main(String[] args)
              JTable table = new JTable(15, 5);
              WrappedAction3 action = new WrappedAction3(table, KeyStroke.getKeyStroke("TAB"));
              action.addPropertyChangeListener( new PropertyChangeListener()
                   public void propertyChange(PropertyChangeEvent e)
                        System.out.println(e.getSource().getClass());
              action.putValue(Action.NAME, "name changed");
              Action paste = new DefaultEditorKit.PasteAction();
              paste.addPropertyChangeListener( new PropertyChangeListener()
                   public void propertyChange(PropertyChangeEvent e)
                        System.out.println(e.getSource().getClass());
              paste.putValue(Action.NAME, "name changed");
    }

  • Hand made or generated GUI code, what do proffesional use?

    Hello!
    I am currious about what programs people that work as a programmer use? Is it common that they use programs that generats code like Netbeens for instance? I tryed that program in design mode to make a gui, but when I looked at the code it had generated I could not understand it. When I have seen simple example of gui code that has been hand written I have no trouble to understand the code.
    My opinion is that code is something that others than yourself can read and understand. Wich ofcource is not as simple as it sounds :) The reason I could not understand Netbeens generated code can ofcource be that I am a java beginner.
    So, what I am asking is that:
    1. Is it common that proffesional programmers use programs like Netbeens to generate GUI code ?
    2. The problem that others cant read or understand the code, is it more common that the programmer have used generated code or does the problem as easly occur when the code is hand written?
    Regards
    Martin
    Edited by: onslow77 on Nov 4, 2009 8:02 AM

    gimbal2 wrote:
    but I prefer hand made code; that generated crap is unreadable (all imho of course) and I don't understand it eitherSeconded. Code generation not only creates messy, undocumented code, but it also leads to hidden mistakes which are the worst kind. I'd rather spend a little more time writing the stuff by hand and not only having full control over the outcome, but also have full knowledge of its inner workings.Thirded. For my money, if you're building rich GUIs that are anything other than trivial, it's probably worth investing some effort in writing a layer of code to simplify building those GUIs. Working with vast amounts of raw Swing, for example, is a painful experience. For our Swing products, we've got a whole library of controls we built specific to our apps. We also wrote a layer of abstraction over the whole of Swing itself, but that's another story. Another alternative is to use a Rich Client Platform like Eclipse RCP, which provides a lot of common, rich components, and a framework for deploying them in, out of the box. Both the Eclipse and NetBeans IDEs are built upon their own respective RCP packages, which are available for you to use for your own apps. All those nice editors, drag-n-drop views, trees, menus, shortcuts and what-not, all just there for you to use without having to write any tiresome window-resizing code. Lovely. I don't know about IntelliJ, but I wouldn't be surprised if it, too, did so. Spring RCP is another such package.

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

  • Multiple classes in the same source file

    I'm not sure what this is called, having multiple classes in the same source file. At first I thought it ws called subclassing but then I googled it and found that subclasses are just derived classes. Here's an example of what I'm talking about.
    public class A {
    class B {
    class C {
    }So first of all, what is having multiple classes in the same source file called?
    Secondly, what are the advantages/disadvantages of this?
    Thirdly, can you have a class completely WITHIN a class (same source file but inside the class not outside) and what are the advantages/disadvantages of this?

    Advantage: You can reduce the number of source files specialy when your secondry classes are used only in the public class of the file.
    Disadvantage: Normaly it make things more clear if we have one-to-one correspondance of class and source files. This make things easy when you want to find the java file of a perticuler class file. Also If you later wanted to create a seperate public class with a same name as one of those secondry classes you got lots of changes to do.
    You can avoid this by creating them as nested classes
    ex:-
    public class MyPublicClass{
       private static class MyInnerClass{
    }this way the inner class will create a class file with name "MyPublicClass$MyInnerClass.class" instead of just "MyInnerClass.class"
    And also if you declare the inner class as public you can access them from out side

Maybe you are looking for