Switching jpanels implemented in different classes

Hi,
I'm quite new to swing applications (not to java) and I run into a problem I couldn't solve.
I got a frame and in that frame a jMenu and a jPanel.
I want to create an application where you have to log in, so my first jPanel represents the login (LogInPanel). After a succesful login I want to replace the LogInPanel with an other (LoggedInPanel). This class doesn't belong to my main class and is implemented separatly.
My questions are:
1.)is it possible create a gui like that or is there an other, better way, beside doing everything in one class?
2.)how can I change from the LogInPanel to the LoggendInPannel after I called the jButtonLogin_actionPerformed(ActionEvent e) from the LogInPanel
3.)I also want to change the state of some values in my jMenu after successful login, but I don't know how to get access to them from my LoggedInPannel class.
Thanks for any help
Jens

I don't really understand your problem, but I've had headaches with managing a GUI before (as many programmers have, I'm sure).
My best advice, if the scheme your using to build and manage a GUI is too confusing for you, the programmer, to easily understand/manage, change the scheme. Even if this means recoding a good deal of your program (though, hopefully, you've kept the GUI as seperate from your functional code as possible) it should be worth it.
Perhaps a clearer explination of your problem would help better illustrate your problem?
-Rejun

Similar Messages

  • Adding 2 JPanels, different classes

    Hi,
    I have 3 different classes in 3 files:
    public class Trainer {
      public static void main(String[] args) {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
          f.getContentPane().add(t);
          f.pack();
    }...plus...
    public class Test extends JPanel {
      public int testing(int n) {
        return 0;
    }...and...
    public class Game extends Test implements MouseListener, MouseMotionListener {
        Game() {
            setPreferredSize(new Dimension(800, 600));
            addMouseListener(this);
            addMouseMotionListener(this);
    (...)I would like to add 2 JPanels side by side to the class "Game". I am not allowed to modify "Test" and "Trainer". Class "Trainer" incorporates the main-method.
    How could I do this?
    Thanks for your help!

    Thanks for your replies, they were really helpful :)
    My last question to this topic: I would like to set a background-color for my 2 JPanels - however, the color isn't applied:
        Game() {
            setPreferredSize(new Dimension(800, 600));
            setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
            JPanel actionPanel = new JPanel() { public void paint(Graphics g) {
                actionPanel_paint(g);
            actionPanel.addMouseListener(this);
            actionPanel.addMouseMotionListener(this);
            actionPanel.setBackground(new java.awt.Color(153, 204, 255));
            JPanel statusPanel = new JPanel() { public void paint(Graphics g) {
                statusPanel_paint(g);
            statusPanel.setBackground(new java.awt.Color(204, 255, 204));
            add(actionPanel);
            add(statusPanel);
        public void actionPanel_paint(Graphics g) {
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);       
            Ellipse2D.Double testCircle_action = new Ellipse2D.Double(100, 100, 20, 20);
            g2.setColor(Color.RED);
            g2.draw(testCircle_action);
            g2.fill(testCircle_action);
        public void statusPanel_paint(Graphics g) {
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            Ellipse2D.Double testCircle_status = new Ellipse2D.Double(100, 100, 20, 20);
            g2.setColor(Color.BLACK);
            g2.draw(testCircle_status);
            g2.fill(testCircle_status);
        }

  • Updating JPanel with buttons from a different class

    I have a JPanel in a class that has a gridlayout with buttons in it for a game board. And my problem is that when I want to update a button using setIcon() the button doesn't change in the GUI because the buttons are in a different class. The JPanel is in a Client class and the buttons are in a GamePlugin class. I've tried a bunch of different things but none of them worked or it was way too slow. I'm sure theres an easy way to do it that I'm not seeing. Any suggestions? Heres part of my code for updating the GUI.
    private JPanel boardPanel = new JPanel(); 
    Container cP = getContentPane();
    cP.add(boardPanel, BorderLayout.WEST);
    boardPanel.setPreferredSize(new Dimension(400, 400));
    boardPanel.setLayout(new GridLayout(8, 8));
    cP.add(optionsPanel, BorderLayout.CENTER);
          * Gets the board panel from the selected plugin.
         public void drawGameBoard(GamePlugin plugin) {
              board = (OthelloPlugin)plugin;
              boardPanel = board.getBoardPanel();
              for (int i = 0; i < GamePlugin.BOARD_SIZE; i++)
                   for (int j = 0; j < GamePlugin.BOARD_SIZE; j++) {
                        board.boardButtons[i][j].setActionCommand("" + i + "" + j);
                        board.boardButtons[i][j].addActionListener(this);
          * This method takes a GameBoard and uses it to update this class' data
          * and GUI representation of the board.
         public void updateBoard(GamePlugin updatedBoard) {
              board = (OthelloPlugin)updatedBoard;
              for (int i = 0; i < GamePlugin.BOARD_SIZE; i++) {
                   for (int j = 0; j < GamePlugin.BOARD_SIZE; j++) {
                        int cell = board.getCell(i,j);
                        if (cell == OthelloPlugin.PLAYER1){
                             board.boardButtons[i][j].setIcon(black);
                        else if (cell == OthelloPlugin.PLAYER2)
                             board.boardButtons[i][j].setIcon(white);
                        else
                             board.boardButtons[i][j].setText("");
         }

    txp200:
    I agree that a call to validate() , possibly repaint(), should fix your problem. In the class with the panel that the buttons are on, i would create a static repaint method that call panel.repaint(). You can then call that method in your other class. Just make sure u only use methods to change the properties of the button, never make a make a new one, as then you will lose the association with the panel. Hope this helps.
    -- Brady E

  • Can't call or execute of different class files in a main program

    Hi, I got a main program which can call 3 different classes. The main program have an implicit-choice List as a starting menu. If one of the file is selected, the files will call out and display it. However, i managed to call the 1st 2 files, and the 3rd files can't display anything after selected.
    I enclosed my code as below:
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    public class Catalogues extends Form implements CommandListener {
         private Displayable parent;
         private Display display;
         private List Cata;
         private Boots bo;
         private Higheels hHeels;
         private Sandals sand;
         private Slippers sp;
        private Command backCommand = new Command("Back", Command.BACK, 1);
        private Command viewCommand = new Command("View", Command.SCREEN, 1);
        private String[] options = {"Boots", "High Heels","Sandals", "Slippers"};
         public Catalogues(Display d, Displayable p) {
              super("Welcome to Footwear World");
              Cata = new List("Select Option", List.IMPLICIT, options, null);
              display = d;
            parent = p;
              addCommand(backCommand);
              addCommand(viewCommand);
              setCommandListener(this);
         public void commandAction(Command c, Displayable d) {
         if(d==parent && c==List.SELECT_COMMAND){
              switch(parent.getSelectedIndex()){
                   case 0:
                           if(bo==null){
                              bo = new Boots(display,parent);
                             display.setCurrent(bo);
                              break;
                   case 1:
                           if(hHeels==null){
                              hHeels = new Higheels(display,parent);
                             display.setCurrent(hHeels);
                              break;
                   case 2:
                           if(sand==null){
                              sand = new Sandals(display,parent);
                             display.setCurrent(sand);
                              break;
                   case 3:
                           if(sp==null){
                              sp = new Slippers(display,parent);
                             display.setCurrent(sp);
                              break;
                   default:
             else if (c==backCommand) {
                       display.setCurrent(parent);
    }If the 3rd option is selected, i'll display above mentioned layout which contain a list to select too.
    After build this project on WToolkit. It shown an error message which is as below:
    Project settings saved
    Building "SelectCustest"
    C:\WTK22\apps\SelectCustest\src\Catalogues.java:29: cannot resolve symbol
    symbol : method getSelectedIndex ()
    location: class javax.microedition.lcdui.Displayable
    switch(parent.getSelectedIndex()){
    ^
    1 error
    com.sun.kvem.ktools.ExecutionException
    Build failed
    May i know what is problem am i facing now? And how to solve it.
    Thanks.

    Thanks to all for your thoughts and replies. I liked the xargs suggestion, so I tried that first. I would have (may still) try the stdin suggestion, followed by writing the grep output to a file.
    xargs does work, in a way I didn't expect it to, but that could be due to my inexperience with the workings of the shell.
    here's a line from my test script
    cat file | grep foo | xargs java com.company.test.TEchoArghere's the contents of 'file'
    123foo
    abc
    qafoozv
    qaz
    wsx
    qwefoort
    zxcfooh
    sdfghhere's the output from the test class, which just echos any arguments
    ::number of args: 4
    ::args[0] 123foo
    ::args[1] qafoozv
    ::args[2] qwefoort
    ::args[3] zxcfoohso xargs appends all the values from grep into an argument list and call the java class once.
    when I took xargs out of the script, nothing was passed to the class:
    ::number of args: 0this was really interesting and something to keep in my back pocket for future use.
    Thanks again to all.
    Tom

  • Java interfaces and containers in different classes

    Hi in trying to create an interface in Java that will be the basis for other classes to populate areas on in in certain panels.
    So for example I have a default size for a screen and some default buttons that should appear on it. These are all setup in a class called ScriptyUI. Within ScriptyUI I want to set up several rows where each row will be populated with the container of a different class. So for instance another class called NetworkAreaUI will create all the buttons and boxes needed for the NetworkUI class along with the actionListeners for each of the buttons. I therefore want to add this into one of the rows of the ScriptyUI class.
    Each time I try and call the networkAreaUI class from within the ScriptyUI class I get an error stating that a container is expected and not a window.
    Any Ideas?
    I have placed everything within the ScriptyUI class and it works, however this class soon becomes so large it is quite unmanageble.
    What I am also trying is something similar to these code snippets:
    I want to add this.............:
    public class NetworkAreaUI extends JFrame implements Runnable, ActionListener
        private JPanel networkPanel;
        private JTextField netPath;
        private JButton remove;
        private JButton add;
        private JLabel netDrives;
        private JComboBox driveList;
        private int driveCount = 0;
        private Thread adds;
        private Thread lists;
        private Thread removes;
        protected NetworkDrive myNetworkDrive;
    public NetworkAreaUI()
            Container cp = getContentPane();
            cp.setLayout(new BorderLayout());
            networkPanel = new JPanel();
            networkPanel.setLayout(new GridLayout(3,4));
            netDrives = new JLabel("Type Network Drive Location");
            networkPanel.add(netDrives);
            remove = new JButton("Remove");
            networkPanel.add(remove);
            netPath = new JTextField("\\\\Server\\Share\\Name",20);
            networkPanel.add(netPath);
            add = new JButton("add");
            networkPanel.add(add);
            driveList = new JComboBox();
            networkPanel.add(driveList);
            networkPanel.setVisible(false);
            cp.add(networkPanel);
            //Adds action listeners
            //Adds MenuSelection to the menu's
            remove.addActionListener(this);
            add.addActionListener(this);
            driveList.addActionListener(this);(then there is code for the action listeners )........into this.....
    public class ScriptyUI extends JFrame// implements ActionListener, Runnable
        private final int FRAME_WIDTH = 600;
        private final int FRAME_HEIGHT = 540;
        private JPanel rows;
        private JPanel row1;
        private JPanel row2;
        private JPanel row3;
        private JPanel row4;
        private JPanel button;
        private JPanel outputArea;
        private JTextArea message;
        private JPanel selection;
        private JButton vbs;
        private JButton bat;
       /* private JPanel networkPanel;
        private JTextField netPath;
        private JButton remove;
        private JButton add;
        private JLabel netDrives;
        private JComboBox driveList;
        private int driveCount = 0;
        private JMenuBar menu;
        private JMenu fileMenu;
        private JMenu helpMenu;
        private JMenuItem restartMenu;
        private JMenuItem quitMenu;
        private JMenuItem show;
        protected NetworkDrive myNetworkDrive;
        protected NetworkAreaUI myNetGui;
        private JButton back;
        private JButton next;
        private JTextArea output;
        private JScrollPane jsp;
        private JButton save;
        private JFileChooser fc;
        private String fileType;
        // private Thread thread;
    /*   private Thread adds;
        private Thread lists;
        private Thread removes;
        private Thread nextOne;
        private Thread saveIt;*/
      //  private Thread;
        public ScriptyUI(String title)
            super(title);
            myNetworkDrive = new NetworkDrive();
            myNetworkDrive.reset();
         //   myNetGui = new NetworkAreaUI();
            setUpGui();
    public void setUpGui()
            setSize(FRAME_WIDTH,FRAME_HEIGHT);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            Container cp = getContentPane();
            cp.setLayout(new BorderLayout());
            //Setup Menu Bar
            menu = new JMenuBar();
            setJMenuBar(menu);
            fileMenu = new JMenu("File");
            helpMenu = new JMenu("Help");
            restartMenu = new JMenuItem("Start Over");
            quitMenu = new JMenuItem("Quit game");
            show = new JMenuItem("Show Drives");
            //Construct Menu Bar
            menu.add(fileMenu);
            menu.add(helpMenu);
            fileMenu.add(restartMenu);
            fileMenu.add(quitMenu);
            fileMenu.add(show);
            rows = new JPanel();
            rows.setLayout(new GridLayout(6,1));
            //Create Message area and populate with Text.
            row1 = new JPanel();
            message = new JTextArea("Select which format you " +
                    "would like the Script to be in. Visual Basic" +
                    "Script or Batch Script", 3, 30);
            row1.add(message);
            rows.add(row1);
            //setup the selection screen
            row2 = new JPanel();
            selection = new JPanel();
            selection.setLayout(new BorderLayout());
            //sets the buttons on the selection screen
            vbs = new JButton("Visual Basic Scripts");
            selection.add(vbs, BorderLayout.NORTH);
            bat = new JButton("Batch Scripts");
            selection.add(bat, BorderLayout.SOUTH);
            row2.add(selection, BorderLayout.CENTER);
            rows.add(row2);
            row3 = new JPanel();
            myNetGui = new NetworkAreaUI();
            row3.add(myNetGui);
            rows.add(row3);
    cp.add(rows, BorderLayout.CENTER);Any help or guidance will be greatly appreciated,

    Encephalopathic wrote:
    good
    Thanks :)
    Are you sure that you want to use a Container and not a JPanel or JComponent? This is Swing after all.Hi i set up the method as below which seemed to work:
    public Container setup()
            networkPanel = new JPanel();
            networkPanel.setLayout(new GridLayout(5,2));
            netDrives = new JLabel("Type Network Drive Location:");
            networkPanel.add(netDrives);
            typeName = new JLabel("Type Drive Letter:");
            networkPanel.add(typeName);
            netPath = new JTextField("\\\\Server\\Share\\Name",20);
            networkPanel.add(netPath);
            nameDrive = new JTextField("X",1);
            networkPanel.add(nameDrive);
            add = new JButton("add");
            networkPanel.add(add);
            remove = new JButton("Remove");
            networkPanel.add(remove);
            driveList = new JComboBox();
            networkPanel.add(driveList);
            driveNames = new JComboBox();
            networkPanel.add(driveNames);
            //Adds action listeners
            //Adds MenuSelection to the menu's
            remove.addActionListener(this);
            add.addActionListener(this);
            driveList.addActionListener(this);
            //return the content panel
            return networkPanel;
    }it is set up in the header to return container
    public Container setup()
    .but i actually return networkPanel which is setup as a JPanel.
    So have now changed it to read:
    public JPanel setup()
    .I think that should be a little better? is it?
    Thanks for the heads up.
    Ian

  • How do I access a gui component in a different class?

    I have a jpanel (mainwindow) in a japplet. mainwindow loads and displays a jpanel form (content1). How do I code a button on conent1 so that mainwindow loads and displays a different jpanel form(content2)? mainwindow, content1, and content2 are all in different classes/packages. Thanks in advance!

    Let your JPanel content1 forward its ActionEvents to its parent. For instance, you could define your content1 as follows:
    public class Content1 extends JPanel
        private ArrayList<ActionListener> actionListeners;
        private JButton myButton;
              public Content1()
             actionListeners = new ArrayList<ActionListener>();
             myButton = new JButton("Test");
             myButton.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                             forwardAction(e);
              public void addActionListener(ActionListener listener) {
             actionListeners.add(listener);
        protected void forwardAction(ActionEvent e) {
          for (ActionListener l: actionListeners) {
               l.actionPerformed(e);
    }Then you could let your mainWindow listen to content1:
    // in your main windows' code:
    Content1 content1 = new Content1();
    content1.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
              swapPane(e);    // create a method swapPane in your mainwindow that handles the switch to content2.
    });

  • Two equal objects, but different classes?

    When programming on binding Referenceable object with JDK version 1.5.0_06, I have encountered a very strange phenomenon: two objects are equal, but they belong to different classes!!!
    The source codes of the program bind_ref.java are listed as below:
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    import java.lang.*;
    import java.io.*;
    import java.util.*;
    import javax.naming.*;
    import javax.naming.spi.ObjectFactory;
    import java.util.Hashtable;
    public class bind_ref {
    public static void main( String[] args ) {
    // Set up environment for creating the initial context
    Hashtable env = new Hashtable();
    env.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory" );
    env.put( Context.PROVIDER_URL, "file:/daniel/" );
    Context ctx = null;
    File f = null;
    Fruit fruit1 = null, fruit2 = null;
    byte [] b = new byte[10];
    try {
    ctx = new InitialContext( env );
    Hashtable the_env = ctx.getEnvironment();
    Object [] keys = the_env.keySet().toArray();
    int key_sz = keys.length;
    fruit1 = new Fruit( "Orange" );
         SubReference ref1 = fruit1.getReference();
    ctx.rebind( "reference", fruit1 );
         fruit2 = ( Fruit )ctx.lookup( "reference" );
         System.out.println( "ref1's class = (" + ref1.getClass().toString() + ")" );
         System.out.println( "fruit2.myRef's class = (" + fruit2.myRef.getClass().toString() + ")" );
         System.out.println( "( ref1 instanceof SubReference ) = " + ( ref1 instanceof SubReference ) );
         System.out.println( "( fruit2.myRef instanceof SubReference ) = " + ( fruit2.myRef instanceof SubReference ) );
         System.out.println( "ref1.hashCode = " + ref1.hashCode() + ", fruit2.myRef.hashCode = " + fruit2.myRef.hashCode() );
         System.out.println( "ref1.equals( fruit2.myRef ) = " + ref1.equals( fruit2.myRef ) );
    } catch( Exception ne ) {
    System.err.println( "Exception: " + ne.toString() );
    System.exit( -1 );
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    All the outputs are shown as below:
    =======================================================
    Fruit: I am created at Mon Jun 18 11:35:13 GMT+08:00 2007
    SubReference: I am created at Mon Jun 18 11:35:13 GMT+08:00 2007
    --------- (i)subref.hashCode() = (-1759114666)
    SubReference: I am created at Mon Jun 18 11:35:13 GMT+08:00 2007
    --------- (i)subref.hashCode() = (-1759114666)
    FruitFactory: obj's class = (class javax.naming.Reference)
    FruitFactory: obj's hashCode = -1759114666
    FruitFactory: obj = (Reference Class Name: Fruit
    Type: fruit
    Content: Orange
    FruitFactory: ( obj instanceof SubReference ) = false
    FruitFactory: subref_class_name = (Fruit)
    Fruit: I am created at Mon Jun 18 11:35:13 GMT+08:00 2007
    ref1's class = (class SubReference)
    fruit2.myRef's class = (class javax.naming.Reference)
    ( ref1 instanceof SubReference ) = true
    ( fruit2.myRef instanceof SubReference ) = false
    ref1.hashCode = -1759114666, fruit2.myRef.hashCode = -1759114666
    ref1.equals( fruit2.myRef ) = true
    ========================================================
    I hightlight the critical codes and outputs related to the strangeness with bold texts.
    Who can tell me what happens? Is it really possible that two objects belonging to different classes are equal? If so, why that?

    It can also depend on how you implement the equals method.
    class Cat {
        String name;
        Cat(String n) {
            name = n;
    class Dog {
        String name;
        Dog(String n) {
            name = n;
        public boolean equals(Object o) {
            return name.equals(o.name);
        public static void main(String[] args) {
            Dog d = new Dog("Fred");
            Cat c = new Cat("Fred");
            System.out.println(d.equals(c));
    }

  • How to call to another form declare in different class ???????

    hi, i'm beginner in j2me...
    I was wondering how to call to other form(class) in the current form...
    For example,
    public class A extends MIDlet implements CommandListener
    public void commandAction(Command d,Displayable s)
    if (d==*OKCommand*)
    if press this OK command, it will be able to show another form declared in the different class...
    How to make it able to call to other form/class(eg.classB)????
    public class B
    //form that will be shown after pressed command OK in class A
    please help if you know...Thanks a lot..... =)

    you MUST have a reference to the other class or MIDlet in the current MIDlet ...
    i think that i have answered to these kind of questions a few month ago.. you should use the 'search' engine to find the topic..
    CLDC and MIDP forum is not a huge forum compare to Java Programming forum so it will be easy !

  • Actionlistener in different class then the button

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

    URgent help need.
    i need to link the page together : by clicking the button on the index page.
    it will show the revelant class file. I have try my ationPerformed method to the actionlistener, it cannot work.
    Thanks in advance.
    // class mtab
    // the tab menu where it display the gui
    import javax.swing.*;
    import java.awt.*;
    public class mtab {
    private static final int frame_height = 480;
    private static final int frame_width = 680;
    public static void main (String [] args){
    JFrame frame = new JFrame ("Mrt Timing System");
    frame.setDefaultCloseOperationJFrame.EXIT_ON_CLOSE);
    frame.setSize(frame_width,frame_height);
    JTabbedPane tp = new JTabbedPane ();
    tp.addTab("Mrt Timing System", new sample());
    frame.setResizable(false);
    frame.getContentPane().add(tp);
    frame.setSize(680,480);
    frame.show();
    // index page
    // class sample
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.Image;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    import java.text.*;
    import javax.swing.border.*;
    class sample extends JPanel implements ActionListener
    //button
    private JButton TimingButton;
    private JButton ViewButton;
    private JButton FrequencyButton;
    private JButton calculateButton;
    private CardLayout mycard;
    private JPanel SelectXPanel;
    private JPanel SelectYPanel;
    private JPanel SelectZPanel;
    private JPanel bigFrame, mainPane;
    // constructor
    public sample() {
    super(new BorderLayout());
    //create the object
    //create button and set it
    TimingButton = new JButton("MRT Timing Calculator");
    TimingButton.addActionListener(this);
    ViewButton = new JButton("View First and Last Train");
    ViewButton.addActionListener(this);
    FrequencyButton = new JButton("Show the Train Frequency");
    FrequencyButton.addActionListener(this);
    // Layout
    //Lay out the button in a panel.
    JPanel buttonPane = new JPanel(new GridLayout(3,0));
    buttonPane.add(TimingButton);
    buttonPane.add(ViewButton);
    buttonPane.add(FrequencyButton);
    // Layout the button panel into another panel.
    JPanel buttonPane2 = new JPanel(new GridLayout(0,1));
    buttonPane2.add(buttonPane);
    tfrequency x = new tfrequency();
    fviewl2 y = new fviewl2 ();
    timing z = new timing ();
    JPanel SelectXPanel = new JPanel(new GridLayout(0,1));
    SelectXPanel.add(x);
    JPanel SelectYPanel = new JPanel(new GridLayout(0,1));
    SelectYPanel.add(y);
    JPanel SelectZPanel = new JPanel(new GridLayout(0,1));
    SelectZPanel.add(z);
    // Layout the button by putting in between the rigid area
    JPanel mainPane = new JPanel(new GridLayout(3,0));
    mainPane.add(Box.createRigidArea(new Dimension(0,1)));
    mainPane.add(buttonPane2);
    mainPane.add(Box.createRigidArea(new Dimension(0,1)));
    mainPane.setBorder(new TitledBorder("MRT Timing System"));
    // x = new tfrequency();
    // The overall panel -- divide the frame into two parts: west and east.
    JPanel bigFrame = new JPanel(new GridLayout(0,2));
    bigFrame.add(mainPane, BorderLayout.WEST);
    //bigFrame.add(x,BorderLayout.EAST); // this is where i want to link the page
    // this page being the index page. there being nothing to display.
    add(bigFrame);
    //Create the GUI and show it. For thread safety,
    public void actionPerformed (ActionEvent e){
    if (e.getSource() == TimingButton ){
    JPanel bigFrame = new JPanel(new GridLayout(0,2));
    bigFrame.add(mainPane, BorderLayout.WEST);
    bigFrame.add(SelectZPanel,BorderLayout.EAST);
    add(bigFrame);
    else if (e.getSource() == ViewButton ){
    JPanel bigFrame = new JPanel(new GridLayout(0,2));
    bigFrame.add(mainPane, BorderLayout.WEST);
    bigFrame.add(SelectYPanel,BorderLayout.EAST);
    add(bigFrame);
    else if (e.getSource() == FrequencyButton ){
    JPanel bigFrame2 = new JPanel(new GridLayout(0,2));
    bigFrame.add(mainPane, BorderLayout.WEST);
    bigFrame.add(SelectXPanel,BorderLayout.EAST);
    add(bigFrame);
    // Train Frequency Page
    // class fviewl2
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.Image;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    import java.text.*;
    import javax.swing.border.*;
    class fviewl2 extends JPanel implements ActionListener
    //Labels to identify the fields
    private JLabel stationLabel;
    private JLabel firstLabel;
    private JLabel lastLabel;
    //Strings for the labels
    private static String station = "MRT Station:";
    private static String first = "First Train Time:";
    private static String last = "Last Train Time:";
    //Fields for data entry
    private JFormattedTextField stationField;
    private JFormattedTextField firstField;
    private JFormattedTextField lastField;
    //button
    private JButton homeButton;
    private JButton cancelButton;
    private JButton calculateButton;
    public fviewl2()
    super(new BorderLayout());
    //create the object
    //Create the Labels
    stationLabel = new JLabel(station);
    firstLabel = new JLabel (first);
    lastLabel = new JLabel (last) ;
    //Create the text fields .// MRT Station:
    stationField = new JFormattedTextField();
    stationField.setColumns(10);
    stationField.setBounds(300,300,5,5);
    //Create the text fields // First Train Time:
    firstField = new JFormattedTextField();
    firstField.setColumns(10);
    firstField.setBounds(300,300,5,5);
    //Create the text fields //Last Train Time:
    lastField = new JFormattedTextField();
    lastField.setColumns(10);
    lastField.setBounds(300,300,5,5);
    //Tell accessibility tools about label/textfield pairs, matching label for the field
    stationLabel.setLabelFor(stationField);
    firstLabel.setLabelFor(firstField);
    lastLabel.setLabelFor(lastField);
    //create button and set it
    homeButton = new JButton("Home");
    //homeButton.addActionListener(this);
    cancelButton = new JButton("Cancel");
    cancelButton.addActionListener(this);
    calculateButton = new JButton("Get Time");
    // Layout
    //MRT Station Label // insert into the panel
    JPanel StationPane = new JPanel(new GridLayout(0,1));
    StationPane.add(stationLabel);
    //MRT Station input field // insert into the panel
    JPanel StationInput = new JPanel(new GridLayout(0,1));
    StationInput.add(stationField);
    //Get Time Button // insert into the panel
    JPanel GetTime = new JPanel(new GridLayout(0,1));
    GetTime.add(calculateButton);
    //Lay out the labels in a panel.
    JPanel FlabelL = new JPanel(new GridLayout(0,1));
    FlabelL.add(firstLabel);
    FlabelL.add(lastLabel);
    // Layout the fields in a panel
    JPanel FFieldL = new JPanel(new GridLayout(0,1));
    FFieldL.add(firstField);
    FFieldL.add(lastField);
    //Lay out the button in a panel.
    JPanel buttonPane = new JPanel(new GridLayout(1,0));
    buttonPane.add(homeButton);
    buttonPane.add(cancelButton);
    // Layout all components in the main panel
    JPanel mainPane = new JPanel(new GridLayout(4,2));
    mainPane.add(StationPane);
    mainPane.add(StationInput);
    mainPane.add(Box.createRigidArea(new Dimension(0,1)));
    mainPane.add(GetTime);
    mainPane.add(FlabelL);
    mainPane.add(FFieldL);
    mainPane.add(Box.createRigidArea(new Dimension(0,1)));
    mainPane.add(buttonPane);
    mainPane.setBorder(new TitledBorder("View First and Last Train"));
    JPanel leftPane = new JPanel(new GridLayout(1,0));
    leftPane.add(Box.createRigidArea(new Dimension(0,1)));
    leftPane.add(mainPane);
    leftPane.add(Box.createRigidArea(new Dimension(0,1)));
    JPanel hahaFrame = new JPanel(new GridLayout(0,1));
    hahaFrame.add(Box.createRigidArea(new Dimension(0,1)));
    hahaFrame.setBorder(BorderFactory.createEmptyBorder(30, 10, 80, 150));
    hahaFrame.add(Box.createRigidArea(new Dimension(0,1)));
    JPanel bigFrame = new JPanel();
    bigFrame.add(hahaFrame, BorderLayout.NORTH);
    bigFrame.add(leftPane, BorderLayout.CENTER);
    add(bigFrame, BorderLayout.CENTER);
    //Create the GUI and show it. For thread safety,
    private void cancelButtonClicked()
    stationField.setText("");
    firstField.setText("");
    lastField.setText("");
    public void actionPerformed (ActionEvent e){
    if (e.getSource() == cancelButton){
    cancelButtonClicked();
    }

  • Updating Swing components from a different class

    I would like to use the JTextArea component in a JFrame to display fast updating text from my application. My application is very simple. When the app launches the GUI is created then my application engine would start processing and displaying text data into the GUI. After reading about Thread safety when using Swing components I concluded it would not be a good idea for my app engine class to update the JTextArea class directly using methods such as .append(String).
    I would be grateful for any suggestions on how I should approach updating Swing components from different classes.
    Many Thanks in advance Sean

    Hi
    Why don't you just implement a basic callback method?
    To do this the right way you should probably define a simple Interface that has a public method like updateProcessText(String s). Your swing class then implements this interface, basically forcing it to provide the public method you defined (this is no different than implementing ActionListener, which forces you to define actionPerformed). Secondly modify your processing class, so that it take's a class that implements the interface you just created, as one of the arguments in it's constructor. Lastly assign the argument from your construnctor to a private var - this will enable your processing class to have a handle to your swing class and update it as it pleases.
    This might sound very complex, but it's really simple once you've done it once.

  • How can I use the same thread pool implementation for different tasks?

    Dear java programmers,
    I have written a class which submits Callable tasks to a thread pool while illustrating the progress of the overall procedure in a JFrame with a progress bar and text area. I want to use this class for several applications in which the process and consequently the Callable object varies. I simplified my code and looks like this:
            threadPoolSize = 4;
            String[] chainArray = predock.PrepareDockEnvironment();
            int chainArrayLength = chainArray.length;
            String score = "null";
            ExecutorService executor = Executors.newFixedThreadPool(threadPoolSize);
            CompletionService<String> referee = new ExecutorCompletionService<String>(executor);
            for (int i = 0; i < threadPoolSize - 1; i++) {
                System.out.println("Submiting new thread for chain " + chainArray);
    referee.submit(new Parser(chainArray[i]));
    for (int chainIndex = threadPoolSize; chainIndex < chainArrayLength; chainIndex++) {
    try {
    System.out.println("Submiting new thread for chain " + chainArray[chainIndex]);
    referee.submit(new Parser(chainArray[i]));
    score = referee.poll(10, TimeUnit.MINUTES).get();
    System.out.println("The next score is " + score);
    executor.shutdown();
    int index = chainArrayLength - threadPoolSize;
    score = "null";
    while (!executor.isTerminated()) {
    score = referee.poll(10, TimeUnit.MINUTES).get();
    System.out.println("The next score is " + score);
    index++;
    My question is how can I replace Parser object with something changeable, so that I can set it accordingly whenever I call this method to conduct a different task?
    thanks,
    Tom                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    OK lets's start from the beginning with more details. I have that class called ProgressGUI which opens a small window with 2 buttons ("start" and "stop"), a progress bar and a text area. It also implements a thread pool to conducts the analysis of multiple files.
    My main GUI, which is much bigger that the latter, is in a class named GUI. There are 3 types of operations which implement the thread pool, each one encapsulated in a different class (SMAP, Dock, EP). The user can set the necessary parameters and when clicking on a button, opens the ProgressGUI window which depicts the progress of the respective operation at each time step.
    The code I posted is taken from ProgressGui.class and at the moment, in order to conduct one of the supported operations, I replace "new Parser(chainArray)" with either "new SMAP(chainArray[i])", "new Dock(chainArray[i])", "new EP(chainArray[i])". It would be redundant to have exactly the same thread pool implementation (shown in my first post) written 3 different times, when the only thing that needs to be changed is "new Parser(chainArray[i])".
    What I though at first was defining an abstract method named MainOperation and replace "new Parser(chainArray[i])" with:
    new Callable() {
      public void call() {
        MainOperation();
    });For instance when one wants to use SMAP.class, he would initialize MainOperation as:
    public abstract String MainOperation(){
        return new SMAP(chainArray));
    That's the most reasonable explanation I can give, but apparently an abstract method cannot be called anywhere else in the abstract class (ProgressGUI.class in my case).
    Firstly it should be Callable not Runnable.Can you explain why? You are just running a method and ignoring any result or exception. However, it makes little difference.ExecutorCompletionService takes Future objects as input, that's why it should be Callable and not Runnable. The returned value is a score (String).
    Secondly how can I change that runMyNewMethod() on demand, can I do it by defining it as abstract?How do you want to determine which method to run?The user will click on the appropriate button and the GUI will initialize (perhaps implicitly) the body of the abstract method MainOperation accordingly. Don't worry about that, this is not the point.
    Edited by: tevang2 on Dec 28, 2008 7:18 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Custom DBTransaction Implementation in different modules

    Hi,
    I am trying to implement custom DBTransactionImpl class by followig the below link -
    http://www.oracle.com/technology/products/jdev/tips/muench/dbtransimpl/index.html
    I achieved the required functionality while working with single Application module.
    But now my issue is -
    I have two modules, two jsp's in both i have commit functionalities. I want to have different implementation for these commits.
    so i created two dbtransactionimpl classes and two transaction factory classes, also mapped configurations to respective impl classes in bc4j.xcfg file.
    following is my configuration ::
    <?xml version = '1.0' encoding = 'UTF-8'?>
    <BC4JConfig version="11.1" xmlns="http://xmlns.oracle.com/bc4j/configuration">
    <AppModuleConfigBag ApplicationName="com.softsol.forms2adf.model.modules.AppModule">
    <AppModuleConfig name="AppModuleLocal" ApplicationName="com.softsol.forms2adf.model.modules.AppModule" DeployPlatform="LOCAL" JDBCName="ORCADB" jbo.project="model.Model" java.naming.factory.initial="oracle.jbo.common.JboInitialContextFactory">
    <Security AppModuleJndiName="com.softsol.forms2adf.model.modules.AppModule"/>
    </AppModuleConfig>
    <AppModuleConfig name="AppModuleShared" ApplicationName="com.softsol.forms2adf.model.modules.AppModule" DeployPlatform="LOCAL" JDBCName="ORCADB" jbo.project="model.Model" java.naming.factory.initial="oracle.jbo.common.JboInitialContextFactory">
    <AM-Pooling jbo.ampool.isuseexclusive="false" jbo.ampool.maxpoolsize="1"/>
    <Security AppModuleJndiName="com.softsol.forms2adf.model.modules.AppModule"/>
    </AppModuleConfig>
    <AppModuleConfig DeployPlatform="LOCAL" JDBCName="ORCADB" jbo.project="model.Model" name="deptModuleLocal" TransactionFactory="com.softsol.forms2adf.model.modules.deptModuleDatabaseTransactionFactory" ApplicationName="com.softsol.forms2adf.model.modules.deptModule">
    <Security AppModuleJndiName="com.softsol.forms2adf.model.modules.deptModule"/>
    </AppModuleConfig>
    <AppModuleConfig name="deptModuleShared" ApplicationName="com.softsol.forms2adf.model.modules.deptModule" DeployPlatform="LOCAL" JDBCName="ORCADB" jbo.project="model.Model" java.naming.factory.initial="oracle.jbo.common.JboInitialContextFactory">
    <AM-Pooling jbo.ampool.isuseexclusive="false" jbo.ampool.maxpoolsize="1"/>
    <Security AppModuleJndiName="com.softsol.forms2adf.model.modules.deptModule"/>
    </AppModuleConfig>
    <AppModuleConfig DeployPlatform="LOCAL" JDBCName="ORCADB" jbo.project="model.Model" name="empModuleLocal" TransactionFactory="com.softsol.forms2adf.model.modules.empModuleDatabaseTransactionFactory" ApplicationName="com.softsol.forms2adf.model.modules.empModule">
    <Security AppModuleJndiName="com.softsol.forms2adf.model.modules.empModule"/>
    </AppModuleConfig>
    <AppModuleConfig name="empModuleShared" ApplicationName="com.softsol.forms2adf.model.modules.empModule" DeployPlatform="LOCAL" JDBCName="ORCADB" jbo.project="model.Model" java.naming.factory.initial="oracle.jbo.common.JboInitialContextFactory">
    <AM-Pooling jbo.ampool.isuseexclusive="false" jbo.ampool.maxpoolsize="1"/>
    <Security AppModuleJndiName="com.softsol.forms2adf.model.modules.empModule"/>
    </AppModuleConfig>
    </AppModuleConfigBag>
    </BC4JConfig>
    But when i am trying to commit, in both pages its using the same transactionimpl class.
    Hope someone helps..
    Thanks
    srikanth

    Thanks to Didier Laurent. I got the solution.
    ref Link : http://blogs.oracle.com/Didier/bc4j/

  • Instance of one of implementations of abstract class depending on context??

    Hi all,
    I just wonder if it is possible in Java to call creation of a new instance of an implementation of an abstract class depending on context.
    I mean something like:
    abstract class Abstract
    //1st implementation of Abstract class
    class Concrete1 extends Abstract
    //2nd implementation of Abstract class
    class Concrete2 extends Abstract
    }And now, somewhere else in the code, I would really need to call something like this:
    Abstract test1 = new ...(); //here I need sometimes to be created instance of Concrete1, sometimes instance of Concrete2
    Is there a way how to do this??

    Some more concrete code if it helps:
    Abstract class:
    * Individual.java
    * Created on 21. leden 2007, 1:08
    package genetics;
    * Abstract class defining fields and methods of one individual for genetic algorithms
    * This class is supposed to be implemented according to problem to be solved
    * @author Richard V�tek
    * @version 1.0
    abstract public class Individual implements Comparable<Individual>
       * Create random chromosomes for this individual
      protected abstract void createRandomChromosomes();
       * Count fitness of this individual
       * This number says how good is this individual (the higher number the better).
       * Better fitness means that this individual is closer to solution.
       * @return  int   Fitness of this individual
      protected abstract int getFitness();
       * Cross-breed this individual with another individual
       * This leaves untouched number of chromosomes to certain (randomly generated) position.
       * From this position on, it will swap chromosomes between this and another individual.
       * So this individual gets changed (cross-breeded) as well as the other, which is returned
       * as result of this method.
       * @param   other              The other individual to cross-breed with
       * @return  Individual         Hybrid of this and another individual (in fact, the other individual
       *                             after cross-breed (this (source) individual gets changed too after cross-breed)
      protected abstract Individual crossbreed(Individual other);
       * Mutate this individual
       * Mutate chromosomes of this individual; every chromosome is mutated
       * with probability set in settings of evolution.
       * This probability is supposed to be quite low number, roughly 1 %.
      protected abstract void mutate();
       * Check this individual
       * Check if this individual still suits the assignment.
       * If not, repair this individual to suit it again.
      protected abstract void check();
       * Implementation of Comparable: comparing of individuals by fitness
       * @param other Another individual to compare
      public int compareTo(Individual other)
        return this.getFitness() - other.getFitness();
    One implementation class:
    * KnapsackIndividual.java
    * Created on 21. leden 2007, 1:41
    package genetics;
    import java.util.Random;
    import java.util.TreeMap;
    import knapsack.KnapsackProblem;
    * This is practically the same as KnapsackProblem class but designed specially
    * for solving knapsack problem with genetic algorithm so all unnecessary fields
    * and methods are removed.
    * @author Richard V�tek
    * @version 1.0
    public class KnapsackIndividual extends Individual
       * Chromosomes of this individual
       * In case of knapsack problem, they are things currentl in knasack
      protected boolean[] arrChromosomes;
       * Cached value of fitness of this individual
       * Used to not to count fitness of this individual everytime when needed
       * (and it is often needed); once counted, it will be read from this cached value
      private int intFitnessCache = Integer.MIN_VALUE;
       * Randomizer for random-driven methods (like mutation, etc.)
      private Random randomizer = new Random();
       * Reference to evolution to read mutation probability from
      protected Evolution evolution;
       * Assignment of problem instance
      protected KnapsackProblem assignment;
       * Create a new Individual instance
       * @param   assignment  Object representing assignment of particular problem
       * @param   evolution   Reference to evolution object to be able to read evolution's settings from
      public KnapsackIndividual(KnapsackProblem assignment, Evolution evolution)
        this.assignment = assignment;
        this.evolution = evolution;
        this.arrChromosomes = new boolean[assignment.getNumberOfThings()];
       * Create random chromosomes for this individual
       * @see Individual#createRandomChromosomes()
      protected void createRandomChromosomes()
        int intChromosomeCount = this.arrChromosomes.length;
        for (int i = 0; i < intChromosomeCount; i++)
          this.arrChromosomes[i] = this.randomizer.nextBoolean();
       * Get fitness of this individual
       * In case of knapsack, fitness is sum of prices of all things currently in knapsack
       * @see Individual#getFitness()
      protected int getFitness()
        //if cached value exist, return it
        if (this.intFitnessCache != Integer.MIN_VALUE)
          return this.intFitnessCache;
        //otherwise, count fitness of this individual
        int intChromosomeCount = this.arrChromosomes.length;
        int intSumOfValues = 0;
        //in case of knapsack, fitness is value of all things currently in knapsack
        //(sum of values of all things in knapsack)
        for (int i = 0; i < intChromosomeCount; i++)
          intSumOfValues = this.assignment.arrPrices;
    //save counted fitness to cache
    this.intFitnessCache = intSumOfValues;
    return intSumOfValues;
    * Cross-breed two individuals
    * @param other The other individual for cross-breed
    * @return The other individual after cross-breed (but this individual is affected too)
    * @see Individual#crossbreed()
    protected Individual crossbreed(Individual other)
    int intChromosomeCount = this.arrChromosomes.length;
    //position from which on swap chromosomes of this and the other individual
    int intCrossbreedPosition = this.randomizer.nextInt(intChromosomeCount);
    boolean booTemp;
    //swap chromosomes from cross-breed position on
    for (int i = intCrossbreedPosition; i < intChromosomeCount; i++)
    booTemp = ((KnapsackIndividual) this).arrChromosomes[i];
    ((KnapsackIndividual) this).arrChromosomes[i] = ((KnapsackIndividual) other).arrChromosomes[i];
    ((KnapsackIndividual) other).arrChromosomes[i] = booTemp;
    return other;
    * Mutate individual chromosomes of this individual with certain probability
    * In case of knapsack, particular thing is just inserted/taken out of the knapsack
    * @see Individual#mutate()
    protected void mutate()
    //probability of mutation (in percents)
    int intMutationProbability = this.evolution.getMutationProbability();
    int intChromosomeCount = this.arrChromosomes.length;
    //iterate through all chromosomes, mutating them with certain (set) probability
    for (int i = 0; i < intChromosomeCount; i++)
    //mutation probability passed => mutate this chromosome
    if (this.randomizer.nextInt(100) < intMutationProbability)
    this.arrChromosomes[i] = !this.arrChromosomes[i];
    //when mutation finished, we must check if this individual still suits the assignment;
    //if not, repait it
    this.check();
    * Check if this individual still suits the assignment; if not, repair it
    * In case of knapsack it means that sum of weights of things currently in knapsack
    * will not exceed capacity of backpack; if exceeds, take out as many things as necessary
    * to not to exceed again; choose things to be taken out according to worst weight to price ratio
    * @see Individual#check()
    protected void check()
    int intSumOfWeights = 0;
    //list of things in the knapsack sorted by weight to price ratio
    //key: index of thing in knapsack
    //value: weight/price ratio
    TreeMap<Integer, Float> things = new TreeMap<Integer, Float>();
    for (int i = 0; i < this.arrChromosomes.length; i++)
    //thing in the knapsack
    if (this.arrChromosomes[i] == true)
    //add its weight to sum of weights
    intSumOfWeights += this.assignment.arrWeights[i];
    //add it to the list of things sorted by weight to price ratio
    things.put(i, (((float) this.assignment.arrWeights[i]) / ((float) this.assignment.arrPrices[i])));
    //sum of weights exceeds knapsack capacity => take out as many things as necessary
    while (intSumOfWeights > this.assignment.getKnapsackCapacity())
    //take out thing with worst weight/price ratio from all things currently in knapsack
    this.arrChromosomes[things.lastKey()] = false;
    //update sum of weights of things currently in knapsack
    intSumOfWeights -= things.get(things.lastKey());
    //also remove this thing from list of things
    things.remove(things.lastKey());
    And another class, where i need this feature (tried to use generics for that, but they can't be used in this way):
    * Evolution.java
    * Created on 21. leden 2007, 2:47
    package genetics;
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.Arrays;
    * Class for algorithms using simulated evolution to deal with a problem
    * Tried to be designed general enough to allow to be used for every genetic algotihm.
    * If true, only class Individual must be implemented according to problem to be solved,
    * the rest of genetic algorithm stays the same.
    * @author Richard V�tek
    * @version
    public class Evolution<Problem, IndividualClass extends Individual>
       * Number of generations of evolution to finish
      protected int intGenerationCount;
       * Number of individuals in each generation
      protected int intGenerationSize;
       * Elite individual count
       * All elite individuals are just copied from one generation to another with no change
      protected int intGenerationEliteCount;
       * Number of individuals participating a tournament
       * To select an good individual for next generation, tournaments are hold.
       * This affects number of individuals which one good individual is selected
       * from in one tournament.
       * @see <a href="http://cs.felk.cvut.cz/%7Exobitko/ga/example_f.html">Genetic Algorithm Example Applet</a>
      protected int intGenerationTournamentSize;
       * Probability of mutation (in percents)
      protected int intMutationProbability;
       * Current generation of individuals in evolution
      protected Generation<IndividualClass> thisGeneration;
       * Next generation of individuals in evolution
      protected Generation<IndividualClass> nextGeneration;
       * Fitness of best individual in this generation
      private int intIndividualBestFitness;
       * Sum of fitnesses of all individuals in this generation
      private int intIndividualsSumFitness;
       * Fitness of worst individual in this generation
      private int intIndividualWorstFitness;
       * Fitness of best elite individual in (every) generation
       * Auxilliary variable to not to count statistics for elite individuals
       * in each generation as well (not needed - elite individuals don't change themselves)
      private int intIndividualEliteBestFitness;
       * Sum of fitnesses of all elite individuals in (every) generation
       * Auxilliary variable to not to count statistics for elite individuals
       * in each generation as well (not needed - elite individuals don't change themselves)
      private int intIndividualElitesSumFitness;
       * Fitness of worst elite individual in (every) generation
       * Auxilliary variable to not to count statistics for elite individuals
       * in each generation as well (not needed - elite individuals don't change themselves)
      private int intIndividualEliteWorstFitness;
       * Create a new instance of Evolution (settings passed through parameters)
       * @param   intGenerationCount            Number of generation of evolution to finish
       * @param   intGenerationSize             Number of individuals in each generation
       * @param   intGenerationEliteRatio       Elite individuals to generation size ratio (in percents)
       * @param   intGenerationTournamentRatio  Members of tournament to generation size ratio (in percents)
       * @param   intMutationProbability        Probability of mutation of each chromosome of each individual of generation (in percents)
       * @see     #intGenerationEliteCount
       * @see     #intGenerationTournamentSize
      public Evolution(
        int intGenerationCount, int intGenerationSize,
        int intGenerationEliteRatio, int intGenerationTournamentRatio,
        int intMutationProbability)
        this.intGenerationCount = intGenerationCount;
        this.intGenerationSize = intGenerationSize;
        this.intGenerationEliteCount = (int) (intGenerationSize * (intGenerationEliteRatio / 100.0));
        this.intGenerationTournamentSize = (int) (intGenerationSize * (intGenerationTournamentRatio / 100.0));
        this.intMutationProbability = intMutationProbability;
       * Create a new instance of Evolution (settings loaded from settings file)
       * @param   strSettingFile  Name of file containing settings for evolution
       * @throws  IOException     File does not exist, cannot be read, etc.
       * @throws  Exception       Another exception occured during loading of file
      public Evolution(String strSettingFile)
        BufferedReader settings;
        String settingsLine;
        int intLineCounter = 0;
        int intSetting;
        try
          settings = new BufferedReader(new FileReader(strSettingFile));
          while ((settingsLine = settings.readLine()) != null)
            intLineCounter++;
            settingsLine = settingsLine.substring(0, settingsLine.indexOf("\t"));
            intSetting = Integer.parseInt(settingsLine);
            switch (intLineCounter)
              case 1:
                this.intGenerationCount = intSetting;
                break;
              case 2:
                this.intGenerationSize = intSetting;
                break;
              case 3:
                this.intGenerationEliteCount = (int) (this.intGenerationSize * (intSetting / 100.0));
                break;
              case 4:
                this.intGenerationTournamentSize = (int) (this.intGenerationSize * (intSetting / 100.0));
                break;
              case 5:
                this.intMutationProbability = intSetting;
                break;
            } //switch
          } //while
          //after reading has been completed, let's close the stream
          settings.close();
        } //try
        //IO exception - file not found, cannot be read, etc.
        catch (IOException ioe)
          System.out.println("Vyskytl se I/O probl�m p&#345;i na&#269;�t�n� zad�n� ze souboru " + strSettingFile);
        //Exception - another problem during reading of file
        catch (Exception e)
          System.out.printf("Vyskytl se n&#283;jak� divn� probl�m p&#345;i na&#269;�t�n� zad�n� ze souboru %s. V�pis vyj�mky:\n", strSettingFile);
          e.printStackTrace();
       * Vivify first generation for evolution
       * Necessary number of individuals is created with random chromosomes.
       * Their chromosomes must then be checked if they suit the assignment
       * and if not so, repaired.
      private Generation<IndividualClass> vivifyFirstGeneration()
        //create a brand-new generation
        Generation generation = new Generation<IndividualClass>(this);
        int intTemp;
        //for all individual of this generation
        for (int i = 0; i < this.intGenerationSize; i++)
    //create an individual with no chromosomes
    generation.arrIndividuals[i] = new IndividualClass(this, Problem);
          //create a set of random chromosomes
          neration.arrIndividuals.createRandomChromosomes();
    //if these chromosomes does not suit assignment, repair them
    generation.arrIndividuals[i].check();
    //sort Individuals by fitness so elite individuals get to first positions of array
    Arrays.sort(generation.arrIndividuals);
    //now count statistics for elite individuals (it is enough to count them once,
    //elite don't get changed so their statistics don't get changed either)
    this.intIndividualEliteBestFitness = Integer.MIN_VALUE;
    this.intIndividualElitesSumFitness = 0;
    this.intIndividualEliteWorstFitness = Integer.MAX_VALUE;
    //count statistics for elite individuals
    for (int i = 0; i < this.intGenerationEliteCount; i++)
    intTemp = generation.arrIndividuals[i].getFitness();
    //better fitness than best fitness so far
    if (intTemp > this.intIndividualEliteBestFitness)
    this.intIndividualEliteBestFitness = intTemp;
    //worse fitness than worst fitness so far
    else if (intTemp < this.intIndividualEliteWorstFitness)
    this.intIndividualEliteWorstFitness = intTemp;
    this.intIndividualElitesSumFitness += intTemp;
    //reset generation's statistics
    this.intIndividualBestFitness = this.intIndividualEliteBestFitness;
    this.intIndividualsSumFitness = this.intIndividualElitesSumFitness;
    this.intIndividualWorstFitness = this.intIndividualEliteWorstFitness;
    //count generation's statistics also from rest of individuals
    for (int i = this.intGenerationEliteCount; i < this.intGenerationSize; i++)
    updateGenerationStatistics(generation.arrIndividuals[i].getFitness());
    return generation;
    * Get next generation in evolution
    * Core method for all evolution; Through this method, new generation is obtained.
    * Every next generation should contain better individuals than the previous one
    * (till certain point) so with growing number of iterations in evolution, we
    * get better results (till certain point).
    * Everytime all elite individuals are copied to next generation, then hold needed number of
    * tournaments to choose a pair of good-looking individuals, cross-breed individuals in these
    * pairs, mutate them (and repair if necessary) and finally add to next generation.
    * @return Generation Next generation in evolution
    * @see Generation#tournament()
    * @see Generation#crossbreed()
    * @see Generation#mutate()
    private Generation getNextGeneration()
    Generation nextGeneration = new Generation(this);
    //number of pairs of individuals to select for next generation
    int intIndividualPairsToSelect = (this.intGenerationSize - this.intGenerationEliteCount) / 2;
    int intTemp;
    //reset generation's statistics
    this.intIndividualBestFitness = this.intIndividualEliteBestFitness;
    this.intIndividualsSumFitness = this.intIndividualElitesSumFitness;
    this.intIndividualWorstFitness = this.intIndividualEliteWorstFitness;
    //just copy all elite individuals from this generation to another
    //(they are on first positions of array of individuals)
    for (int i = 0; i < this.intGenerationEliteCount; i++)
    nextGeneration.arrIndividuals[i] = this.thisGeneration.arrIndividuals[i];
    //hold as many tournaments as necessary to select remaining number of pairs
    //of good-looking individuals for next generation (apart from the elite ones)
    for (int i = 0; i < intIndividualPairsToSelect; i++)
    this.thisGeneration.tournament();
    this.thisGeneration.crossbreed();
    this.thisGeneration.mutate();
    //add this individual in next generation
    nextGeneration.arrIndividuals[2 * i] = this.thisGeneration.nextGenerationIndividual01;
    //update statistics of generation
    updateGenerationStatistics(this.thisGeneration.nextGenerationIndividual01.getFitness());
    //add this individual in next generation
    nextGeneration.arrIndividuals[2 * i + 1] = this.thisGeneration.nextGenerationIndividual02;
    //update statistics of generation
    updateGenerationStatistics(this.thisGeneration.nextGenerationIndividual02.getFitness());
    //next generation is complete => return it
    return nextGeneration;
    * Update statistics of current generations
    * @param intFitness Fitness that may possibly update generation's statistics
    * (best fitness, worst fitness, sum of fitnesses)
    private void updateGenerationStatistics(int intFitness)
    //better fitness than best fitness so far
    if (intFitness > this.intIndividualBestFitness)
    this.intIndividualBestFitness = intFitness;
    //worse fitness than worst fitness so far
    else if (intFitness < this.intIndividualWorstFitness)
    this.intIndividualWorstFitness = intFitness;
    //update sum of fitnesses as well (for average fitness)
    this.intIndividualsSumFitness += intFitness;
    * Execute evolution process
    * Vivify first generation and then as many next generations as set in settings of evolution
    public void evolution()
    this.thisGeneration = vivifyFirstGeneration();
    //output generation's statistics
    System.out.printf("Generace 0:\t%d\t%d\t%d", this.getIndividualBestFitness(), this.getIndividualAverageFitness(), this.getIndividualWorstFitness());
    for (int i = 0; i < this.intGenerationCount; i++)
    this.nextGeneration = getNextGeneration();
    this.thisGeneration = this.nextGeneration;
    //output generation's statistics
    System.out.printf("Generace %d:\t%d\t%d\t%d", i, this.getIndividualBestFitness(), this.getIndividualAverageFitness(), this.getIndividualWorstFitness());
    * Get best fitness of all individuals in this generation
    public int getIndividualBestFitness()
    return intIndividualBestFitness;
    * Get average fitness of all individuals in this generation
    public float getIndividualAverageFitness()
    return (this.intIndividualsSumFitness / (float) this.intGenerationSize);
    * Get worst fitness of all individuals in this generation
    public int getIndividualWorstFitness()
    return intIndividualWorstFitness;
    * Get probability of mutation
    * @return Probability of mutation of each chromosome of every individual in generation (in percents)
    public int getMutationProbability()
    return intMutationProbability;

  • Sorting a list of different class objects

    Hi All ,
    How to sort a List a.which contains objects of different Classes, b. objects of same class . Is it possible to sort these by implementing Comparable interface .
    Thanks ,
    Rajesh Reddy

    rajeshreddyk wrote:
    Hi All ,
    How to sort a List a.which contains objects of different Classes, b. objects of same class . Is it possible to sort these by implementing Comparable interface .Well, if objects of different classes are kept in the same List and you want to sort them together they at least have that in common. They're Comparable-able. -:) To manifest that the different classes could all implement a Comparableable interface (or maybe Intercomparable would be a better choise of name.)

  • Calling a method from a different class?

    Ok..
    I been trying for hours... but im stumped.
    How can I get this to work?
    (Note: I cut this code down from over 600+ lines of code.. I left in a REALLY raw framework that shows where the basic problem is.)
    public class Client extends JPanel implements Runnable {
    // variable declarations...
        Socket connection;
        BufferedReader fromServer;
        PrintWriter toServer;
        public Client(){
    // GUI creation...
    // Create the login JFrame
        Login login = new Login()
        public void connect(){
        try {
                //Attempt to connect to the server
                connection = new Socket(ip,port);
                fromServer = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                toServer = new PrintWriter(connection.getOutputStream());
                //Launch a thread here to read incoming messages from the server
                //so I dont block on reading
                new Thread (this).start();
        } catch (Exception e) {
            e.printStackTrace();
        public void run(){
            // This keeps reading lines from the server
            String s;
            try {
                //Read messages sent from the server - add them to chat window
                while ((s=fromServer.readLine()) != null) {
                txtChat.append(s);
            } catch (Exception e) {}
        public static void main(String args[]){
            // some init frame stuff
            frame = new JFrame();
            frame.getContentPane().add(new Client(),BorderLayout.CENTER);
         frame.setVisible(true);
    class Login extends JFrame {
        JPanel pane;
        public Login() {
         super("Login");
         pane = new JPanel();
         JButton cmdConnect = new JButton("Connect");
            pane.add(cmdConnect);
         setContentPane(pane);
         setSize(300,300);
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         cmdConnect.addActionListener(new ActionListener(){
             public void actionPerformed(ActionEvent ae){
              // I want to connect to the server when this button is pressed.
              // How can I call the connect method in the Client class?
    }

    Your posted code shows Login as an inner class. So one way to solve your problem is.
    1. Make an instance variable to hold the instance. For example, after "PrintWriter toServer;" add "private Client client;"
    2. In the Client constructor, add a line "client = this;"
    3. In the Login actionPerformed(), use "client.connect();"
    Another way is to have Login keep a reference to the Client that created it.
    1. Add an instance variable to Login "private Client client;"
    2. Change the Login constructor "public Login(Client c) {"
    3. Add a line in the constructor "client = c;"
    4. In the actionPerformed() "client.connect();"

Maybe you are looking for