Problem with JFrame's dispose();

Hello everyone,
I'm having a problem with JFrame's dispose() method. In my program I have 2 classes which go into full screen. On each screen there is a button to switch to the other screen. The first time I push the button on both of them the other screen closes, which is what I want. However, if I push the same button more than twice - like by going from Screen1 to Screen2 and Screen2 to Screen1 and then Screen1 to Screen2 - I get 2 screens. If I keep doing that I eventually get 10+ screens up, which is bad. How do I prevent that?

There's a lot of code, so I'll just post up the part that does it.
backButton.addActionListener(new ActionListener()
              public void actionPerformed(ActionEvent e)
                  soundManagerM.close();
                    new MenuScreen().setVisible(true);
                    dispose();
         });I don't think it opens up 2 at once, because it would play multiple music right?

Similar Messages

  • Is there a problem with JFrame and window listeners?

    As the subject implies, i'm having a problem with my JFrame window and the window listeners. I believe i have implemented it properly (i copied it from another class that works). Anyway, none of the events are caught and i'm not sure why. Here's the code
    package gcas.gui.plan;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowListener;
    import java.util.Hashtable;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import gcas.plandata.TaskData;
    import gcas.util.GCASProperties;
    import gcas.gui.planlist.MainPanel;
    * MainFrame extends JPanel and is the main class for the plan details window
    public class MainFrame extends JFrame implements WindowListener
         * the container for this window
        private Container contentPane;
         * a string value containing the name of the plan being viewed
        private String labelText;
         * a string value containing the name of the window (GCAS - plan list)
        private static String title;
         * an instance of JDialog class
        private static MainFrame dialog;
         * hashTable that correlates the task name to its id as found in the
         * plan
        private Hashtable taskNameToId = new Hashtable();
         * an instance of taskSetPane.  This is the current instance of taskSetPane
         * being viewed
        private PlanTaskSet currentPane;
         * instance of TaskData class.  Each instance will hold information on
         * an individual task
        private TaskData taskData;
         * hashTable containing instances of the taskSetPane class
        private Hashtable taskSetPanes = new Hashtable();
         * an instance of the OuterPanel class
        OuterPanel mainPanel;
         * an instance of the ButtonPanel class
        ButtonPanel buttonsPanel;
         * an instance of the LeftPanel class
        LeftPanel leftPanel;
         * an instance of the the GCASProperties class
        GCASProperties gcasProps;
        private static MainFrame thisPlanMain = null;
        private MainPanel planListMain;
         * constructor for MainFrame
         * @param frame the parent frame calling this class
         * @param locationComp the location of the component that initiated the opening of the dialog
         * @param labelText the name of the plan that is being viewed
         * @param title title of window
        private MainFrame(JFrame frame, Component locationComp, String labelText,
                String title)
            super(title);
            gcasProps = GCASProperties.getInstance();
            mainPanel = new OuterPanel(labelText, currentPane,
                    taskNameToId, taskSetPanes);
            leftPanel = mainPanel.getLeftPanel();
            System.out.println("LABLE: " + labelText);
            leftPanel.setMainPanelContents();
            buttonsPanel = new ButtonPanel(labelText, taskSetPanes,
                    taskNameToId, leftPanel);
            contentPane = getContentPane();
            contentPane.add(mainPanel, BorderLayout.CENTER);
            contentPane.add(buttonsPanel, BorderLayout.PAGE_END);
            this.addWindowListener(this);
            this.labelText = labelText;
            pack();
            setLocationRelativeTo(locationComp);
            this.setVisible(true);
            planListMain = MainPanel.getInstance();
            planListMain.setVisible(false);
        public static MainFrame getInstance(JFrame frame, Component locationComp, String labelText,
                String title)
            if (thisPlanMain == null)
                thisPlanMain = new MainFrame(frame, locationComp, labelText,
                        title);
            return thisPlanMain;
        public static MainFrame getDialogObject()
        {   //from the location this is called (ButtonPanel), this will never
            //be null
            return thisPlanMain;
        public static void setABMDDialogNull()
            thisPlanMain = null;
         * returns an instance of MainFrame
         * @return MainFrame instance
        public static MainFrame getDialog()
            return dialog;
         * setter for MainFrame
         * @param aDialog a MainFrame instance
        public static void setDialog(MainFrame aDialog)
            dialog = aDialog;
         * window opened event
         * @param windowEvent the window event passed to this method
        public void windowOpened(WindowEvent windowEvent)
         * The window event when a window is closing
         * @param windowEvent the window event passed to this method
        public void windowClosing(WindowEvent windowEvent)
            gcasProps.storeProperties("PlanList");
            MainPanel abmd = MainPanel.getInstance();
    //        planMain = this.getDialogObject();
    //        if(planMain != null)
    //            planMain.setVisible(false);
    //            abmd.setVisible(true);
    //            planMain.setABMDDialogNull();
            if(this.getDialogObject()!= null)
                abmd.setVisible(true);
                setVisible(false);
                setABMDDialogNull(); 
         * Invoked when the Window is set to be the active Window
         * @param windowEvent the window event passed to this method
        public void windowActivated(WindowEvent windowEvent)
         * Invoked when a window has been closed as the result of calling dispose on the window
         * @param windowEvent the window event passed to this method
        public void windowClosed(WindowEvent windowEvent)
         * Invoked when a Window is no longer the active Window
         * @param windowEvent the window event passed to this method
        public void windowDeactivated(WindowEvent windowEvent)
            System.out.println("HI");
         * Invoked when a window is changed from a minimized to a normal state
         * @param windowEvent the window event passed to this method
        public  void windowDeiconified(WindowEvent windowEvent)
            //we could have code here that changed the way alerts are done
           System.out.println("Invoked when a window is changed from a minimized to a normal state.");
         * Invoked when a window is changed from a normal to a minimized state
         * @param windowEvent the window event passed to this method
        public  void windowIconified(WindowEvent windowEvent)
            //we could have code here that changed the way alerts are done
    //        System.out.println("Invoked when a window is changed from a normal to a minimized state.");
    }anyone know whats wrong?

    It turned out that my ide was running the old jar and not updating it, so no matter what code i added, it wasn't being seen. Everything should be fine now.

  • Problem with JFrame and busy/wait Cursor

    Hi -- I'm trying to set a JFrame's cursor to be the busy cursor,
    for the duration of some operation (usually just a few seconds).
    I can get it to work in some situations, but not others.
    Timing does seem to be an issue.
    There are thousands of posts on the BugParade, but
    in general Sun indicates this is not a bug. I just need
    a work-around.
    I've written a test program below to demonstrate the problem.
    I have the problem on Solaris, running with both J2SE 1.3 and 1.4.
    I have not tested on Windows yet.
    When you run the following code, three JFrames will be opened,
    each with the same 5 buttons. The first "F1" listens to its own
    buttons, and works fine. The other two (F2 and F3) listen
    to each other's buttons.
    The "BUSY" button simply sets the cursor on its listener
    to the busy cursor. The "DONE" button sets it to the
    default cursor. These work fine.
    The "SLEEP" button sets the cursor, sleeps for 3 seconds,
    and sets it back. This does not work.
    The "INVOKE LATER" button does the same thing,
    except is uses invokeLater to sleep and set the
    cursor back. This also does not work.
    The "DELAY" button sleeps for 3 seconds (giving you
    time to move the mouse into the other (listerner's)
    window, and then it behaves just like the "SLEEP"
    button. This works.
    Any ideas would be appreciated, thanks.
    -J
    import java.awt.BorderLayout;
    import java.awt.Cursor;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    public class BusyFrameTest implements ActionListener
    private static Cursor busy = Cursor.getPredefinedCursor (Cursor.WAIT_CURSOR);
    private static Cursor done = Cursor.getDefaultCursor();
    JFrame frame;
    JButton[] buttons;
    public BusyFrameTest (String title)
    frame = new JFrame (title);
    buttons = new JButton[5];
    buttons[0] = new JButton ("BUSY");
    buttons[1] = new JButton ("DONE");
    buttons[2] = new JButton ("SLEEP");
    buttons[3] = new JButton ("INVOKE LATER");
    buttons[4] = new JButton ("DELAY");
    JPanel buttonPanel = new JPanel();
    for (int i = 0; i < buttons.length; i++)
    buttonPanel.add (buttons);
    frame.getContentPane().add (buttonPanel);
    frame.pack();
    frame.setVisible (true);
    public void addListeners (ActionListener listener)
    for (int i = 0; i < buttons.length; i++)
    buttons[i].addActionListener (listener);
    public void actionPerformed (ActionEvent e)
    System.out.print (frame.getTitle() + ": " + e.getActionCommand());
    if (e.getActionCommand().equals ("BUSY"))
    frame.setCursor (busy);
    else if (e.getActionCommand().equals ("DONE"))
    frame.setCursor (done);
    else if (e.getActionCommand().equals ("SLEEP"))
    frame.setCursor (busy);
    try { Thread.sleep (3000); } catch (Exception ex) { }
    frame.setCursor (done);
    System.out.print (" finished");
    else if (e.getActionCommand().equals ("INVOKE LATER"))
    frame.setCursor (busy);
    SwingUtilities.invokeLater (thread);
    else if (e.getActionCommand().equals ("DELAY"))
    try { Thread.sleep (3000); } catch (Exception ex) { }
    frame.setCursor (busy);
    try { Thread.sleep (3000); } catch (Exception ex) { }
    frame.setCursor (done);
    System.out.print (" finished");
    System.out.println();
    Runnable thread = new Runnable()
    public void run()
    try { Thread.sleep (3000); } catch (Exception ex) { }
    frame.setCursor (done);
    System.out.println (" finished");
    public static void main (String[] args)
    BusyFrameTest f1 = new BusyFrameTest ("F1");
    f1.addListeners (f1);
    BusyFrameTest f2 = new BusyFrameTest ("F2");
    BusyFrameTest f3 = new BusyFrameTest ("F3");
    f2.addListeners (f3); // 2 listens to 3
    f3.addListeners (f2); // 3 listens to 2

    I've had the same problems with cursors and repaints in a swing application, and I was thinking of if I could use invokeLater, but I never got that far with it.
    I still believe you would need a thread for the time consuming task, and that invokeLater is something you only need to use in a thread different from the event thread.

  • Advance level drawing problem with Jframe and JPanel need optimize sol?

    Dear Experts,
    I m trying to create a GUI for puzzle game following some kind of "game GUI template", but i have problems in that,so i tried to implement that in various ways after looking on internet and discussions about drawing gui in swing, but i have problem with both of these, may be i m doing some silly mistake, which is still out of my consideration. please have a look at these two and recommend me one of them, which is running without problems (flickring and when you enlarge window the board draw copies (tiled) everywhere,
    Note: i don't want to inherit jpanel or Jframe
    here is my code : import java.awt.BorderLayout;
    public class GameMain extends JFrame {
         private static final long serialVersionUID = 1L;
         public int mX, mY;
         int localpoints = 0;
         protected static JTextField[][] squares;
         protected JLabel statusLabel = new JLabel("jugno");
         Label lbl_score = new Label("score");
         Label lbl_scorelocal = new Label("local score");
         protected static TTTService remoteTTTBoard;
         // Define constants for the game
         static final int CANVAS_WIDTH = 800; // width and height of the game screen
         static final int CANVAS_HEIGHT = 600;
         static final int UPDATE_RATE = 4; // number of game update per second
         static State state; // current state of the game
         private int mState;
         // Handle for the custom drawing panel
         private GameCanvas canvas;
         // Constructor to initialize the UI components and game objects
         public GameMain() {
              // Initialize the game objects
              gameInit();
              // UI components
              canvas = new GameCanvas();
              canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
              this.setContentPane(canvas);
              this.setDefaultCloseOperation(EXIT_ON_CLOSE);
              this.pack();
              this.setTitle("MY GAME");
              this.setVisible(true);
         public void gameInit() {     
         // Shutdown the game, clean up code that runs only once.
         public void gameShutdown() {
         // To start and re-start the game.
         public void gameStart() {
         private void gameLoop() {
         public void keyPressed(KeyEvent e) {
         public void keyTyped(KeyEvent e) {
         public void gameKeyReleased(KeyEvent e) {
              PuzzleBoard bd = getBoard();
              for (int row = 0; row < 4; ++row) {
                   for (int col = 0; col < 4; ++col) {
                        if (e.getSource() == squares[row][col]) {
                             if (bd.isOpen(col, row)) {
                                  lbl_score.setText("Highest Score = "
                                            + Integer.toString(bd.getPoints()));
                                  setStatus1(bd);
                                  pickSquare1(col, row, squares[row][col].getText()
                                            .charAt(0));
         protected void pickSquare1(int col, int row, char c) {
              try {
                   remoteTTTBoard.pick(col, row, c);
              } catch (RemoteException e) {
                   System.out.println("Exception: " + e.getMessage());
                   e.printStackTrace();
                   System.exit(1);
         // method "called" by remote object to update the state of the game
         public void updateBoard(PuzzleBoard new_board) throws RemoteException {
              String s1;
              for (int row = 0; row < 4; ++row) {
                   for (int col = 0; col < 4; ++col) {
                        squares[row][col].setText(new_board.ownerStr(col, row));
              lbl_score.setText("Highest Score = "
                        + Integer.toString(new_board.getPoints()));
              setStatus1(new_board);
         protected void setStatus1(PuzzleBoard bd) {
              boolean locals = bd.getHave_winner();
              System.out.println("local win" + locals);
              if (locals == true) {
                   localpoints++;
                   System.out.println("in condition " + locals);
                   lbl_scorelocal.setText("Your Score = " + localpoints);
              lbl_score
                        .setText("Highest Score = " + Integer.toString(bd.getPoints()));
         protected PuzzleBoard getBoard() {
              PuzzleBoard res = null;
              try {
                   res = remoteTTTBoard.getState();
              } catch (RemoteException e) {
                   System.out.println("Exception: " + e.getMessage());
                   e.printStackTrace();
                   System.exit(1);
              return res;
         /** Custom drawing panel (designed as an inner class). */
         class GameCanvas extends JPanel implements KeyListener {
              /** Custom drawing codes */
              @Override
              public void paintComponent(Graphics g) {
                   // setOpaque(false);
                   super.paintComponent(g);
                   // main box; everything placed in this
                   // JPanel box = new JPanel();
                   setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
                   // add(statusLabel, BorderLayout.NORTH);
                   // set up the x's and o's
                   JPanel xs_and_os = new JPanel();
                   xs_and_os.setLayout(new GridLayout(5, 5, 0, 0));
                   squares = new JTextField[5][5];
                   for (int row = 0; row < 5; ++row) {
                        for (int col = 0; col < 5; ++col) {
                             squares[row][col] = new JTextField(1);
                             squares[row][col].addKeyListener(this);
                             if ((row == 0 && col == 1) || (row == 2 && col == 3)
                             || (row == 1 && col == 4) || (row == 4 && col == 4)
                                       || (row == 4 && col == 0))
                                  JPanel p = new JPanel(new BorderLayout());
                                  JLabel label;
                                  if (row == 0 && col == 1) {
                                       label = new JLabel("1");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 4 && col == 0) {// for two numbers or
                                       // two
                                       // blank box in on row
                                       label = new JLabel("2");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 1 && col == 4) {
                                       label = new JLabel("3");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 4) {
                                       label = new JLabel("4");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else {
                                       label = new JLabel("5");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  label.setOpaque(true);
                                  label.setBackground(squares[row][col].getBackground());
                                  label.setPreferredSize(new Dimension(label
                                            .getPreferredSize().width, squares[row][col]
                                            .getPreferredSize().height));
                                  p.setBorder(squares[row][col].getBorder());
                                  squares[row][col].setBorder(null);
                                  p.add(label, BorderLayout.WEST);
                                  p.add(squares[row][col], BorderLayout.CENTER);
                                  xs_and_os.add(p);
                             } else if ((row == 2 && col == 1) || (row == 1 && col == 2)
                                       || (row == 3 && col == 3) || (row == 0 && col == 3)) {
                                  xs_and_os.add(squares[row][col]);
                                  // board[ row ][ col ].setEditable(false);
                                  // board[ row ][ col ].setText("");
                                  squares[row][col].setBackground(Color.RED);
                                  squares[row][col].addKeyListener(this);
                             } else {
                                  squares[row][col] = new JTextField(1);
                                  // squares[row][col].addActionListener(this);
                                  squares[row][col].addKeyListener(this);
                                  xs_and_os.add(squares[row][col]);
                   this.add(xs_and_os);
                   this.add(statusLabel);
                   this.add(lbl_score);
                   this.add(lbl_scorelocal);
              public void keyPressed(KeyEvent e) {
              public void keyReleased(KeyEvent e) {
                   gameKeyReleased(e);
              public void keyTyped(KeyEvent e) {
         // main
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                   @Override
                   public void run() {
                        new GameMain();
      thanks a lot for your time , consideration and efforts.
    jibby
    Edited by: jibbylala on Sep 20, 2010 6:06 PM

    jibbylala wrote:
    thanks for mentioning as i wasn't able to write complete context here.Yep thanks camickr. I think that Darryl's succinct reply applies here as well.

  • Problem with JFrame class.

    To risolve my problem i need for few diferent frame
    ( for esample in one i put JTextFild that take the user input, in a nother one i need for program output ) . But, th problem is, all my frames using the same object.
    If i construct diferent JFrame window class i have problem that i don't acess in the same object from all the window. And if i dont use a object, i have static acess .
    I risolve the problem with 1 JFrame class with diferent constructors, but i wont a diferent way to risolve my problem, because there are few windows.
    Help me.....

    Make the class that extends JFrame an inner class of the the main class. You can then access all members of the outer class.

  • Problem with JFrame resizing at runtime

    Hi All,
    I have a problem with resizing the JFrame at runtime. Even if i resize the JPanel. It is not affection on all the components over the frame. How can i solve that I am using AbsoluteLayout(jre1.6) and here i am going to provide you code snippet. My requirement is to resizt the form. If form is small in size then all the component should also be according tothe size of the form.
    public void initComponents(int size) {
    if(size >= 50) {
    x_co_or = 300;
    y_co_or = 300;
    } else if(size < 50) {
    x_co_or = 200;
    y_co_or = 200;
    jPanel1 = new javax.swing.JPanel();
    jButton1 = new javax.swing.JButton();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
    jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
    jButton1.setText("jButton1");
    jPanel1.add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 40, 110, 40));
    getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, x_co_or, y_co_or));
    pack();
    Can anybody suggest any idea/solution.
    Any idea/solution are most welcome.
    Regards,
    Pradeep Dubey

    How can i solve that I am using AbsoluteLayout(jre1.6)
    and here i am going to provide you code snippet.no need for the snippet, you're using absolute positioning, which means you're responsible for location and size on every single change.
    start coding now, take about a week, or you could use a layout manager, take maybe, 5 minutes

  • Problem with JFrame code

    Can anyone say the problem with the attached code. When I run the program, only, maximize, minimize and close options are viewable and nothing else.
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Graphics;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Image;
    import java.awt.Insets;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.border.LineBorder;
    * Created on Mar 24, 2008
    * @author Anand
    public class JBackGroundImageDemo extends JFrame
        Container con = null;
        JPanel panelBgImg;
        public JBackGroundImageDemo()
            setTitle("JBackGroundImageDemo");
            con = getContentPane();
            con.setLayout(null);
            ImageIcon imh = new ImageIcon("aditi.jpg");
            setSize(imh.getIconWidth(), imh.getIconHeight());
            panelBgImg = new JPanel()
                public void paintComponent(Graphics g)
                    Image img = new ImageIcon("aditi.jpg").getImage();
                    Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
                    setPreferredSize(size);
                    setMinimumSize(size);
                    setMaximumSize(size);
                    setSize(size);
                    setLayout(null);
                    g.drawImage(img, 0, 0, null);
            con.add(panelBgImg);
            panelBgImg.setBounds(0, 0, imh.getIconWidth(), imh.getIconHeight());
            GridBagLayout layout = new GridBagLayout();
            JPanel panelContent = new JPanel(layout);
            GridBagConstraints gc = new GridBagConstraints();
            gc.insets = new Insets(3, 3, 3, 3);
            gc.gridx = 1;
            gc.gridy = 1;
            JLabel label = new JLabel("UserName: ", JLabel.LEFT);                       
            panelContent.add(label, gc);
            gc.gridx = 2;
            gc.gridy = 1;
            JTextField txtName = new JTextField(10);
            panelContent.add(txtName, gc);
            gc.insets = new Insets(3, 3, 3, 3);
            gc.gridx = 1;
            gc.gridy = 2;
            gc.gridwidth = 2;
            JButton btn = new JButton("Login");
            panelContent.add(btn, gc);
            panelContent.setBackground(Color.GRAY);
            panelContent.setBorder(new LineBorder(Color.WHITE));
            panelBgImg.add(panelContent);
            panelBgImg.setLayout(new FlowLayout(FlowLayout.CENTER, 150, 200));
            setResizable(false);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        public static void main(String[] args)
            new JBackGroundImageDemo().setVisible(true);
         Please help.
    Regards,
    Anees

    Here's you a little code example, it works, so take a look at it.
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.MediaTracker;
    import java.awt.Toolkit;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class Junk{
      public Junk(){
      public void makeFrame(){
        JFrame j = new JFrame("Junk");
        Toolkit t = Toolkit.getDefaultToolkit();
        MediaTracker mt = new MediaTracker(j);
        Image img = t.getImage("junk.jpg");
        mt.addImage(img, 0);
        try{
          mt.waitForID(0);
        }catch(InterruptedException e){
          System.out.println("Hey, we were too impatient!");
        myPanel p = new myPanel(img);
        p.setPreferredSize(new Dimension(img.getWidth(null), img.getHeight(null)));
        j.add(p);
        j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        j.pack();
        j.setVisible(true);
      public static void main(String[] args){
        new Junk().makeFrame();
      class myPanel extends JPanel{
        Image img;
        myPanel(Image img){
          this.img = img;
        public void paintComponent(Graphics g){
          g.drawImage(img, 0, 0, this);
    }BTW: your image should be in your project folder.

  • Problem with JFrame, it goes blank

    i
    My problem is with JFrame, when it's carrying operation which takes a bit of time, if somethhing goes on
    top of the frame the frame goes blank, all the components vanished and when the operation is completed the components bacome visible. I dont know why this is happening,. The code is below, since my code is very complicated I am sending some code whcih shows the problem I have, when you press the button it execute's a for loop, whcih takes some time. If you minimize the frame and maximize again, you'll see what I mean.
    Please help!!!
    Many Thanks
    Lilylay
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Frame1 extends JFrame {
    JPanel contentPane;
    JButton jButton2 = new JButton();
    /**Construct the frame*/
    public Frame1() {
    enableEvents(AWTEvent.WINDOW_EVENT_MASK);
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    /**Component initialization*/
    private void jbInit() throws Exception {
    //setIconImage(Toolkit.getDefaultToolkit().createImage(Frame1.class.getResource("[Your Icon]")));
    contentPane = (JPanel) this.getContentPane();
    contentPane.setLayout(null);
    this.setSize(new Dimension(407, 289));
    this.setTitle("Frame Title");
    contentPane.setBackground(SystemColor.text);
    contentPane.setForeground(Color.lightGray);
    jButton2.setText("Press me!");
    jButton2.setBounds(new Rectangle(107, 111, 143, 48));
    jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
    public void mousePressed(MouseEvent e) {
    jButton2_mousePressed(e);
    contentPane.add(jButton2, null);
    /**Overridden so we can exit when window is closed*/
    protected void processWindowEvent(WindowEvent e) {
    super.processWindowEvent(e);
    if (e.getID() == WindowEvent.WINDOW_CLOSING) {
    System.exit(0);
    void jButton2_mousePressed(MouseEvent e) {
    for(int i=0; i<256898; i++){
    for(int j=0; j<5656585; j++){
    System.out.println("hello");
    public static void main(String [] args){
    Frame1 frame=new Frame1();
    frame.show();
    }

    The reason this is happening is because your loop is so intensive that your program doesn't have time to refresh its JFrame. There is no great way to get past this stumbling block without decreasing the efficiency of your code. One possible solution is to call repaint() from within your loop, but of course this slows down your loop.
    Hope that helps

  • Problem with JFrame updating

    I'm having trouble making this application remove the "Client 1: 127.0.0.1 [localhost]" (and Client 2: or how ever many are connected) from a Box inside of a JPanel inside of a JFrame...
    I searched around a bit, but nothing fixed my problem. (SwingUtilities.invokeLater(new Runnable() etc is from another post, but with or without it I can't get it to work...)
    Running Fedora Core 2, JDK 1.4.2_04.
    Thanks in advance.
    (Hrmm, I had to mess with some of the longer lines to get them to display correctly...)
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class PennyServer extends JFrame implements ActionListener
         private Boolean finished;
         private Border border;
         private Box clientBox;
         private BoxLayout boxlayout;
         private Container content;
         private Dimension size;
         private JButton button;
         private JPanel buttonList;
         private JPanel clientList;
         private LinkedList llClient, llInput, llOutput;
         PennyServer()
              setBounds(100, 100, 400, 400);
    //          setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
              setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
              setTitle("Test Server - by Joshua");
              content = getContentPane();
              border = BorderFactory.createRaisedBevelBorder();
              boxlayout = new BoxLayout(content, BoxLayout.Y_AXIS);
              clientBox = Box.createVerticalBox();
              size = new Dimension(80, 20);
              clientList = new JPanel(new BorderLayout());
              buttonList = new JPanel();
              content.setLayout(boxlayout);
              clientList.setBorder(new TitledBorder(new EtchedBorder(), "Client List"));
              clientList.add(clientBox, BorderLayout.CENTER);
              buttonList.add(button = new JButton("Start"));
              button.setBorder(border);
              button.setPreferredSize(size);
              button.addActionListener(this);
              buttonList.add(button = new JButton("Quit"));
              button.setBorder(border);
              button.setPreferredSize(size);
              button.addActionListener(this);
              buttonList.setBorder(
                   new CompoundBorder(
                        BorderFactory.createLineBorder(Color.black, 1),
                        BorderFactory.createBevelBorder(BevelBorder.RAISED)
              content.add(clientList);
              content.add(buttonList);
              setVisible(true);
              finished = new Boolean(false);
              llClient = new LinkedList();
              llInput = new LinkedList();
              llOutput = new LinkedList();
         public void addClient(Socket s)
              try
                   s.setSoTimeout(0100);
                   s.setTcpNoDelay(true);
                   llClient.addLast(s);
                   llInput.addLast(
                        new BufferedReader(
                             new InputStreamReader(
                                  s.getInputStream()
                   llOutput.addLast(new PrintStream(s.getOutputStream()));
              catch (Exception e)
                   System.out.println ("<" + e + ">");
              SwingUtilities.invokeLater(new Runnable()
                   public void run()
                        refreshClientList();
         public void refreshClientList()
              InetAddress addr;
              ListIterator iter = llClient.listIterator(0);
              clientBox.removeAll();
              clientBox.add(Box.createVerticalStrut(20));
              while(iter.hasNext())
                   addr = ((Socket) iter.next()).getInetAddress();
    System.out.println (
         "Debug:  refreshClientList():  adding client " +
         (iter.previousIndex() + 1)
                   // This is not going away on the display...
                   clientBox.add(
                        new JLabel(
                             "Client " + (iter.previousIndex() + 1) + ": " +
                             addr.getHostAddress() + " [" + addr.getHostName() + "]"
                   if (iter.hasNext())
                        clientBox.add(Box.createVerticalStrut(20));
              clientBox.revalidate();
         public void select()
              BufferedReader in;
              ListIterator iterClient = llClient.listIterator(0);
              ListIterator iterInput = llInput.listIterator(0);
              ListIterator iterOutput = llOutput.listIterator(0);
              PrintStream out;
              Socket s;
              String userInput;
              while(iterClient.hasNext() && iterInput.hasNext() && iterOutput.hasNext())
                   s = (Socket) iterClient.next();
                   in = (BufferedReader) iterInput.next();
                   out = (PrintStream) iterOutput.next();
                   try
                        userInput = in.readLine();
                        if (userInput == null)
                             System.out.println (
                                  "Client " + (iterClient.previousIndex() + 1) +
                                  " has disconnected from the server."
                             iterClient.remove();
                             iterInput.remove();
                             iterOutput.remove();
                             SwingUtilities.invokeLater(new Runnable()
                                  public void run()
                                       refreshClientList();
                             continue;
                        System.out.println (
                             "Client " + (iterClient.previousIndex() + 1) +
                             ": " + userInput
                   catch (SocketTimeoutException e)
                   {}  // Do nothing, 100 millisecond time expired
                   catch (Exception e)
                        System.out.println ("<" + e + ">");
                   userInput = null;
         public boolean alive()
              return (!(finished.booleanValue()));
         public static void main (String[] args)
              try
                   PennyServer penny = new PennyServer();
                   ServerSocket ss;
                   Socket client;
                   ss = new ServerSocket(1234);  // Start a listening socket on port 1234
                   ss.setReuseAddress(true);  // Reuse local address/port combonation
                   ss.setSoTimeout(0100);  // 100 milliseconds, to simulate nonblocking IO
                   while(penny.alive())
                        penny.select();  // Poll sockets for input
                        try
                             penny.addClient(client = ss.accept());
                        catch (SocketTimeoutException e)
                        {}  // Do nothing, 100 millisecond time expired
                   penny.dispose();
                   ss.close();
              catch (Exception e)
                   System.out.println ("<" + e + ">");
         public void actionPerformed(ActionEvent event)
              if (event.getActionCommand().equals("Start"))
              else if (event.getActionCommand().equals("Quit"))
                   finished = new Boolean(true);
    }Joshua

    Ahha! Thank you, sjl. It works perfectly now.
    I thought it would be something silly, but I couldn't for the life of me figure out what.
    Joshua

  • Problem with JFrame and JPanel

    Okay, well I'm busy doing a lodge management program for a project and I have programmed this JFrame
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class FinalTest extends JFrame
         public JPanel contentPane;
         public JImagePanel imgPanel;
         private JLabel[] cottageIcon;
         private boolean keepMoving;
         private int selectedCottage;
         public FinalTest()
              super();
              initializeComponent();
              addActionListeners();
              this.setVisible(true);
         private void initializeComponent()
              contentPane = (JPanel)getContentPane();
              contentPane.setLayout(null);
              imgPanel = new JImagePanel("back.png");
               imgPanel.setLayout(null);
              imgPanel.setBackground(new Color(1, 0, 0));
                   addComponent(contentPane, imgPanel, 10,10,imgPanel.getImageWidth(),imgPanel.getImageHeight());
              cottageIcon = new JLabel[6];
              keepMoving = true;
              selectedCottage = 0;
              cottageIcon[0] =  new JLabel();
              //This component will never be added or shown, but needs to be there to cover for no cottage selected
              for(int a = 1; a < cottageIcon.length; a++)
                   cottageIcon[a] = new JLabel("C" + (a));
                   cottageIcon[a].setBackground(new Color(255, 0, 0));
                    cottageIcon[a].setHorizontalAlignment(SwingConstants.CENTER);
                    cottageIcon[a].setHorizontalTextPosition(SwingConstants.LEADING);
                    cottageIcon[a].setForeground(new Color(255, 255, 255));
                    cottageIcon[a].setOpaque(true);
                    addComponent(imgPanel,cottageIcon[a],12,(a-1)*35 + 12,30,30);
                this.setTitle("Cottage Chooser");
                this.setLocationRelativeTo(null);
              this.setSize(new Dimension(540, 430));
         private void addActionListeners()
              imgPanel.addMouseListener(new MouseAdapter()
                   public void mousePressed(MouseEvent e)
                        imgPanel_mousePressed(e);
                   public void mouseReleased(MouseEvent e)
                        imgPanel_mouseReleased(e);
                   public void mouseEntered(MouseEvent e)
                        imgPanel_mouseEntered(e);
              imgPanel.addMouseMotionListener(new MouseMotionAdapter()
                   public void mouseDragged(MouseEvent e)
                        imgPanel_mouseDragged(e);
         private void addComponent(Container container,Component c,int x,int y,int width,int height)
              c.setBounds(x,y,width,height);
              container.add(c);
         private void imgPanel_mousePressed(MouseEvent e)
              for(int a = 1; a < cottageIcon.length; a++)
                   if(withinBounds(e.getX(),e.getY(),cottageIcon[a].getBounds()))
                        System.out.println("B" + withinBounds(e.getX(),e.getY(),cottageIcon[a].getBounds()));
                        selectedCottage = a;
                        keepMoving = true;
         private void imgPanel_mouseReleased(MouseEvent e)
              System.out.println("called");
              selectedCottage = 0;
              keepMoving = false;
         private void imgPanel_mouseDragged(MouseEvent e)
               System.out.println("XXX" + Math.random() * 100);
              if(keepMoving)
                   int x = e.getX();
                    int y = e.getY();
                    if(selectedCottage!= 0)
                         cottageIcon[selectedCottage].setBounds(x-(30/2),y-(30/2),30,30);
                    if(!legalBounds(imgPanel,cottageIcon[selectedCottage]))
                        keepMoving = false;
                        cottageIcon[selectedCottage].setBounds(imgPanel.getWidth()/2,imgPanel.getHeight()/2,30,30);
              System.out.println(cottageIcon[selectedCottage].getBounds());
         private void imgPanel_mouseEntered(MouseEvent e)
               System.out.println("entered");
         private void but1_actionPerformed(ActionEvent e)
              String input = JOptionPane.showInputDialog(null,"Enter selected cottage");
              selectedCottage = Integer.parseInt(input) - 1;
         public boolean legalBounds(Component containerComponent, Component subComponent)
              int contWidth = containerComponent.getWidth();
              int contHeight = containerComponent.getHeight();
              int subComponentX = subComponent.getX();
              int subComponentY = subComponent.getY();
              int subComponentWidth = subComponent.getWidth();
              int subComponentHeight = subComponent.getHeight();
              if((subComponentX < 0) || (subComponentY < 0) || (subComponentX > contWidth) || (subComponentY > contHeight))
                   return false;
              return true;
         public boolean withinBounds(int mouseX, int mouseY, Rectangle componentRectangle)
              int componentX = (int)componentRectangle.getX();
              int componentY = (int)componentRectangle.getY();
              int componentHeight = (int)componentRectangle.getHeight();
              int componentWidth = (int)componentRectangle.getWidth();
              if((mouseX >= componentX) && (mouseX <= (componentX + componentWidth)) && (mouseY >= componentY) && (mouseY <= (componentY + componentWidth)))
                   return true;
              return false;
         public static void main(String[] args)
              JFrame.setDefaultLookAndFeelDecorated(true);
              //JDialog.setDefaultLookAndFeelDecorated(true);
              try
                   UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
              catch (Exception ex)
                   System.out.println("Failed loading L&F: ");
                   System.out.println(ex);
              FinalTest ft = new FinalTest();
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Image;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class JImagePanel extends JPanel
      private Image image;
      public JImagePanel(String imgFileName)
           image = new ImageIcon(imgFileName).getImage();
        setLayout(null);
      public void paintComponent(Graphics g)
        g.drawImage(image, 0, 0, null);
      public Dimension getImageSize()
                Dimension size = new Dimension(image.getWidth(null), image.getHeight(null));
             return size;
      public int getImageWidth()
                int width = image.getWidth(null);
                return width;
      public int getImageHeight()
              int height = image.getHeight(null);
              return height;
    }Now the problem I'm having is changing that class to a JFrame, it seems simple but I keep having problems like when it runs from another JFrame nothing pops up. I can do it like this:
    FinalTest ft = new FinalTest();
    ft.setVisible(false);
    JPanel example = ft.contentPanehowever I will probably be marked down on this for bad code. I'm not asking for the work to be done for me, but I'm really stuck on this and just need some pointers so I can carry on with the project. Thanks,
    Steve

    CeciNEstPasUnProgrammeur wrote:
    I'd actually consider your GUI being a JPanel instead of a JFrame quite good design - makes it easy to put the stuff into an applet when necessary...
    Anyway, you should set setVisible() to true to make it appear, not to false. Otherwise, I don't seem to understand your problem.That is actually my problem. I am trying to convert this JFrame to a JPanel

  • Problem with JFrame , please help !

    hello , all !
    I define a JFrame1 as ancestor
    I set the JFrame's contentPane Layout to borderLayout ,
    and add some component in south , north , and add a menu , in its constructor
    then I define a new JFrame2 inherit from JFrame1, I also add a Jpanel component
    to contentPane center in its constructor !
    but something a wrong , I can't see the Jpanel , only see the components which add in JFrame1?
    this is why ?
    thanks
    /* source code */
    public class JFrame1{
    public JFrame1(){
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    private void jbInit() throws Exception {
    contentPane = (JPanel) this.getContentPane();
    contentPane.setLayout(borderLayout1);
    statusBar.setBorder(BorderFactory.createEtchedBorder());
    statusBar.setText("Hello , Young follow! ");
    contentPane.add(statusBar, BorderLayout.SOUTH);
    toolbar = new Toolbar_DataEntry(this);
    contentPane.add(toolbar, BorderLayout.NORTH);
    menubar = new Menu_DataEntry(this);
    this.setJMenuBar(menubar);
    public class JFrame2 extends JFrame1 {
    public JFrame2() {
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    /**Component initialization*/
    private void jbInit() throws Exception {
    contentPane = (JPanel) this.getContentPane();
    JPanel bodyPane = new JPanel();
    bodyPane.setDataModule(queryDataSet1);
    queryDataSet1.Opendatabase();
    bodyPane.setBorder(null);
    this.setTitle("Frame Title");
    bodyPane.setBounds(new Rectangle(4, 5, 427, 114));
    contentPane.setPreferredSize(bodyPane.getPreferredSize());
    contentPane.setMinimumSize(bodyPane.getMinimumSize());
    Frame_Resize();

    The problem is that the constructor for JFrame2 does not automatically call the constructor for JFrame1. Therefore the JFrame1 constructor never gets called.
    You must do this yourself with the super() method.
    public JFrame2() {
    super();
    try {
    jbinit();
    catch( Exception e )
    e.printStackTrace();
    Remember that this rule applies to all descendent classes.

  • Problem with jframe has jtextfield and jpanel

    hi all
    i ve a jframe with some components on it
    of these components a jpanel that i repaint each time i want
    and a textfield for chatting between players
    the problem is as follows
    some times when i click the textfield after repaining the panel
    it can not be activated and the caret does not appear
    when i click any other component out or in the frame
    and return i get it active and in a good state
    i use single buffer for repapint
    thanks for reading
    i'm waiting for response

    Your best bet here is to show us your code. We don't want to see all of it, but rather you should condense your code into the smallest bit that still compiles, has no extra code that's not relevant to your problem, but still demonstrates your problem, in other words, an SSCCE (Short, Self Contained, Correct (Compilable), Example). For more info on SSCCEs please look here:
    [http://homepage1.nifty.com/algafield/sscce.html|http://homepage1.nifty.com/algafield/sscce.html]
    Again, if the code is compilable and runnable more people will be able to help you.
    Also, when posting your code, please use code tags so that your code will retain its formatting and be readable. To do this, you will need to paste already formatted code into the forum, highlight this code, and then press the "code" button at the top of the forum Message editor prior to posting the message. You may want to click on the Preview tab to make sure that your code is formatted correctly. Another way is to place the tag &#91;code] at the top of your block of code and the tag &#91;/code] at the bottom, like so:
    &#91;code]
      // your code block goes here.
      // note the differences between the tag at the top vs the bottom.
    &#91;/code]

  • Problem with JFrame, JPanel and getInsets()...

    hi, this is my problem:
    I have a JFrame and I want add a JPanel to its ContentPan, I need to know the JFrame's getInsets values to set (with setBounds()) the right dimensions of the JPanel, but if I call getInsets() before of setVisible(true) I obtain all 0 values, if I call setVisible(true) before of add() I obtain the right values, but the JPanel is not showed.
    By now I have solved with this sequence:
    new panel();
    contpan.add(panel);
    getInsets();
    panel.setBounds();but I would pass the bounds values to my panel constructor, something like this:
    new panel(getInsets(););
    contpan.add(panel);Could someone help me?

    I have just found this post:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=302473
    And the first way seems to be the only way to solve the problem... :(
    Now the question is, does it exist a way to refresh a JFrame after that I have uset setVisible(true)?
    If it does exist I could have something like this:
    setVisible(true)
    new panel(getInsets(););
    contpan.add(panel);
    REFRESH();

  • Problem with  JFrame (I'm thinking) from enother java program

    Hi,
    I'm using jasperReport and running viewReport from my java application.
    JasperPrint jasperPrint = JasperFillManager.fillReport(
                             jasperReport, parameters, conn);
                   JasperViewer.viewReport(jasperPrint, true);
    My problem is when I'm closing the view report, my java aplication closing twe!
    I think it's because the view frame sel exit(0)?
    and one more question, if I run this viewReport from JButton in a JDIalog, the view location is under my dialog, how can I set this view to be allways on top??
    Thanks alot :)

    The following code is running without problems (SQLSERVER),and you can compared with yours.
    public static Connection con;
         public  Statement sta;
         public ResultSet rst;
         public CallableStatement  cas = null;
         public int OutPut;
    public void doProcedures(String str,Vector vec){
                   try {
         String s=null;
                        con=null;
                        rst=null;
                        Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
                                            con = DriverManager.getConnection(getConnectionString(), "sa","");               
                                         s=str;
                        s="{call"+" "+s+"(?,?,?)}";
                    cas=con.prepareCall(s);
                       cas.registerOutParameter(1, java.sql.Types.INTEGER ); 
                       for(int i =0;i<vec.size();i++){                   
                      cas.setInt(i+2,Integer.parseInt ((String)vec.elementAt(i)));  
                       cas.execute() ;
                       OutPut =cas.getInt(1);
                       rst = cas.executeQuery();
                      // while(rst.next()){
                           // String output=rst.getString(1);
                       //rst.close() ;
                   } catch (Exception e) {
                        e.printStackTrace();
    Good Luck,baby!!!

  • Problem with JFrame

    I can't get rid of the previous frame I have used, when I create a new frame with added data the previous frame overlaps with the new frame and it all gets a bit messy !

    My fault I think I worded it wrong.
    basically I have a JFrame with many components in it, when a client clicks on one of the Jlists items and presses select I get the item from the Jlist and pass it to a private variable. now what I want to do is scrap this JFrame and produce an identical one but with the JList next to the previous one filled in with the data which is dependant on the choice just made !
    i am sure i am doing something wrong ! maybe JPanels not JFrames?

Maybe you are looking for

  • Difference between null layout and absolutelayout

    hello I would like to know the difference between the null layout and the absolutelayout thank you in advance

  • HD video movies with DVI cable

    Would it work to visualize an ITunes HD movie on a TV screen with a MacBook (end 2008) using a mini-display to DVI cable ? Thanks

  • How to develop a simple HMI in LabView

    Hello, I need to develop a very simple HMI for TestStand. This HMI must only show some IDs of the DUT and the Name and Result of the step actually running. The language I know best is LabView, so I would like to write this HMI in this language. I loo

  • CQ41-207UA upgrade im a newbie

    Hi To All, I just bought my CQ41-207UA with a 250GB drive, I was wondering if it is possible for me to upgrade and place a 500GB Sata drive? Thank you very much

  • Syncing photos from Lumia 920 to Lumia 1020- Quest...

    I just received my Lumia 1020- I started up the Windows Phone desktop application, and wanted to transfer all the photos I had stored on the 920 to my new 1020; so I selected the photos I wanted to sync. I got a message- "You are deleting a large num