Focus In Jframe

I am trying to have a key listener inside a Jframe which will work no matter where the focus is, currently it only works when the focus is at certain locations. How can I do this, here is where I create the frame and components and attempt to get the keylistener to work....
import java.awt.*;
import javax.swing.*;
//import cs1.*;
//import java.io.*;
import java.awt.event.*;
//import java.applet.*;
class Driver extends JPanel implements ActionListener, KeyListener
     static String title = "Number Munchers";     //Game title
     Board board;                                        //Game board
     public JFrame frame;                              //Game frame
     protected JButton b1,b2,b3,b4,b5;
     Score s1=new Score();
     Monster monster1;
     public void createAndShowGUI()
          frame = new JFrame("Number Munchers");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.addKeyListener(this);
          board = new Board(this);
          JMenuBar menuBar = new JMenuBar();
          JMenu fileMenu = new JMenu("File");
          JMenu optionMenu =new JMenu("Options");
          JMenuItem start = new JMenuItem("New Game");
          JMenuItem end = new JMenuItem("End Game");
          JMenuItem sound = new JMenuItem("Sound On");
          JMenuItem mute = new JMenuItem("Mute");
          start.addActionListener(this);
          start.setActionCommand("New Game");
          end.addActionListener(this);
          end.setActionCommand("Exit");
          sound.addActionListener(this);
          sound.setActionCommand("Sound");
          mute.addActionListener(this);
          mute.setActionCommand("Mute");
          menuBar.add(fileMenu);
          menuBar.add(optionMenu);
          fileMenu.add(start);
          fileMenu.add(end);
          optionMenu.add(sound);
          optionMenu.add(mute);
          frame.setJMenuBar(menuBar);
          //Add Number Muncher game board to frame
          frame.getContentPane().add(board,BorderLayout.CENTER);
          //Add score to frame
          frame.getContentPane().add(s1.scoreLabel, BorderLayout.NORTH);
          //frame.getContentPane().add(l1.livesLabel, BorderLayout.EAST);
          //Add info to frame
          frame.getContentPane().add(board.getGameLabel(), BorderLayout.EAST);
          frame.getContentPane().add(board.getScoreLabel(), BorderLayout.NORTH);
          frame.getContentPane().add(board.getLivesLabel(), BorderLayout.SOUTH);
          frame.setSize(550,550);
          frame.setVisible(true);
          monster1 = new Monster(0,0,this,board,board.muncher);
     public static void main (String args[])
          final Driver driver = new Driver();
          javax.swing.SwingUtilities.invokeLater(new Runnable()
               public void run()
                    driver.createAndShowGUI();
     }//End main method
     public void keyPressed(KeyEvent e)
          System.out.println("Key pressed");
          if(e.getKeyCode()==KeyEvent.VK_LEFT)
               System.out.print("LEFT ");
               board.move(-1,0);
               System.out.println(board.muncher.returnY() + " " + board.muncher.returnX());
          if(e.getKeyCode()==KeyEvent.VK_RIGHT)
               System.out.print("RIGHT ");
               board.move(1,0);
               System.out.println(board.muncher.returnY() + " " + board.muncher.returnX());
          if(e.getKeyCode()==KeyEvent.VK_UP)
               System.out.print("UP ");
               board.move(0,1);
          if(e.getKeyCode()==KeyEvent.VK_DOWN)
               System.out.print("DOWN ");
               board.move(0,-1);
               System.out.println(board.muncher.returnY() + " " + board.muncher.returnX());
     public void keyTyped(KeyEvent e)
     public void keyReleased(KeyEvent e)
          if(e.getKeyCode()==KeyEvent.VK_CONTROL)
               System.out.println("MUNCH");
               board.munch();               
          if(e.getKeyCode()==KeyEvent.VK_ENTER)
               System.out.println("REFRESH BOARD");
               board.refresh();
     public void actionPerformed(ActionEvent e)
          //Menu Bar
          if(e.getActionCommand().equals("New Game"))
               System.out.println("New Game");
               board.clear();
               s1.refreshScore();
          if(e.getActionCommand().equals("Exit"))
               JOptionPane.showMessageDialog(frame,"Are you sure you want to exit?");
               System.exit(0);
          if(e.getActionCommand().equals("Sound"))
               System.out.println("Sound On");
          if(e.getActionCommand().equals("Mute"))
               System.out.println("Mute");
} //end Driver class
If you can help thanks a lot, this is a problem I have spent a long time attempting to fix.
Geoff Gross

chack this URL http://developer.java.sun.com/developer/bugParade/bugs/4647551.html
I reported it as a bug 3 years ago and still did not find a solution to this problem, but sun still convince that making us a hard life and getting to no where is still not their bug.
If you want to help me with this fight please send them also an email and report it as a bug.
Amnonm

Similar Messages

  • Need to keep the focus on JFrame

    hi everybody, i need your help.
    in my program i have a JInternalFrame and i have a JButton "open" it open an image browser that i made, but the problem that i made the browser in JFrame, and i have problem to keep the focus on it , cause the user must not do anything before he click on ok or cancel...
    i try to make the browser on a JOPtionPane, but the size of JOptionPane is so small and i lost a part of my components.
    thanks for ur help.

    Just change browser class to extend JDialog and set the jDialog to modal.

  • Child JWindow containing JTextField takes focus from JFrame

    I have a bit of a unique problem.
    I have a JFrame as the main application window. I then create a JWindow with a JTextField that I would like to use as a Popup Palette. The problem is that when I click in the text box, the title bar of the JFrame changes it's appearance because the focus is now on the text box in the JWindow.
    If I use setFocusableWindowState(false) on the JWindow then the title bar of the JFrame does not change(which is the behaviour I want), but I cannot type in the JTextField.
    I understand why this is happening. The JTextField needs to have focus in order to recieve input and because it is in the JWindow, the JWindow takes the focus away from the JFrame.
    Does anyone know how I can make it so the JFrame Title Bar does not change appearance when the JTextField in the JWindow gets focus?
    The only thing that I can think of, is to somehow change the JFrame Look & Feel so that the title does not change appearance when the JFrame looses focus. I have no idea how to do that though.
    If you are wondering why I need this, it is because I need a JTextField to display on top of a Heavyweight component. I want it to appear as if it is part of the same window. Having the title bar of the JFrame change when you click in the textbox kind of destroys the illusion that it is part of the heavyweight component.
    Also, if you know of any other ways to get the JTextField to display and work on top of a Heavyweight component then I would appreciate that as well.
    Here is an example that you can run to see the behaviour. You can try it with the setFocusableWindowState line both uncommented and commented out.
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.JWindow;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    public class TestFocus implements Runnable {
        private JFrame frame;
        private JWindow popup;
        public void run() {
            //Create a new Frame
             frame = new JFrame("Frame Test");
             JButton but = new JButton("Does Nothing");
            frame.getContentPane().add(but);
            frame.setPreferredSize(new Dimension( 500, 500 ));
            frame.pack();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
            //Create a JWindow with a JTextField
            popup = new JWindow( frame );
            JPanel p = new JPanel(new BorderLayout());
            JTextField txt = new JTextField();
            p.add( txt, BorderLayout.NORTH );
            JButton but2 = new JButton("Also does nothing");
            p.add(but2, BorderLayout.SOUTH);
            popup.getContentPane().add(p);
            popup.setLocation( frame.getLocation().x + 50, frame.getLocation().y + 50 );
            popup.pack();
            //Proper title behaviour if I have this statement
            //but then I can't type in the text box.
            //popup.setFocusableWindowState(false);
            popup.setVisible(true);
        public static void main(String[] args) {
            try {
                System.setProperty("sun.java2d.noddraw", "true");
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            catch (Exception e) {
            SwingUtilities.invokeLater(new TestFocus());
    }Thanks,
    Jeff

    The code works fine on XP using JDK1.4.2, maybe its a version/platform issue check the bug database.
    -> if you know of any other ways to get the JTextField to display and work on top of a Heavyweight component
    You could try using
    JPopupMenu.setDefaultLightWeightPopupEnabled(false)and then add the JTextField to a jPopupMenu instead of a JWindow (although behind the scenes I think it will use a JWindow as the popup, so it may not solve the problem either if it is a version/platform issue).

  • Hold Focus with JFrames

    I am trying to create a JFrame much like an JOptionPane.showInputDialog which disallows the user to use anything until they have clicked on the ok or cancel buttons. Does anyone know how I can make the JFrame have this property? Thanks for your help,
    Anthony.
    Also do you know the property to keep the JFrame inFront of all the others no matter what the user does (Like they do in photoshop). I have been trying to program this to no avail for ages, putting Listeners on all other panels to call JFrame.toFront but none of them work like those in photoshop.ta again.

    Hi hope your still there, I haven't been able to get into this site for a while something to do with the automatice login which I've just disabled. I've downloaded the API and install it on my computer but I can't find the 'Always on top' method for any of the provided Classes. I have been trying to use skin window which doesn't seem to add any methods onto the existing JFrame methods,
    Anthony.

  • Jframe lose focus with jdk 1.4 beta90

    My jframe has two JInternalFrame. One contains a jtree, another contains a jeditorpane. A jpopup menu will appear, after I click the jtree. After I finish the jpopupmenu action, my jeditorpane can not recieve any keyboard event. The only workaround is to switch to any other application, then click jeditorpane again.
    I trace the status of the JFrame.
    1. JFrame get focus
    2. after click jtree, JFrame lose focus
    3. After finish the jpopup menu action, JFrame should gain focus. but JFrame doesn't get that.
    How can I figure it out. Any advice would be highly appreciated.

    i believe it is a bug of jdk14

  • Requesting focus for JTextField inside JPanel

    I have an application with following containment hierarchy.
    JFrame --> JSplitPane --> JPanel.
    JPanel is itself a seperate class in a seperate file. I want to give focus to one of the JTextfields in JPanel, when the JPanel is intially loaded in the JFrame. I believe that I cannot request focus until the JPanel is constructed. I can set the focus from JFrame (which loads JPanel) but I want to do this from JPanel. Is there any technique to request focus from the JPanel itself (preferably during JPanel construction).
    regards,
    Nirvan.

    I believe that I cannot request focus until the JPanel is constructedYou can't request focus until the frame containing the panel is visible. You can use a WindowListener and handle the windowOpened event.

  • Browser window gains focus :-(

    Hello,
    I am starting an applet... this applet loads data from the server, which is came from. After its gets the data it visualize a JFrame... so no JApplet window appears in the browser window... the JFrame is the actually user window....
    Under Mac OS X it runs fine... but under Windows XP SP2, Firefox, IE 6, Java 5 latest I do have the problem, that the browser window, which the applet loads comes in foreground when the JFrame is set to visible.... I have to click on the JFrame to use it...
    has anybody an idea how I can give the focus the JFrame and not the browser window under windows? That would be nice....
    Thanks guys.

    Maybe toFront()? Saw it in the API, it looks appropriate, but I haven't tried it myself.

  • Help needed for jspinner

    Its the third time i am posting the same qusetion with out any sucess. Some one may knew the answer . Please help me
    I got a jspinner , a text box and a button in my frame. i valdiate the values entered in the text field and if an invalid value is entered an error dialog is show . Now if I enter an invalid value in the text field and click the buttons along with the jspinner, the error dialog is displayed and focus is returned back to the textbox,but the problem is that the spinner button remains in a pressed condition as a result the number keeps of increasing / decreasing in jspinner (if you click both the buttons , it will increase and decrease at the same time). I am including the code also.
    I have searched through the forums and couldnt find a solution. Is it a problem with jspinner or my code?
    thanks in advance
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class focus extends JFrame implements FocusListener {
    JPanel pan1=new JPanel();
    JButton btn1=new JButton("OK");
    JButton btn2=new JButton("Cancel");
    JTextField txt1=new JTextField(10);
    SpinnerCircularNumberModel model=new SpinnerCircularNumberModel(50);
    JSpinner spin=new JSpinner(model);
    focus() {
    getContentPane().setLayout(new FlowLayout());
    getContentPane().add(txt1);
    getContentPane().add(btn1);
    getContentPane().add(btn2);
    getContentPane().add(spin);
    txt1.addFocusListener(this);
    setSize(200,200);
    setVisible(true);
    pack();
    public void focusGained(FocusEvent fe) {
    public void focusLost(FocusEvent fe) {
    try {
    Integer.parseInt(txt1.getText());
    } catch ( NumberFormatException nfe) {
    JOptionPane.showMessageDialog(this, "Invalid value","ERROR", JOptionPane.ERROR_MESSAGE);
    txt1.requestFocus();
    public static void main(String arg[]) {
    focus f=new focus();
    class SpinnerCircularNumberModel extends SpinnerNumberModel {
    public SpinnerCircularNumberModel(int init) {
    super(init,0,99,1);
    public Object getNextValue() {
    int val = Integer.parseInt(getValue().toString());
    if(val==99)
    return (new Integer(0));
    else
    return (new Integer(++val));
    public Object getPreviousValue() {
    int val = Integer.parseInt(getValue().toString());
    if(val==0)
    return (new Integer(99));
    else
    return (new Integer(--val));

    i found out the answer . It was a bug with the jspinner.
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4840869

  • Funny behaviour of JSpinner

    please help me solving this peculiar problem with jspinner . I got a jspinner , a text box and a button of my frame.i have written code to valdiate the value entered in text field. If an invalid value is entered an error dialog is show. and focus is returned to the textbox.. Now if I enter an invalid value in the text field and click the small buttons in jspinner, the error dialog is displayed and focus is returned back to the textbox but the problem is that the spinner button remains in a pressed condition as a result the number keeps of increasing / decreasing in jspinner (if you click both the buttons , it will increase and decrease at the same time). I am including the code also.
    I have searched through the forums and find that its a problemm with the look and feel. Can any one suggest a simple method to rectify it ??
    thanks in advance
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class focus extends JFrame implements FocusListener {
    JPanel pan1=new JPanel();
    JButton btn1=new JButton("OK");
    JButton btn2=new JButton("Cancel");
    JTextField txt1=new JTextField(10);
    SpinnerCircularNumberModel model=new SpinnerCircularNumberModel(50);
    JSpinner spin=new JSpinner(model);
    focus() {
    getContentPane().setLayout(new FlowLayout());
    getContentPane().add(txt1);
    getContentPane().add(btn1);
    getContentPane().add(btn2);
    getContentPane().add(spin);
    txt1.addFocusListener(this);
    setSize(200,200);
    setVisible(true);
    pack();
    public void focusGained(FocusEvent fe) {
    public void focusLost(FocusEvent fe) {
         try {
              Integer.parseInt(txt1.getText());
         } catch ( NumberFormatException nfe) {
              JOptionPane.showMessageDialog(this, "Invalid value","ERROR", JOptionPane.ERROR_MESSAGE);               
    txt1.requestFocus();
    public static void main(String arg[]) {
    focus f=new focus();
    class SpinnerCircularNumberModel extends SpinnerNumberModel {
    public SpinnerCircularNumberModel(int init) {
    super(init,0,99,1);
    public Object getNextValue() {
    int val = Integer.parseInt(getValue().toString());
    if(val==99)
    return (new Integer(0));
    else
    return (new Integer(++val));
    public Object getPreviousValue() {
    int val = Integer.parseInt(getValue().toString());
    if(val==0)
    return (new Integer(99));
    else
    return (new Integer(--val));

    I used it in the following way:
    class OptEmSpinner extends EmSpinner{
    public OptEmSpinner() {
    public interface RevertListener extends EventListener
         * The value has been Reverted to a the old valid value.
         * @param source is this bean.
         public void valueReverted(Component source);
    public static class OptNumberEditor extends NumberEditor {
         public OptNumberEditor(JSpinner spinner) {
         super(spinner);
         public void propertyChange(PropertyChangeEvent e)
              OptEmSpinner spinner = (OptEmSpinner)getSpinner();
              if (spinner == null) return; // Indicates we aren't installed anywhere.
              Object source = e.getSource();
              String name = e.getPropertyName();
              if ((source instanceof JFormattedTextField) && "value".equals(name))
                   Object lastValue = spinner.getValue();
                   // Try to set the new value
                   try
                        spinner.setValue(getTextField().getValue());
                   catch (IllegalArgumentException iae)
                        // Spinner didn't like new value, reset
                        try
                             ((JFormattedTextField)source).setValue(lastValue);
                        catch (IllegalArgumentException iae2)
                             spinner.fireValueReverted(e);
                             // Still bogus, nothing else we can do, the
                             // SpinnerModel and JFormattedTextField are now out
                             // of sync.
              else
                   spinner.fireValueReverted(e);
    protected JComponent createEditor(SpinnerModel model) {
         if (model instanceof SpinnerNumberModel) return new OptNumberEditor((JSpinner)this);
         return super.createEditor(model);
    private void fireValueReverted(PropertyChangeEvent e)
         Object source = e.getSource();
         String name = e.getPropertyName();
    // JFormattedTextField jft = ((DefaultEditor) getEditor()).getTextField();
         JComponent jft = ((DefaultEditor)getEditor()).getTextField();
         if ((source instanceof JFormattedTextField) && "editValid".equals(name))
              if (!jft.hasFocus()) // ensure lost focus
                   Object[] listeners = listenerList.getListenerList();
                   for (int i = listeners.length - 2; i >= 0; i -= 2)
                        if (listeners[i] == RevertListener.class)
                             ((RevertListener)listeners[i + 1]).valueReverted(jft);
    public void addRevertListener(RevertListener revListener)
         listenerList.add(OptEmSpinner.RevertListener.class, revListener);
    public void removeRevertListener(RevertListener revListener)
         listenerList.remove(OptEmSpinner.RevertListener.class, revListener);
    USED in class:
    public class MyPanel extends JPanel implements OptEmSpinner.RevertListener
    LISTENER IMPLEMENTATION:
    public void valueReverted(Component source)
              Runnable runnable =
                        new Runnable()
                             public void run()
                                  EmOptionPane.showSemiModalMessageDialog(
                                       parent,
                                       sRes.getString("Invalid Value: Old value will be retained."),
                                       sRes.getString("Invalid Input"),
                                       JOptionPane.WARNING_MESSAGE
    //                              dialogShown = false;
                   SwingUtilities.invokeLater(runnable);
    You can modify or pick from this......
    Regards
    Mohit

  • In Unix, main JFrame focus not regained after modal dialog exit.

    Hi all,
    I'm new to this forum so hopefully this is the right place to put this question.
    I have a relatively simple GUI application written in Java 6u20 that involves a main gui window (extends JFrame). Most of the file menu operations result in a modal dialog (either JFileChooser or JOptionPane) being presented to the user.
    The problem is that when running on Unix (HPUX), the process of changing focus to one of these modal dialogs occasionally results in a quick flash of the background terminal window (not necessarily that used to launch the Java), and the process of closing the modal dialogs (by any means, i.e. any dialog button or hitting esc) doesn't always return focus to the main extended JFrame object, sometimes it goes to the terminal window and sometimes just flashes the terminal window before returning to the main JFrame window.
    I think the problem is with the Unix window manager deciding that the main focus should be a terminal window, not my Java application, since the problem occurs in both directions (i.e. focus from main JFrame to modal dialog or vice versa).
    In most cases of JOptionPane, I DO specify that the main extended JFrame object is the parent.
    I've tried multiple things since the problem first occured, including multiple calls to a method which calls the following:
    .toFront();
    .requestFocus();
    .setAlwaysOnTop(true);
    .setVisible(true);
    ..on the main JFrame window (referred to as a public static object)...
    just before and after dialog display, and following selection of any button from the dialogs. This reduced the frequency of the problem, but it always tends to flash the terminal window if not return focus to it completely, and when it occurs (or starts to occur then gets worse) is apparently random! (which makes me think it's an OS issue)
    Any help appreciated thanks,
    Simon
    Self-contained compilable example below which has the same behaviour, but note that the problem DOESN'T occur running on Windows (XP) and that my actual program doesn't use auto-generated code generated by a guibuilder:
    * To change this template, choose Tools | Templates 
    * and open the template in the editor. 
    package example;  
    import javax.swing.JOptionPane;  
    * @author swg 
    public class Main {  
         * @param args the command line arguments 
        public static void main(String[] args) {  
            java.awt.EventQueue.invokeLater(new Runnable() {  
                public void run() {  
                    new NewJFrame().setVisible(true);  
    class NewJFrame extends javax.swing.JFrame {  
        /** Creates new form NewJFrame */ 
        public NewJFrame() {  
            initComponents();  
        /** This method is called from within the constructor to 
         * initialize the form. 
         * WARNING: Do NOT modify this code. The content of this method is 
         * always regenerated by the Form Editor. 
        @SuppressWarnings("unchecked")  
        // <editor-fold defaultstate="collapsed" desc="Generated Code">  
        private void initComponents() {  
            jMenuBar1 = new javax.swing.JMenuBar();  
            jMenu1 = new javax.swing.JMenu();  
            jMenuItem1 = new javax.swing.JMenuItem();  
            jMenu2 = new javax.swing.JMenu();  
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);  
            jMenu1.setText("File");  
            jMenuItem1.setText("jMenuItem1");  
            jMenuItem1.addActionListener(new java.awt.event.ActionListener() {  
                public void actionPerformed(java.awt.event.ActionEvent evt) {  
                    jMenuItem1ActionPerformed(evt);  
            jMenu1.add(jMenuItem1);  
            jMenuBar1.add(jMenu1);  
            jMenu2.setText("Edit");  
            jMenuBar1.add(jMenu2);  
            setJMenuBar(jMenuBar1);  
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());  
            getContentPane().setLayout(layout);  
            layout.setHorizontalGroup(  
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)  
                .addGap(0, 400, Short.MAX_VALUE)  
            layout.setVerticalGroup(  
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)  
                .addGap(0, 279, Short.MAX_VALUE)  
            pack();  
        }// </editor-fold>  
        private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {  
            int result = JOptionPane.showConfirmDialog(this, "hello");  
        // Variables declaration - do not modify  
        private javax.swing.JMenu jMenu1;  
        private javax.swing.JMenu jMenu2;  
        private javax.swing.JMenuBar jMenuBar1;  
        private javax.swing.JMenuItem jMenuItem1;  
        // End of variables declaration  
    }

    It won't comfort you much, but I had similar problems on Solaris 10, and at the time we traked them down to a known bug [6262392|http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6262392]. The status of this latter is "Closed, will not fix", although it is not explained why...
    It's probably because the entry is itself related to another, more general, bug [6888200|http://bugs.sun.com/bugdatabase/view_bug.do;jsessionid=b6eea0fca217effffffffe82413c8a9fce16?bug_id=6888200], which is still open.
    So it is unclear whether this problem will be worked upon (I suspect that yes) and when (I suspect that... not too soon, as it's been dormant for several years!).
    None of our attempts (+toFront(...)+ etc...) solved the issue either, and they only moderately lowered the frequency of occurrence.
    I left the project since then, but I was said that the workaround mentioned in the first bug entry (see comments) doesn't work, whereas switching to Java Desktop instead of CDE reduced the frequency of the issues (without fixing them completely either) - I don't know whether it's an option on HPUX.
    Edited by: jduprez on Jul 9, 2010 11:29 AM

  • Problems with 'background' JFrame focus when adding a modal JDialog

    Hi all,
    I'm trying to add a modal JDialog to my JFrame (to be used for data entry), although I'm having issues with the JFrame 'focus'. Basically, at the moment my program launches the JFrame and JDialog (on program load) fine. But then - if I switch to another program (say, my browser) and then I try switching back to my program, it only shows the JDialog and the main JFrame is nowhere to be seen.
    In many ways the functionality I'm looking for is that of Notepad: when you open the Find/Replace box (albeit it isn't modal), you can switch to another program, and then when you switch back to Notepad both the main frame and 'JDialog'-esque box is still showing.
    I've been trying to get this to work for a couple of hours but can't seem to. The closest I have got is to add a WindowFocusListener to my JDialog and I hide it via setVisible(false) once windowLostFocus() is fired (then my plan was to implement a similar functionality in my JFrame class - albeit with windowGainedFocus - to show the JDialog again, i.e. once the user switches back to the program). Unfortunately this doesn't seem to work; I can't seem to get any window or window focus listeners to actually fire any methods, in fact?
    I hope that kind of makes sense lol. In short I'm looking for Notepad CTRL+R esque functionality, albeit with a modal box. As for a 'short' code listing:
    Main.java
    // Not all of these required for the code excerpt of course.
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.GraphicsEnvironment;
    import java.awt.Rectangle;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ComponentAdapter;
    import java.awt.event.ComponentEvent;
    import java.awt.event.FocusEvent;
    import java.awt.event.FocusListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowFocusListener;
    import java.awt.event.WindowListener;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JSplitPane;
    import javax.swing.UIManager;
    import javax.swing.plaf.basic.BasicSplitPaneDivider;
    import javax.swing.plaf.basic.BasicSplitPaneUI;
    public class Main extends JFrame implements ActionListener, WindowFocusListener, WindowListener, FocusListener {
         static JFrame frame;
         private static int programWidth;
         private static int programHeight;
         private static int minimumProgramWidth = 700;
         private static int minimumProgramHeight = 550;
         public static SetupProject setupProjectDialog;
         public Main() {
              // Setup the overall GUI of the program
         private static void createSetupProjectDialog() {
              // Now open the 'Setup Your Project' dialog box
              // !!! Naturally this wouldn't auto-open on load if the user has already created a project
              setupProjectDialog = new SetupProject( frame, "Create Your Website Project", true );
              // Okay, for this we want it to be (say) 70% of the progamWidth/height, OR *slightly* (-25px) smaller than the minimum size of 700/550
              // Change (base on programWidth/Height) then setLocation
              int currProgramWidth = getProgramWidth();
              int currProgramHeight = getProgramHeight();
              int possibleWidth = (int) (currProgramWidth * 0.7);
              int possibleHeight = (int) (currProgramHeight * 0.7);
              // Set the size and location of the JDialog as needed
              if( (possibleWidth > (minimumProgramWidth-25)) && (possibleHeight > (minimumProgramHeight-25)) ) {
                   setupProjectDialog.setPreferredSize( new Dimension(possibleWidth,possibleHeight) );
                   setupProjectDialog.setLocation( ((currProgramWidth/2)-(possibleWidth/2)), ((currProgramHeight/2)-(possibleHeight/2)) );
               else {
                   setupProjectDialog.setPreferredSize( new Dimension( (minimumProgramWidth-25), (minimumProgramHeight-25)) );
                   setupProjectDialog.setLocation( ((currProgramWidth/2)-((minimumProgramWidth-25)/2)), ((currProgramHeight/2)-((minimumProgramHeight-25)/2)) );
              setupProjectDialog.setResizable(false);
              setupProjectDialog.toFront();
              setupProjectDialog.pack();
              setupProjectDialog.setVisible(true);
         public static void main ( String[] args ) {
              Main frame = new Main();
              frame.pack();
              frame.setVisible(true);
              createSetupProjectDialog();
            // None of these get fired when the Jframe is switched to. I also tried a ComponentListener, but had no joy there either.
         public void windowGainedFocus(WindowEvent e) {
              System.out.println("Gained");
              setupProjectDialog.setVisible(true);
         public void windowLostFocus(WindowEvent e) {
              System.out.println("GainedLost");
         public void windowOpened(WindowEvent e) {
              System.out.println("YAY1!");
         public void windowClosing(WindowEvent e) {
              System.out.println("YAY2!");
         public void windowClosed(WindowEvent e) {
              System.out.println("YAY3!");
         public void windowIconified(WindowEvent e) {
              System.out.println("YAY4!");
         public void windowDeiconified(WindowEvent e) {
              System.out.println("YAY5!");
         public void windowActivated(WindowEvent e) {
              System.out.println("YAY6!");
         public void windowDeactivated(WindowEvent e) {
              System.out.println("YAY7!");
         public void focusGained(FocusEvent e) {
              System.out.println("YAY8!");
         public void focusLost(FocusEvent e) {
              System.out.println("YAY9!");
    SetupProject.java
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowFocusListener;
    import java.awt.event.WindowListener;
    import java.io.IOException;
    import java.net.URL;
    import javax.imageio.ImageIO;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    public class SetupProject extends JDialog implements ActionListener {
         public SetupProject( final JFrame frame, String title, boolean modal ) {
              // Setup the JDialog
              super( frame, title, modal );
              setDefaultCloseOperation( JDialog.DISPOSE_ON_CLOSE );
              // Bad code. Is only temporary
              add( new JLabel("This is a test.") );
              // !!! TESTING
              addWindowFocusListener( new WindowFocusListener() {
                   public void windowGainedFocus(WindowEvent e) {
                        // Naturally this now doesn't get called after the setVisible(false) call below
                   public void windowLostFocus(WindowEvent e) {
                        System.out.println("Lost");
                        setVisible(false); // Doing this sort of thing since frame.someMethod() always fires a null pointer exception?!
    }Any help would be very much greatly appreciated.
    Thanks!
    Tristan

    Hi,
    Many thanks for the reply. Isn't that what I'm doing with the super() call though?
    As in, in Main.java I'm doing:
    setupProjectDialog = new SetupProject( frame, "Create Your Website Project", true );Then the constructor in SetupProject is:
    public SetupProject( final JFrame frame, String title, boolean modal ) {
              // Setup the JDialog
              super( frame, title, modal );
              And isn't the super call (since the class extends JDialog) essentially like doing new JDialog(frame,title,modal)?
    If not, that would make sense due to the null pointer exception errors I've been getting. Although I did think I'd done it right hence am confused as to the right way to handle this,if so.
    Thanks,
    Tristan
    Edited by: 802573 on 20-Oct-2010 08:27

  • JFrame not keeping focus

    How can I ensure that a JFrame will always keep focus?. I need it to always remain on top and be visible
    thanks

    A tricky one.
    Java doesn't allow this. Not even the upcoming version 1.4 allows this.
    I have done it, though and many people on this forum have. What you need to do is go native. If you are on the Windows platform write a JNI (Java Native Interface) compliant DLL and call it from your code using the native keyword. If you want some code write me at [email protected]
    Morten Hjerl-Hansen

  • Printing a focused chart contained in a JFrame

    Hello everyone,
    I have problem of printing a focused chart which contained in a JFrame. Here is the case:
    1) A JFrame I designed as the root of my application, in which there are menu items, such as Print, Save,Open....
    2)A graphwindow is opened when user hits the "Open" from the above menu list. This graphwindow is basically another JFrame, which contains a chart ( a JPanel). It is an instance of a General chart class somewhere else.
    3) User is able to open multiple graphwindow by selecting different data. the window is able to be focused by a mouse click,just like all the windows applicaiton.
    Hope you have a clear picture now.
    Now, I'm trying to implement the Print function in the Root Frame which should be able to print out the focused the graphwindow. Could anyone please tell me how to do it? any ideas?
    All the reply will be appreciated.
    -SQ

    Here's one thread with my solution:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=501660
    and here's some more discussion:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=407727

  • How can I stop a JFrame from taking the focus?

    Hi,
    Please see my original post in the Java Event Handling forum:
    http://forum.java.sun.com/thread.jsp?forum=424&thread=565034&tstart=0&trange=15
    Sorry, for cross-posting but its been nearly a week and I have had no replies. This forum looks a bit more active.
    - David

    try this...
    JFrame frame = new JFrame();
    frame.setFocusableWindowState(false);setFocusableWindowState
    public void setFocusableWindowState(boolean focusableWindowState)Sets whether this Window can become the focused Window if it meets the other requirements outlined in isFocusableWindow. If this Window's focusable Window state is set to false, then isFocusableWindow will return false. If this Window's focusable Window state is set to true, then isFocusableWindow may return true or false depending upon the other requirements which must be met in order for a Window to be focusable.
    Setting a Window's focusability state to false is the standard mechanism for an application to identify to the AWT a Window which will be used as a floating palette or toolbar, and thus should be a non-focusable Window.
    Parameters:
    focusableWindowState - whether this Window can be the focused Window

  • 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();
    }

Maybe you are looking for