简体   繁体   中英

Cannot edit JTextField in popup JFrame

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM