[NetBeans][JFrame] - JFrame Button

HI !
Im trying to make the application that is base on the multiple windows(JFrames ). When im opening window and somebody gonna enter wrong information i would likt to make a warning window with one button for example 'OK'. i puting action for the button
this.dispose(); but when im doing like that,when im pressing button the warning windows is being closed and that is ok and my additional window is being cloesed to. Can i use another function just to close this one window/?
Krystian,

Check out the JOptionPane functions.
Also, if your main application frame is "this," this.dispose() will destroy your application (or at the very least, the GUI portion of it). Try getting whatever child pane is causing the problem and destroying that.
For example:
ParentFrame.getChildFrame().dispose();Joe H

Similar Messages

  • DrawImage on NetBeans-created jFrame

    Hi, I've built the basics of a GUI with swing in Netbeans 6.1. I'd like to draw an image onto an existing jFrame, but I'm having some difficulty. I have a simple class to draw part of the image:
    public class LoadImageApp extends Component {
        public BufferedImage img;
        public LoadImageApp() {
           try {
               img = ImageIO.read(new File("D:/image.jpg"));
           } catch (IOException e) {System.out.println("Nothing");}
        @Override
        public void paint(Graphics g) {
            g.drawImage(img, 0, 0, 100, 100, 0, 0, 100, 100, null);
        @Override
        public Dimension getPreferredSize() {
            if (img == null) {
                return new Dimension(100,100);
            } else {
                return new Dimension(200,200);
    }Then I am attempting to draw/display the image when a button is clicked:
    private void loadImageActionPerformed(java.awt.event.ActionEvent evt) {
        final JFrame f = new JFrame("Load Image Sample");
        f.addWindowListener(new WindowAdapter(){
            @Override
            public void windowClosing(WindowEvent e) {
                f.setVisible(false);
        f.add(new LoadImageApp());
        f.pack();
        f.setVisible(true);
        jFrame1.add(new LoadImageApp());
        jFrame1.pack();
        jFrame1.setVisible(true);
    }For frame "f" - everything works as expected. Frame is displayed, image is drawn, and window is sized properly.
    For frame "jFrame1" (created with swing/netbeans) - Frame is displayed, but image is not drawn and window is not sized properly.
    Why is this?
    I have read something about overriding update for the frame, but I don't know how to do this for the netbeans code, or if it is even the correct thing to do here. So any help is greatly appreciated!
    Edited by: gtg811a on Aug 5, 2008 11:10 PM

    I appreciate the initial effort.
    Rodney_McKay wrote:
    You have 2 options:
    *1*. Don't use NetBeans.
    *2*. Post your question in a NetBeans forum.Believe it or not, this was not helpful. Actually, you might even say it was pompous. Not everyone has been doing this for a long time, so no, you didn't give me the information to answer my question (well maybe in the sense that directing me to www.google.com would be the information to answer it). Seems to me that in a Java graphics forum there might be one or two people who use NetBeans for GUI building. And by posting some snide remark rather than helpful information, you basically cut the thread off from useful input. I'll read the rules for posting to a forum if you'll be just a little less jaded about answering questions.

  • Resizing JFrame on button click to show an image on the JFrame

    Dear All,
    I have a JFrame which has an empty label. On button click I want to set an icon for the label and want the JFrame to be resized to show that icon. I am using frame.pack() and I am not using any other sizing function. The code that I have right now, prints the image on the panel, but does not resize the frame to show the image. Pleae could someone help.package gui;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ItemEvent;
    import java.awt.event.ItemListener;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    public class ComponentDemo extends JPanel implements ActionListener,
    ItemListener, MouseListener, KeyListener {
         private JTextArea textarea;
         private JButton button;
         private final static String newline = "\n";
         private JLabel imageIcon;
         public ComponentDemo() {
              button = new JButton("JButton welcomes you  to CO2001");
              button.addActionListener(this);
              add(button);
              textarea = new JTextArea(10, 50);
              textarea.setEditable(false);
              addMouseListener(this);
              textarea.addKeyListener(this);
              JScrollPane scrollPane = new JScrollPane(textarea);
              add(scrollPane);
              imageIcon = new JLabel();
              add(imageIcon);
              setBackground(Color.pink);
              new JScrollPane(this);
          * Create the GUI and show it. For thread safety, this method should be
          * invoked from the event-dispatching thread.
         private static void createAndShowGUI() {
              // Create and set up the window.
              JFrame frame = new JFrame("Simple FrameDemo");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
              frame.setLocation(700, 200);
              // get the content pane and set the background colour;
              frame.add(new ComponentDemo());
         //     frame.setSize(screenSize);
              // frame.getContentPane().setBackground(Color.cyan);
              // Display the window.
              frame.pack();
              frame.setVisible(true);
              frame.setResizable(true);
         public static void main(String[] args) {
              // Schedule a job for the event-dispatching thread:
              // creating and showing this application's GUI.
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        createAndShowGUI();
         @Override
         public void actionPerformed(ActionEvent e) {
              // TODO Auto-generated method stub
              if (e.getSource() instanceof JButton) {
                   // System.out.println(e.getSource());
                   String text = ((JButton) e.getSource()).getText();
                   textarea.append(text + newline);
                   textarea.setBackground(Color.cyan);
                   textarea.setForeground(Color.BLUE);
                   textarea.setCaretPosition(textarea.getDocument().getLength());
                   imageIcon.setIcon(createImageIcon("SwingingDuke.png",
                   "Image to be displayed"));
         @Override
         public void itemStateChanged(ItemEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void mouseClicked(MouseEvent arg0) {
              textarea.append("A Mouse click welcomes you to CO2001" + newline);
              textarea.setBackground(Color.green);
              textarea.setCaretPosition(textarea.getDocument().getLength());
         @Override
         public void mouseEntered(MouseEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void mouseExited(MouseEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void mousePressed(MouseEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void mouseReleased(MouseEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void keyPressed(KeyEvent e) {
              System.out.println(e.getKeyChar());
              textarea.append("The key " + e.getKeyChar()
                        + " click welcomes you to CO2001" + newline);
              textarea.setBackground(Color.YELLOW);
              textarea.setFont(new Font("Arial", Font.ITALIC, 16));
              textarea.setCaretPosition(textarea.getDocument().getLength());
         @Override
         public void keyReleased(KeyEvent e) {
              System.out.println(e.getKeyChar());
              // textarea.append("The key "+
              // e.getKeyChar()+" click welcomes you to CO2001" + newline);
              // textarea.setBackground(Color.green);
              // textarea.setCaretPosition(textarea.getDocument().getLength());
         @Override
         public void keyTyped(KeyEvent e) {
              // TODO Auto-generated method stub
              System.out.println(e.getKeyChar());
              // textarea.append("The key "+
              // e.getKeyChar()+" click welcomes you to CO2001" + newline);
              // textarea.setBackground(Color.blue);
              // textarea.setCaretPosition(textarea.getDocument().getLength());
         /** Returns an ImageIcon, or null if the path was invalid. */
         protected ImageIcon createImageIcon(String path, String description) {
              java.net.URL imgURL = getClass().getResource(path);
              if (imgURL != null) {
                   System.out.println("found");
                   return new ImageIcon(imgURL, description);
              } else {
                   System.err.println("Couldn't find file: " + path);
                   return null;
    }

    myJPanel.setPerferredSize(new Dimension(new_width, new_hight));
    myJFrame.pack();

  • Closing a Jframe on button click

    Dear all,
    Please help me !!!
    I am having a jframe inside which I am having a jbutton. I want to close the jframe on that jbutton click.
    rock

    import javax.swing.JFrame;
    import javax.swing.JButton;
    import javax.swing.JTextField;
    public class Check extends JFrame {
         private javax.swing.JPanel jContentPane = null;
         private JButton jButton = null;
         private JTextField jTextField = null;
         private JButton getJButton() {
              if (jButton == null) {
                   jButton = new JButton();
                   jButton.addActionListener(new java.awt.event.ActionListener() {
                   public void actionPerformed(java.awt.event.ActionEvent e) {                                                          Check pop = new Check();
                               pop.dispose();  // here I want this frame should be close on clicking this button
              return jButton;
         private JTextField getJTextField() {
              if (jTextField == null) {
                   jTextField = new JTextField();
              return jTextField;
           public static void main(String[] args) {
              Check c = new Check();
         public Check() {
              super();
              initialize();
         private void initialize() {
              this.setSize(300,200);
              this.setContentPane(getJContentPane());
              this.setTitle("JFrame");
              this.setVisible(true);
         private javax.swing.JPanel getJContentPane() {
              if(jContentPane == null) {
                   jContentPane = new javax.swing.JPanel();
                   jContentPane.setLayout(new java.awt.BorderLayout());
                   jContentPane.add(getJButton(), java.awt.BorderLayout.EAST);
                   jContentPane.add(getJTextField(), java.awt.BorderLayout.NORTH);
              return jContentPane;
    }THis is my code I use dispose but it is not working

  • How to setExtendedState for NetBeans IDE JFrame

    Hello.
    I seem to have a problem with using the visual editor to set extended state for my jframe in NetBeans IDE.
    I would like to make max out the screen, is there a way or a work around in this case?
    Thank you very much.

    I would like to make max out the screen, is there a
    way or a work around in this case?Did you mean maximizing the JFrame ? Then this will help
    setExtendedState(JFrame.MAXIMIZED_BOTH);Good luck! Happy New Year

  • Close JFrame in Netbeans

    Hello,
    I have a java application in NetBeans. I have been using Netbean absolut layout. I didn´t create JFrame class variable at all, instead using:Ok is a button
    ok.setFont(new java.awt.Font("Arial", 0, 10));
    ok.setToolTipText("ok");
    ok.setLabel("ok");
    ok.setMargin(new java.awt.Insets(2, 2, 2, 2));
    getContentPane().add(ok, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 150, 60, 20));
    ok.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    okPerformed(evt);
    I don´t want to use System.exit(0); because it will shut down whole system. In order to use dispose method, I created a JFrame class variable in beginning of the class, but it doesn´t work.
    JFrame frame = new JFrame();
    public void okPerformed (java.awt.event.ActionEvent evt){
    this.frame.dispose();
    Can anyone help me?
    Thanks

    hello,
    Thanks for replying my message so fast.
    I tried, but it still doesn´t work. I am using netbeans absolute Layout. It doesn´t really have frame. Here is my code
    public class tt extends JFrame{
    JFrame frame = new JFrame();
    JTextField text1= new JTextField(20);
    JButton ok = new JButton();
    public tt throws Exception
    setSize(400,300);
    setTitle("tt");
    getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
    text1.setFont(new java.awt.Font("Arial",0,12));
    text1.setBounds(5, 8, 5, 5);
    text1.setEditable(true);
    getContentPane().add(text1, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 30, 100, 20));
    ok.setFont(new java.awt.Font("Arial", 0, 10));
    ok.setToolTipText("ok");
    ok.setLabel("ok");
    ok.setMargin(new java.awt.Insets(2, 2, 2, 2));
    getContentPane().add(ok, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 150, 60, 20));
    ok.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    okPerformed(evt);
    setVisible(true);
    public void okPerformed (java.awt.event.ActionEvent evt){
    setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
    Thanks

  • How  add buttons to Jframe from other class

    Hi, a have a little problem;)
    I want make a JFrame, but i want to add JButtons from other class. Now I have something like that:
    My JFrame class:
    package windoow;
    import javax.swing.*;
    import java.awt.*;
    public class MyWindow extends JFrame {
           Butt buttons ;
            public Window(String s) {
                     super(s);
                    this.setSize(600, 600);
                    this.setVisible(true);
                    Buttons();
                public void Buttons(){
                    setLayout(null);            
                   buttons = new Butt();
                   buttons.mywindow =this;
    } My class with buttons:
    package windoow;
    import javax.swing.JButton;
    public class Butt {
            MyWindow mywindow;
            JButton b1;
            Butt(){
                      b1 = new JButton("Button");
                      b1.setBounds(100,100,100,20);
                      mywindow.add(b1);  
    } and i have NullPointerException.
    When i try to make new MyWindow in Butt clas i have something like StackOverFlow.
    what should i do?

    Your null pointer exception is occuring because, in your Butt() constructor, you are calling mywindow.add(b1), but you don't set mywindow until after you call the constructor in the MyWindow::Buttons() method.
    And, if you try to create a new MyWindow() in your Butt() constructor, and, assuming that you are calling the MyWindow::Window(String s) method from the MyWindow() constructor (which is not clear from the code fragment you posted), then Butt() calls new MyWindow() which calls Window(String s) which calls Butt() which calls ... and so on, until the stack overflows.
    One possible solution ... pass your MyWindow reference into your Butt() constructor as this, as so:
    public void Buttons()
       // stuff deleted
      buttons = new Butt( this );
       // stuff deleted
    // AND
    Butt( MyWindow mw )
       // stuff deleted
      mywindow = mw;
      mywindow.add( b1 ); // b1 created in stuff deleted section  
    }Also, I would call setVisible(true) as the last thing I did during the construction of the frame. This realizes the frame, and from that point forward, most changes to the frame should be made on the event thread.
    ¦ {Þ                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

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

  • Mouse Drag in JDialog produces Mouse Enter & Mouse Exit events in JFrame.

    Hi, all.
    Do I have a misconception here? When I drag the mouse in a modal JDialog, mouseEntered and mouseExited events are being delivered to JComponents in the parent JFrame that currently happens to be beneath that JDialog. I would not have expected any events to be delivered to any component not in the modal JDialog while that JDialog is displayed.
    I submitted this as a bug many months ago, and have heard nothing back from Sun, nor can I find anything similar to this in BugTraq.
    Here is sample code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    * This class demonstrates what I believe are TWO bugs in Mouse Event handling in Swing
    * 1.1.3_1, 1.1.3_2, 1.1.3_3, and 1.4.0.
    * 1) When a MODAL JDialog is being displayed, and the cursor is DRAGGED from the JDialog
    *    into and across the parent JFrame, Mouse Enter and Mouse Exit events are given to
    *    the parent JFrame and/or it's child components.  It is my belief that NO such events
    *    should be delivered, that modal dialogs should prevent ANY user interaction with any
    *    component NOT in the JDialog.  Am I crazy?
    *    You can reproduce this simply by running the main() method, then dragging the cursor
    *    from the JDialog into and across the JFrame.
    * 2) When a MODAL JDialog is being displayed, and the cursor is DRAGGED across the JDialog,
    *    Mouse Enter and Mouse Exit events are given to the parent JFrame and/or it's child
    *    components.  This is in addition to the problem described above.
    *    You can reproduce this by dismissing the initial JDialog displayed when the main()
    *    method starts up, clicking on the "Perform Action" button in the JFrame, then dragging
    *    the cursor around the displayed JDialog.
    * The Mouse Enter and Mouse Exit events are reported via System.err.
    public class DragTest
        extends JFrame
        public static void main(final String[] p_args)
            new DragTest();
        public DragTest()
            super("JFrame");
            WindowListener l_windowListener = new WindowAdapter() {
                public void windowClosing(final WindowEvent p_evt)
                    DragTest.this.dispose();
                public void windowClosed(final WindowEvent p_evt)
                    System.exit(0);
            MouseListener l_mouseListener = new MouseAdapter() {
                public void mouseEntered(final MouseEvent p_evt)
                    System.err.println(">>> Mouse Entered: " + ((Component)p_evt.getSource()).getName() );
                public void mouseExited(final MouseEvent p_evt)
                    System.err.println(">>> Mouse Exited: " + ((Component)p_evt.getSource()).getName() );
            JPanel l_panel1 = new JPanel();
            l_panel1.setLayout( new BorderLayout(50,50) );
            l_panel1.setName("JFrame Panel");
            l_panel1.addMouseListener(l_mouseListener);
            JButton l_button = null;
            l_button = new JButton("JFrame North Button");
            l_button.setName(l_button.getText());
            l_button.addMouseListener(l_mouseListener);
            l_panel1.add(l_button, BorderLayout.NORTH);
            l_button = new JButton("JFrame South Button");
            l_button.setName(l_button.getText());
            l_button.addMouseListener(l_mouseListener);
            l_panel1.add(l_button, BorderLayout.SOUTH);
            l_button = new JButton("JFrame East Button");
            l_button.setName(l_button.getText());
            l_button.addMouseListener(l_mouseListener);
            l_panel1.add(l_button, BorderLayout.EAST);
            l_button = new JButton("JFrame West Button");
            l_button.setName(l_button.getText());
            l_button.addMouseListener(l_mouseListener);
            l_panel1.add(l_button, BorderLayout.WEST);
            l_button = new JButton("JFrame Center Button");
            l_button.setName(l_button.getText());
            l_button.addMouseListener(l_mouseListener);
            l_panel1.add(l_button, BorderLayout.CENTER);
            JButton l_actionButton = l_button;
            Container l_contentPane = this.getContentPane();
            l_contentPane.setLayout( new BorderLayout() );
            l_contentPane.add(l_panel1, BorderLayout.NORTH);
            JPanel l_panel2 = new JPanel();
            l_panel2.setName("JDialog Panel");
            l_panel2.addMouseListener(l_mouseListener);
            l_panel2.setLayout( new BorderLayout(50,50) );
            l_panel2.add( new JButton("JDialog North Button"),  BorderLayout.NORTH  );
            l_panel2.add( new JButton("JDialog South Button"),  BorderLayout.SOUTH  );
            l_panel2.add( new JButton("JDialog East Button"),   BorderLayout.EAST   );
            l_panel2.add( new JButton("JDialog West Button"),   BorderLayout.WEST   );
            l_panel2.add( new JButton("JDialog Center Button"), BorderLayout.CENTER );
            final JDialog l_dialog = new JDialog(this, "JDialog", true);
            WindowListener l_windowListener2 = new WindowAdapter() {
                public void windowClosing(WindowEvent p_evt)
                    l_dialog.dispose();
            l_dialog.addWindowListener(l_windowListener2);
            l_dialog.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
            l_dialog.getContentPane().add(l_panel2, BorderLayout.CENTER);
            l_dialog.pack();
            Action l_action = new AbstractAction() {
                { putValue(Action.NAME, "Perform Action (open dialog)"); }
                public void actionPerformed(final ActionEvent p_evt)
                    l_dialog.setVisible(true);
            l_actionButton.setAction(l_action);
            this.addWindowListener(l_windowListener);
            this.pack();
            this.setLocation(100,100);
            this.setVisible(true);
            l_dialog.setVisible(true);
    }(Too bad blank lines are stripped, eh?)
    Thanks in advance for any insights you may be able to provide.
    ---Mark

    I guess we can think of this as one problem. When mouse dragged, JFrame also (Parent) receives events. If i understood correctly, what happens here is, Modal dialog creates its own event pump and Frame will be having its own. See the source code of Dialog's show() method. It uses an interface called Conditional to determine whether to block the events or yield it to parent pump.
    Here is the Conditional code and show method code from java.awt.dialog for reference
    package java.awt;
    * Conditional is used by the EventDispatchThread's message pumps to
    * determine if a given pump should continue to run, or should instead exit
    * and yield control to the parent pump.
    * @version 1.3 02/02/00
    * @author David Mendenhall
    interface Conditional {
        boolean evaluate();
    /////show method
        public void show() {
            if (!isModal()) {
                conditionalShow();
            } else {
                // Set this variable before calling conditionalShow(). That
                // way, if the Dialog is hidden right after being shown, we
                // won't mistakenly block this thread.
                keepBlocking = true;
                if (conditionalShow()) {
                    // We have two mechanisms for blocking: 1. If we're on the
                    // EventDispatchThread, start a new event pump. 2. If we're
                    // on any other thread, call wait() on the treelock.
                    if (Toolkit.getEventQueue().isDispatchThread()) {
                        EventDispatchThread dispatchThread =
                            (EventDispatchThread)Thread.currentThread();
                           * pump events, filter out input events for
                           * component not belong to our modal dialog.
                           * we already disabled other components in native code
                           * but because the event is posted from a different
                           * thread so it's possible that there are some events
                           * for other component already posted in the queue
                           * before we decide do modal show. 
                        dispatchThread.pumpEventsForHierarchy(new Conditional() {
                            public boolean evaluate() {
                                return keepBlocking && windowClosingException == null;
                        }, this);
                    } else {
                        synchronized (getTreeLock()) {
                            while (keepBlocking && windowClosingException == null) {
                                try {
                                    getTreeLock().wait();
                                } catch (InterruptedException e) {
                                    break;
                    if (windowClosingException != null) {
                        windowClosingException.fillInStackTrace();
                        throw windowClosingException;
        }I didn't get exactly what is happening but this may help to think further

  • How to set focus on opened new JFrame??

    Hi,
    I have a problem:
    I have my active JFrame that I am currently running.
    When I press a JButton I have an action that it opens another JFrame,
    which is minimized (maybe it doesn't have a focus enabled or something)
    How to make the opening JFrame window maximized and make it be the one on the foreground (put the first JRame in background)
    Thanks

    Try this:
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    public class JFrames extends JFrame{
         public JFrames(){
              super();
              // exit on close
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              // button to create new JFrame
              JButton button = new JButton("New Frame");
              button.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent e){
                        // create new instance and maximize it
                        JFrames frame = new JFrames();
                        frame.setExtendedState(frame2.getExtendedState()|frame2.MAXIMIZED_BOTH);
              // panel to add the button to
              JPanel panel = new JPanel();
              panel.setPreferredSize(new Dimension(300, 200));
              panel.add(button);
              this.getContentPane().add(panel);
    // display the frame
    this.pack();
    this.setVisible(true);
         public static void main(String args[]){
              JFrames frames = new JFrames();
    }

  • Automatic placement of components on to the JFrame.

    Hello I want to know if it is possible to have a button in my program and when this button is pressed by the user it automatically places about 3 JFormattedtextfields on to the JFrame? If so how do I go about writing code for this?

    Well I am trying to have a check box so that only selected components are deleted. At the moment I am trying to item listener to the check box. I had a look at the checkbox demo and I did the exact same thing but mine does'nt seem to work I don't want to proceed with the remove clients method before this is sorted out. Can someone please point out my mistake to me and suggest ways to correct it.
    import net.miginfocom.swing.MigLayout;
    import javax.swing.*;*
    *import java.awt.event.*;
    public class LayOut {
    //Labels to identify the fields
    JLabel currentLabel = new JLabel("Current");
    JLabel systemVoltageLabel = new JLabel ("Voltage");
    JLabel kVALabel = new JLabel ("KVA");
    //The button
    JButton addClients = new JButton("Add Clients");
    JButton removeClients = new JButton("Remove Clients");
    // the panel
    JPanel mainPanel = new JPanel();
    // the JFrame
    JFrame frame = new JFrame("Runtime test software");
    public LayOut() {
    mainPanel.setLayout(new MigLayout());
    mainPanel.add(addClients, "wrap");
    addClients.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    addClients();
    removeClients.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    removeClients();
    frame.add(mainPanel);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(500,500);
    frame.setVisible(true);
    public void addClients() {
    mainPanel.add(new JCheckBox());
    mainPanel.add(new JFormattedTextField(),"width 20:80");
    mainPanel.add(new JFormattedTextField(),"gapleft 30, width 20:80");
    mainPanel.add(new JFormattedTextField(),"gapleft 30, width 20:80, wrap");
    mainPanel.revalidate();
    mainPanel.validate();
    public void removeClients() {
    JCheckBox.addItemListener(this); // this is how it is done in the check box tutorial
    mainPanel.revalidate();
    mainPanel.validate();
    public static void main(String[] args) {
    LayOut l;
    l = new LayOut();
    }

  • Make 2 JFrames work one after the other

    Hello,
    I have JFrame with a button and after a clicking on that it opens a new JFrame which takes inputs from user and saves them in a file;Until I finish the file writing in second frame, the user should not be able to edit anything in first frame,frame should be visible.The code for creating the frames is:
    import javax.swing.JFrame;
    import javax.swing.JButton;
    public class FrameTest extends JFrame{
         private JButton button=new JButton("Click");
         public FrameTest() {
              button.addActionListener(new java.awt.event.ActionListener(){
                   public void actionPerformed(java.awt.event.ActionEvent ae){
                   new ChildFrame();     
              getContentPane().add(button);
              pack();
              setVisible(true);
         public static void main(String args[]){
              new FrameTest();
    import java.awt.Event;
    import javax.swing.JFrame;
    import javax.swing.JButton;
    import javax.swing.JTextField;
    public class ChildFrame extends JFrame {
         JButton button=new JButton("Save");
         JTextField name=new JTextField(10);
         java.io.FileOutputStream fout;
         public ChildFrame() {
              button.addActionListener(new java.awt.event.ActionListener(){
                   public void actionPerformed(java.awt.event.ActionEvent ae){
                        try{
                             fout=new java.io.FileOutputStream("c:/TestFile.txt");
                             fout.write(name.getText().getBytes());
                             fout.close();
                        catch(java.io.FileNotFoundException fnf){
                        catch(java.io.IOException ioe){
              getContentPane().setLayout(new java.awt.FlowLayout());
              getContentPane().add(name);
              getContentPane().add(button);
              pack();
              setVisible(true);
    }

    You can add a boolean variable (initialized to false) to the child frame that holds true once the file operation is complete. Let's say we call it: FileTransferComplete=false;
    fout=new java.io.FileOutputStream("c:/TestFile.txt");
    fout.write(name.getText().getBytes());
    fout.close();
    FileTransferComplete=true;
    /code]
    you can add a method to the child frame to return this status
    and set the main frame's setVisible property to this value likethis.setVisible(ChildFrame.isFileTransferComplete());
    You'll probably have to cater for the likely scenario that a IO exception is called in which case FileTransferComplete never becomes true.

  • JFrame displays without its components or settings (please help)

    On clicking a button in an app, due to computational time required, I need to have a message popup that says 'Please Wait', which vanishes on end of needed computation. For this, I have a small working class MsgDiag that simply displays a non-modal titled JFrame showing a message string in a JLabel and an 'ok' in a JButton. This works fine when invoked directly via its own main method as a standalone, but when called from that other application(also a extended JFrame) via button click, it just brings up a blank grey untitled JFrame without the components (JLabel and JButton) or the background color! It does stay up for the required duration and vanishes on disposing its JFrame as expected but why blank w/o components or settings ?
    I also find that though the JFrame component comes up blank grey, if during the computation portion in calling application, if any info/errors are popped up via direct call to a JOptionPane().showMessageDialog(JFrame(),msgString, titleString, msgType), then along with that modal popup (from JOptionPane), the grey JFrame gets correctly drawn with components and background !
    Does this provide any hints ? Since MsgDiag works ok by itself I am puzzled.
    I also tried putting basic code from MsgDiag (creating JFrame, adding its components, setting it visible etc) into the other app directly but same grey blank frame results. Had there been a non-modal JOptionPane I could have tried using it. I use JRE 1.4.2

    Per your suggestion, I tried putting computational part in a different thread. Also tried putting the thread priority for computational thread to lowest.
    In other approach, also tried putting the GUI popup (frame2) in a separate thread with highest priority while lowest priority computational thread executed. But neither approach worked. Still shows frame2 as blank w/o background or components inside while low priority computational thread finished, when frame2 gets disposed as instructed.
    In 1st approach, also tried adding validate() following setSize() as some other posts have suggested but that did not change anything. Any other pointers ?

  • Flashing JFrame

    Hi,
    I would like to create a JFrame with two specifal features:
    1. JFrame should not grab focus while maximized from minimized state.
    2. When a JFrame created or became maximized from minimized state, it should flash in the Windows bar until a user will grant a focus to it. (like as in ICQ clients [url http://i.imgur.com/dKwJV.jpg]flashing example ).
    Does anybody know how the second requirement can be implemented?
    Little self-explained example:
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    public class JFrameTest {
        private static JFrame childFrame;
        public static Container getParentContentPane() {
            JPanel panel = new JPanel();
            JButton button = new JButton("Create\\Restore child frame");
            button.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e) {
                    createOrRestoreChildFrame();
            panel.add(button);
            return panel;
        private static void createOrRestoreChildFrame() {
            if (childFrame == null) {
                childFrame = new JFrame("Child Frame");
                childFrame.setLocation(200, 200);
                childFrame.add(new JLabel("Child Frame"));
                childFrame.pack();
                setChildFrameVisible();
            } else {
                setChildFrameVisible();
        private static void setChildFrameVisible() {
            childFrame.setFocusableWindowState(false);
            childFrame.setVisible(true);
            flashInWindowsBar(childFrame);
            childFrame.toFront();
            childFrame.setFocusableWindowState(true);
         * Should Make child frame flash in Windows bar.
         * Currently, it does not work for me.
         * Could anybody help me to fix this please? )
        private static void flashInWindowsBar(JFrame childFrame) {
            childFrame.setState(JFrame.ICONIFIED);
            childFrame.toFront();
        private static void createAndShowGUI() {
            JFrame parentFrame = new JFrame("JFrame Demo");
            parentFrame.setLocation(100, 100);
            parentFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            parentFrame.setContentPane(getParentContentPane());
            parentFrame.pack();
            parentFrame.setVisible(true);
        public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }Thanks!
    Edited by: user1106343 on Nov 30, 2010 2:10 AM
    Edited by: user1106343 on Nov 30, 2010 2:11 AM

    In the future, you should at least alert users that you've cross-posted (which is frowned upon):
    http://stackoverflow.com/questions/4305837/flashing-jframe
    http://www.coderanch.com/t/518839/GUI/java/Flashing-JFrame

  • Substance 6.0 and JFrame

    I've been playing around with the new Substance release. When I apply it in code, everything takes on the skin as it's supposed to except the JFrame. Buttons, checkboxes, etc work fine, even JInternalFrames, but the Main JFrame itself still looks like any other window. From the examples about Substance given, even the main window is supposed to take on the skin. Is there something else besides the UIManager call that needs to be done, or will this always happen without making the JFrame undecorated and have to make your own title bar and control buttons? Tried looking at sample code to see how its done, but only .class files were given so I can't check out what's happening in the test program.

    efecher wrote:
    Tried looking at sample code to see how its done, but only .class files were given so I can't check out what's happening in the test program.Full source code for both the library itself and the test program is available in the SVN repository and the substance-all.zip file in the Downloads section.
    Thanks
    Kirill (Substance developer)

Maybe you are looking for

  • Can execut a query in Oracle UCM to get View_Values instead of using GET_SC

    Dear All, i have a question that i had google it and didn't find anything helpful. i want to ask if i can execut a query in Oracle UCM to get View_Values instead of using GET_SCHEMA_VIEW_VLAUES service ? ie: asuume that we have a Table name called Em

  • Ipod touch screen randomly quitting.

    I just bought a new iPod Touch 5th Generation less than 2 weeks ago. About a week ago a problem arose. Now, sometimes the screen will randomly stop working and do things that I don't want it to do(e.g. open apps). It will also do things when I am not

  • BPC cannot connect to ABAP server

    Hello Experts, I'm facing the following issue when installing SAP BPC NW 7.5 SP04 When the installation is done (succesfully) I try to login to the server manager and get following error message: "Cannot connect to ABAP server; Check your ABAP server

  • Photos not properly downloading, prevents editing

    With the new Yosemite OS X update, I have been trying to edit my photos that were in iPhoto and now in Photos but when I click on Edit it says "Error Downloading Photo" An error occurred while downloading a larger version of this photo for editing. P

  • Tabs have to be clicked twice to load page

    I have FF 26. Windows 7 I have some saved bookmarks on the toolbar. When I click one to open that page up, it does nothing. I have to click it again in order for that page to load up. It usually does this for bookmarks on the toolbar and I'm not sure