Results 1 to 14 of 14
Like Tree2Likes
  • 1 Post By Junky
  • 1 Post By DarrylBurke

Thread: error opening GUI

  1. #1
    samanyu is offline Member
    Join Date
    Jun 2011
    Location
    Tsukuba, Japan
    Posts
    63
    Rep Power
    0

    Default error opening GUI

    Hi all,
    I am using the following code to call the class which should open my GUI, but it simply opens a blank frame and does not show the display area.
    Java Code:
    b2.addActionListener(new ActionListener(){
                public void actionPerformed( ActionEvent ev ){  // process the control events
        if( ev.getSource() == b2 ){  // handle  GUI open
            Iteration1.main();
    The GUI works perfectly when I directly use java Iteration1 on c-prompt.
    Any ideas?

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,001
    Blog Entries
    7
    Rep Power
    20

    Default

    Run the call to your main() method in another Thread because that's what happens when you start your program through Iteration.main( ... ); here you're trying to run that method on the EDT (Event Dispatch Thread).

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  3. #3
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    There's nothing in the code posted that explains the problem, and so likely it lies elsewhere [edit: except for the valid point that Jos makes]. Question though: why start Iteration through its static main method? Why not create an Iteration1 object and start it up that way? It would give you a reference to the object and give your code more flexibility.

  4. #4
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,189
    Rep Power
    19

    Default

    And in an anonymous listener added to b2, the test for the event's source is redundant and should be removed.

    db

  5. #5
    samanyu is offline Member
    Join Date
    Jun 2011
    Location
    Tsukuba, Japan
    Posts
    63
    Rep Power
    0

    Default

    Thanks DB, JosAH and Fubarable.

    I do believe the problem lies elsewhere, because I used a similar statement to call a class which worked the difference is:

    Class which worked:

    Java Code:
    public class Neigh1 { ...code
    }
    class DisplayArea{ 
    paintComponent();
    }
    class Neigh2 { ....code
    }
    GUI that didn't work:
    Java Code:
    public class Iteration1 {
    code...
    public class DisplayArea{
    paintComponent()
    }
    }
    public class Iteration1{
    code...
    }
    Does that make sense? To point it out in words, the GUI that works has the entire program in one file, called Neigh1, the classes DisplayArea (which handles painting functions) and Neigh2 are not public and defined outside the Neigh1 class. In the GUI that doesn't work, there are two files, called Iteration1 and Iteration2. The class DisplayArea is public and defined INSIDE the Iteration1 class.
    If that doesn't make sense I can post the entire code highlighting what I mean.
    Thanks.

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    No, it doesn't make sense and shouldn't matter as your program should work if different classes are in their own files.

  7. #7
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,755
    Rep Power
    7

    Default

    [soapbox]
    I smell a design flaw if class names are numbered.
    [/soapbox]
    Fubarable likes this.

  8. #8
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,189
    Rep Power
    19

    Default

    A paintComponent overload that doesn't take any arguments is certainly suspicious...
    Lesson: Performing Custom Painting (The Java™ Tutorials > Creating a GUI With JFC/Swing)

    db

  9. #9
    samanyu is offline Member
    Join Date
    Jun 2011
    Location
    Tsukuba, Japan
    Posts
    63
    Rep Power
    0

    Default

    Ok. Just tell me this. Suppose my program is running when i run it via command prompt directly. But not when I use the new ConstructorName(); statement in another program, what should I do?

  10. #10
    samanyu is offline Member
    Join Date
    Jun 2011
    Location
    Tsukuba, Japan
    Posts
    63
    Rep Power
    0

    Default

    Still not solved, now that infinite loop is not working. What could be the probable cause for a program that works perfectly when called individually through the main function on c prompt, doesn't work when called from another function?

  11. #11
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,450
    Rep Power
    18

    Default

    The difference is in the first case you are calling/creating a new GUI from an existing one.
    In the second case it is creating it from scratch.

    What is in the main() method you are calling?

  12. #12
    samanyu is offline Member
    Join Date
    Jun 2011
    Location
    Tsukuba, Japan
    Posts
    63
    Rep Power
    0

    Default

    Thanks for replying. I have copied the code that is executing correctly. If I use new Iteration1 to call this class from some other class, it doesn't work. What should I do? I know the code below is long and really messy, but I've tried highlighting the problems. Could you take a look?
    Java Code:
    import javax.swing.*;    // the Java eXtensions "Swing" graphics kit
    import java.awt.*;       // the Java  Abstract Windowing Toolkit
    import java.awt.image.*; // the AWT image  package
    import java.awt.geom.*;  // AWT geometry
    import java.awt.event.*; // AWT Event Management  package
    import java.io.*;        // I/O package
    
    // Iterated brahma  with some simplified  con5trols and cell editing capabilities
    public class Iteration1 extends JFrame implements ActionListener {
    
        public static final int DISP_WIDTH  = 768;  // constants
        public static final int DISP_HEIGHT = 768;
        private static final int MNU_HEIGHT    = 22;
        public static int CELL_PXL    = 16;
        private static final int FPS = 1;
    
    
    
        public Container con = null;
        public DisplayArea da = null;
        public Iteration2 exchanges = null;
    
        public boolean running = false;
        
    
        [B]public static void main (String args[]) throws IOException
        {
            Iteration1 iter1 = new Iteration1();
            iter1.loops();
        }[/B]
        
        [B]public void loops()
       {
           long delayTime = 1000/FPS;     // main loop
        long startTime, waitTime, elapsedTime;
        while( true ){
            if( running ){
            startTime = System.currentTimeMillis();
            exchanges.update();
            elapsedTime = System.currentTimeMillis() - startTime;
            waitTime = Math.max( delayTime - elapsedTime, 5 );
            try{
    	Thread.sleep(waitTime);
    	}catch (InterruptedException ie) {}
           da.repaint();
           }
         }
        }[/B]
    
    
    
    
    
        public Iteration1(){  // con5structor set up thread loops
        super("Brahma-II");
        JFrame frame = new JFrame("Brahma-II");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(true);
        con = getContentPane();
        con.setLayout(null);  
    
        setupMenus();
        exchanges = new Iteration2( DISP_WIDTH/CELL_PXL, DISP_HEIGHT/CELL_PXL );
    
        da = new DisplayArea( new Rectangle( 0, 0, DISP_WIDTH, DISP_HEIGHT ) );
        con.add( da );
        con.addMouseListener( da );
        
        setVisible(true);
        resizeToInternalSize5( DISP_WIDTH, DISP_HEIGHT + MNU_HEIGHT);
       }
       
        public void resizeToInternalSize5( int internalWidth, int internalHeight ){
        Insets insets = getInsets();
        final int newWidth  = internalWidth  + insets.left + insets.right;
        final int newHeight = internalHeight + insets.top  + insets.bottom;
        Runnable resize = new Runnable(){ // an anonymous inner class
            public void run(){
                setSize( newWidth, newHeight);
            }
        };
        if(!SwingUtilities.isEventDispatchThread() ){
            try{
            SwingUtilities.invokeAndWait( resize );
            }catch( Exception e ) { }
        }
        else{
            resize.run();
        }
        validate(); 
        }
    
    
        public JMenuBar menuBar;
    
        public JMenu fileMenu;
        public JMenuItem resizeItem;
        public JMenuItem saveItem;
        public JMenuItem openItem;
        public JMenuItem clearItem;
        public JMenuItem exitItem;
    
        public JMenu gridMenu;
        public JMenuItem openRulItem;
        public JMenuItem randGen;
        
        public JButton startButton;
        public JButton stopButton;
        public JButton stepButton;
    
        public void setupMenus(){
    
        menuBar = new JMenuBar();
        this.setJMenuBar(menuBar );
    
        fileMenu = new JMenu("File");
        menuBar.add( fileMenu );
        
        resizeItem = new JMenuItem("Resize");
        resizeItem.addActionListener( this );
        fileMenu.add(resizeItem);
    
        saveItem = new JMenuItem("Save Grid");
        saveItem.addActionListener( this );
        fileMenu.add(saveItem);
    
        openItem = new JMenuItem("Open Grid");
        openItem.addActionListener( this );
        fileMenu.add(openItem);
    
        clearItem = new JMenuItem("Clear Grid");
        clearItem.addActionListener( this );
        fileMenu.add(clearItem);
    
        fileMenu.add( new JSeparator() );
    
        exitItem = new JMenuItem("Exit");
        exitItem.addActionListener( this );
        fileMenu.add(exitItem);
    
    
        gridMenu = new JMenu("Grid");
        menuBar.add( gridMenu );    
        
        openRulItem = new JMenuItem("Load Rules");
        openRulItem.addActionListener( this );
        gridMenu.add(openRulItem);
         randGen = new JMenuItem("Random Grid");
        randGen.addActionListener(this);
        gridMenu.add(randGen);
    
        gridMenu.add( new JSeparator() );
    
       startButton = new JButton("Start");
        startButton.addActionListener( this );
        menuBar.add(startButton);
       
        stopButton = new JButton("Stop");
        stopButton.addActionListener( this );
        menuBar.add(stopButton);
    
        stepButton = new JButton("1-Step");
        stepButton.addActionListener( this );
        menuBar.add(stepButton);
    
        menuBar.validate();
    
        }
            
        public void actionPerformed( ActionEvent ev ){
    
            if( ev.getSource() == exitItem ){  // handle  EXIT
            System.exit(1);
        }
        else if( ev.getSource() == saveItem ){  // handle  saving  to  file
            JFileChooser chooser = new JFileChooser( new File( System.getProperty("user.dir", "." ) ) );
            int returnVal = chooser.showSaveDialog(this);
            if(returnVal == JFileChooser.APPROVE_OPTION) {
                File myFile = chooser.getSelectedFile();
            try{
                FileOutputStream fin = new FileOutputStream( myFile );
                ObjectOutputStream oin = new ObjectOutputStream( fin );
                oin.writeObject(exchanges.cells);
                oin.writeObject(exchanges.buffer);
                fin.close();
            }catch( Exception e ){
                System.out.println("Error Saving file: " +  myFile.getName() );
                e.printStackTrace();
            }
            }
        }
        else if( ev.getSource() == openItem ){  // handle  reloading from file
            JFileChooser chooser = new JFileChooser( new File( System.getProperty("user.dir", "." ) ) );
            //      JFileChooser chooser = new JFileChooser();
            int returnVal = chooser.showOpenDialog(this);
            if(returnVal == JFileChooser.APPROVE_OPTION) {
            File inputFile = chooser.getSelectedFile();
            try{
                FileInputStream fot = new FileInputStream( inputFile );
                ObjectInputStream oot = new ObjectInputStream( fot );
                exchanges.cells = (int[][])oot.readObject();
                exchanges.buffer = (int[][])oot.readObject();
                fot.close();
            }catch( Exception e ){
                System.out.println("Error Opening file: " +  inputFile.getName() );
                e.printStackTrace();
            }
            } da.repaint();
        }
        else   if( ev.getSource() == openRulItem ){  // handle  reloading from file
            JFileChooser chooser = new JFileChooser( new File( System.getProperty("user.dir", "." ) ) );
            //      JFileChooser chooser = new JFileChooser();
            int returnVal = chooser.showOpenDialog(this);
            if(returnVal == JFileChooser.APPROVE_OPTION) {
            File inputFile = chooser.getSelectedFile();
            try{
                FileInputStream fis = new FileInputStream( inputFile );
                ObjectInputStream ois = new ObjectInputStream( fis );
                exchanges.set=(int[][])ois.readObject();
                exchanges.rules = (int[][][])ois.readObject();
                exchanges.child = (int[][][])ois.readObject();
                fis.close();
            }catch( Exception e ){
                System.out.println("Error Opening file: " +  inputFile.getName() );
                e.printStackTrace();
            }
            } 
        }
        else if ( ev.getSource() == randGen)
        {
            exchanges.randomFn();
            da.repaint();
        }
        else if ( ev.getSource() == clearItem)
        {
            exchanges.blank(0);
            da.repaint();
        }// process the con5trol events
        else if( ev.getSource() == startButton ){  // start  running
          running = true;
        }
        else if( ev.getSource() == stopButton ){  // stop background thread
            running = false;
        }
        else if( ev.getSource() == stepButton ){  // do exactly ONE step
            exchanges.update(); 
            da.repaint();
        }
        }
            
    
        
    
    
    
        public class DisplayArea extends JPanel implements MouseListener{
            
        public DisplayArea( Rectangle bounds ){  // default constructor
            setLayout(null);
            setBounds( bounds);
            setOpaque(false);
            setPreferredSize( new Dimension (bounds.width, bounds.height )  );
            
        }
    
        public void paintComponent( Graphics g ){  // main rendering  recipe
            Graphics2D g2 = (Graphics2D)g;        
            g2.setColor( Color.black );
            g2.fillRect( 0, 0, getWidth()-1, getHeight()-1 );        
            int w = DISP_WIDTH / exchanges.width;
            int h = DISP_HEIGHT /exchanges.height;
             for(int col=0;col<exchanges.width;col++){
                for(int row=0;row<exchanges.height;row++){
                    for(int k=0; k<11; k++){  //replaced with works1.l                    
                if( exchanges.buffer[col][row] == k ){
                     g2.setColor( exchanges.colarray[k] ); // is and was a cooperator
                }            
                }           
                g2.fillRect( col * w +1, row * h +1, w-2, h-2 );
            }
            }
        }
    
        public void mousePressed(  MouseEvent mev ){}
        public void mouseReleased( MouseEvent mev ){}
        public void mouseEntered(  MouseEvent mev ){}
        public void mouseExited(   MouseEvent mev ){}
    
        public void mouseClicked(  MouseEvent mev ){
            int i = mev.getX() / CELL_PXL;
            int j = mev.getY() / CELL_PXL;
            if( i < exchanges.width && j < exchanges.height ){
            for (int k=0; k<11; k++){
            if( exchanges.cells[i][j] == k ){ // toggle the value
                exchanges.cells[i][j] = k+1;
                exchanges.buffer[i][j] = k+1;
                break;
            }}
            if (exchanges.cells[i][j] == (11)){
                exchanges.cells[i][j] = 0;
                exchanges.buffer[i][j] = 0;  // toggles the old behaviour too for clarity
            }
           
            da.repaint();
            }
        }
        }
    }

  13. #13
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,189
    Rep Power
    19

    Default

    Java Code:
            iter1.loops();
        }
        
        public void loops()
       {
           long delayTime = 1000/FPS;     // main loop
        long startTime, waitTime, elapsedTime;
        while( true ){
    There's your problem. Better go through Lesson: Concurrency in Swing (The Java™ Tutorials > Creating a GUI With JFC/Swing)

    db
    Fubarable likes this.

  14. #14
    samanyu is offline Member
    Join Date
    Jun 2011
    Location
    Tsukuba, Japan
    Posts
    63
    Rep Power
    0

    Default

    So if I use Swing Worker, I should be calling my update() function in the background, and using process and publish to paint? Or both update and paint in the background?

Similar Threads

  1. Opening a Form Compile Error
    By shurgs in forum New To Java
    Replies: 7
    Last Post: 08-20-2010, 01:59 PM
  2. Error While Opening A PDF file
    By Cluster Storm in forum AWT / Swing
    Replies: 6
    Last Post: 06-07-2010, 06:03 PM
  3. Jre upgrade Issue :java.util.zip.ZipException: error in opening zip file
    By selvakumar.velmurugesan in forum New To Java
    Replies: 0
    Last Post: 10-27-2009, 05:20 AM
  4. Replies: 1
    Last Post: 10-26-2009, 04:38 PM
  5. Replies: 3
    Last Post: 01-26-2009, 05:30 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •