1

Ok, I am having problems with a textfield in a popup JFrame... I actually had 2 separate programs, one was a game, and one was a map editor. I decided to make the game have a sort of built in map editor, so I added the classes from the map editor to a new package in my game's project, made a few small adjustments(like removing the main() method from the map editor), and then got things working. The map editor pops up as a new JFrame, and when I click the "new" button it opens a new JFrame with a couple TextFields and a button requesting a width and a height for the new map. I cannot edit the values in the textfields... and I have no clue why... Popup code:

private class newMap extends JFrame implements ActionListener{
    JLabel wlbl = new JLabel("Map width: ");
    JTextField w = new JTextField("12");
    JLabel hlbl = new JLabel("Map height: ");
    JTextField h = new JTextField("8");
    JButton create = new JButton("Create map");
    public newMap(Component p){
        super("New Map");
        setSize(100,75);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setResizable(false);
        setLayout(null);
        setVisible(true);
        int bw = 96, bh = 24, s = 4, x = s;

        wlbl.setBounds(x,s,bw,bh);
        x+=s+bw;
        add(wlbl);
        w.setBounds(x,s,bw,bh);
        x+=s+bw;
        add(w);
        hlbl.setBounds(x,s,bw,bh);
        x+=s+bw;
        add(hlbl);
        h.setBounds(x,s,bw,bh);
        x+=s+bw;
        add(h);
        create.setBounds(x,s,bw,bh);
        x+=s+bw;
        create.addActionListener(this);
        add(create);

        setSize(getWidth()-this.getContentPane().getWidth()+x,
                getHeight()-this.getContentPane().getHeight()+s+s+bh);
        setLocationRelativeTo(p);
    }
    public void actionPerformed(ActionEvent e){
        try{
            mapBox.create(Integer.parseInt(w.getText()),Integer.parseInt(h.getText()));
        }catch(NumberFormatException ex){
            return;
        }
        dispose();
    }
}

I have obviously tried things like w.requestFocusInWidnow(), and w.requestFocus(), and the same for the frame in general and a few other solutions I found online, but none of them have worked for me.

Problem solved: After explaining my problem I realized that the problem HAD to be in the code for the game somewhere, probably in the class for the JFrame, and I noticed that I did something weird instead of using a KeyListener implementation to handle input.(I previously was attempting to create the game as a JApplet, and I was having trouble with Keylisteners on the JApplet). I made my Main class a KeyEventDispatcher, or some such thing. Thanks for the help guys, it was a dumb problem(I was just looking in the wrong places for a solution).

So the KeyEventDispatcher wasn't properly "dispatching" the key actions to other components. I just went back to a conventional KeyListener, since it works fine for me in a JFrame.

csga5000
  • 4,062
  • 4
  • 39
  • 52

1 Answers1

5

I suspect the problem is in how you're calling this new window, that perhaps you have an infinite loop or some other construct that freezes the Swing event dispatch thread or EDT, making your GUI non-responsive. We'd know best if you could create and post an SSCCE for us to compile, test, run, and possibly modify and correct.

Also in my opinion, you have other significant but problems with your code that are unrelated to your main problem:

  • You shouldn't use JFrames where dialogs such as JOptionPanes or JDialogs should be used.
  • You should avoid use of absolute positioning in favor of use of layout managers.
  • You should strive to create code that complies with Java naming standards including giving classes names that start with an upper case letter. This becomes especially important when asking others to read and understand your code and help you.

For example, some quickly produced sample code:

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

@SuppressWarnings("serial")
public class TestNewMap extends JPanel {
   private MapBox mapBox = new MapBox();
   private NewMap newMap = new NewMap(this);
   private HoverNewMap hoverNewMap = new HoverNewMap();

   public TestNewMap() {
      JPanel btnPanel = new JPanel(new GridLayout(1, 0, 5, 0));

      btnPanel.add(new JButton(new AbstractAction("Show Your NewMap") {

         @Override
         public void actionPerformed(ActionEvent evt) {
            newMap.setVisible(true);
         }
      }));
      btnPanel.add(new JButton(new AbstractAction("Show Hover's NewMap") {

         @Override
         public void actionPerformed(ActionEvent evt) {
            hoverNewMap.setMapWidth(mapBox.getWidthValue());
            hoverNewMap.setMapHeight(mapBox.getHeightValue());

            Object[] options = { "Create Map", "Cancel" };
            Object initialValue = options[0];
            int result = JOptionPane.showOptionDialog(TestNewMap.this,
                  hoverNewMap, "Get Map Dimensions",
                  JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null,
                  options, initialValue);
            if (result == 0) {
               try {
                  int w = hoverNewMap.getMapWidth();
                  int h = hoverNewMap.getMapHeight();

                  mapBox.create(w, h);
               } catch (NumberFormatException e) {
                  JOptionPane.showMessageDialog(TestNewMap.this,
                        "Please only enter int values", "Non-int Input Error",
                        JOptionPane.ERROR_MESSAGE);
                  hoverNewMap.setMapHeight(0);
                  hoverNewMap.setMapWidth(0);
               }
            }
         }
      }));

      int borderGap = 5;
      setBorder(BorderFactory.createEmptyBorder(borderGap, borderGap,
            borderGap, borderGap));
      setLayout(new BorderLayout(borderGap, borderGap));
      add(btnPanel, BorderLayout.NORTH);
      add(mapBox, BorderLayout.CENTER);
   }

   private static void createAndShowGui() {
      TestNewMap mainPanel = new TestNewMap();

      JFrame frame = new JFrame("TestNewMap");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }

   private class MapBox extends JPanel {
      private static final int INIT_WIDTH = 12;
      private static final int INIT_HEIGHT = 8;
      private JTextField widthField = new JTextField(
            String.valueOf(INIT_WIDTH), 5);
      private JTextField heightField = new JTextField(
            String.valueOf(INIT_HEIGHT), 5);

      public MapBox() {
         add(new JLabel("Width:"));
         add(widthField);
         add(Box.createHorizontalStrut(10));
         add(new JLabel("Height:"));
         add(heightField);
      }

      public void create(int width, int height) {
         widthField.setText(String.valueOf(width));
         heightField.setText(String.valueOf(height));
      }

      public int getWidthValue() {
         return Integer.parseInt(widthField.getText());
      }

      public int getHeightValue() {
         return Integer.parseInt(heightField.getText());
      }

   }

   private class HoverNewMap extends JPanel {
      private JTextField mapWidth = new JTextField(5);
      private JTextField mapHeight = new JTextField(5);

      public HoverNewMap() {
         add(new JLabel("Width:"));
         add(mapWidth);
         add(Box.createHorizontalStrut(15));
         add(new JLabel("Height:"));
         add(mapHeight);

         setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
      }

      public void setMapWidth(int w) {
         mapWidth.setText(String.valueOf(w));
      }

      public void setMapHeight(int h) {
         mapHeight.setText(String.valueOf(h));
      }

      public int getMapWidth() throws NumberFormatException {
         int w = Integer.parseInt(mapWidth.getText());
         return w;
      }

      public int getMapHeight() throws NumberFormatException {
         int h = Integer.parseInt(mapHeight.getText());
         return h;
      }
   }

   private class NewMap extends JFrame implements ActionListener {
      JLabel wlbl = new JLabel("Map width: ");
      JTextField w = new JTextField("12");
      JLabel hlbl = new JLabel("Map height: ");
      JTextField h = new JTextField("8");
      JButton create = new JButton("Create map");

      public NewMap(Component p) {
         super("New Map");
         setSize(100, 75);
         setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
         setResizable(false);
         setLayout(null);
         // setVisible(true);
         int bw = 96, bh = 24, s = 4, x = s;

         wlbl.setBounds(x, s, bw, bh);
         x += s + bw;
         add(wlbl);
         w.setBounds(x, s, bw, bh);
         x += s + bw;
         add(w);
         hlbl.setBounds(x, s, bw, bh);
         x += s + bw;
         add(hlbl);
         h.setBounds(x, s, bw, bh);
         x += s + bw;
         add(h);
         create.setBounds(x, s, bw, bh);
         x += s + bw;
         create.addActionListener(this);
         add(create);

         setSize(getWidth() - this.getContentPane().getWidth() + x, getHeight()
               - this.getContentPane().getHeight() + s + s + bh);
         setLocationRelativeTo(p);
      }

      public void actionPerformed(ActionEvent e) {
         try {
            mapBox.create(Integer.parseInt(w.getText()),
                  Integer.parseInt(h.getText()));
         } catch (NumberFormatException ex) {
            return;
         }
         dispose();
      }
   }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • I have a preference of doing things myself, I don't much like using layouts, or JFrame subclasses, but if need be, I can change it to something like that. And in terms of the SSCCE, I would totally do that, except that, I don't have the problem when I reduce it. For example, if I copy ALL of the code for the map editor, paste it into a new project and then simply add a main method that initiating the first JFrame, then I don't have the problem. – csga5000 Jan 26 '13 at 02:29
  • @user1828361: using layout managers doesn't prevent you from doing things yourself, but rather it makes it much easier to maintain and update your code. As for not having the problem when you reduce it, then that is your main task as I see it -- to try to isolate the error by reducing your code until the error goes away. As for not liking to subclass JFrame -- but that's what you're doing above, so your statement confuses me. – Hovercraft Full Of Eels Jan 26 '13 at 02:38
  • Um, I figured it out, Editing it into the question, and yeah, I did need to isolate the problem... – csga5000 Jan 26 '13 at 02:38
  • @user1828361: Can you show the code where you display the window that is created from the code you've posted above? – Hovercraft Full Of Eels Jan 26 '13 at 02:39
  • I isolated the problem, and fixed it, read the edit to the question if you want to see what the problem was. – csga5000 Jan 26 '13 at 02:43