Swing getText不会读取用户输入

时间:2015-07-12 00:13:20

标签: java swing

我一直试图让GUI继续用于我正在处理的应用程序,而且,自从在Swing中做任何事情以来,已经过了很多年。大多数东西都回来了,但不是这样。我无法理解为什么,在所有不同的文本组件中,如果我在其中键入内容,getText()将始终返回""而不管。如果我使用setText()作为测试,它会正确返回,但这并没有真正帮助。

这在JTextArea / JTextField中保持一致,引用文本字段的各种方式(直接变量与从HashMap中提取),以及访问的是什么类型的线程。有时我使用调试器尝试查看通过其他测试片段发生的事情,但仍然没有。自编辑以来,已经修复了很多这些案例,但仍然存在问题。

在所有情况下,永远不会获得用户输入。

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class LifePathUI2 {

     final static boolean shouldWeightX = true;
     private GridBagConstraints cons;
     private BorderLayout windowLayout;
     private GridBagLayout layout;
     private JFrame mainWindow;
     private JPanel mainPanel;


     private JComponent currentComponent;
     private JTextField characterName;

    /**
     * @throws HeadlessException
     */
    public LifePathUI2() throws HeadlessException {
        cons = new GridBagConstraints();
        windowLayout = new BorderLayout();
        layout = new GridBagLayout();
        mainWindow = new JFrame();     
        mainPanel = new JPanel();

        mainWindow.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        init();
    }


    public void init()
    {
        mainWindow.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);

        mainWindow.setLayout(windowLayout);


        cons.ipadx = 5;
        cons.ipady = 5;
        cons.anchor = GridBagConstraints.NORTHWEST;
        cons.fill = GridBagConstraints.NONE;
        cons.weighty = 1.0;
        cons.weightx = 1.0;

        // to make everything work right we add a mainPanel under the mainWindow
        cons.gridheight = 1;
        cons.gridwidth = 1;

        mainWindow.add(mainPanel);
        // Readers keep in mind if you don't set this below, strange behavior happens
        mainPanel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
        mainPanel.setLayout(layout);

        currentComponent = mainPanel;

        addLabel(0,0,"Character Name");
        characterName = addTextF(1,0,"",30,true);
        endRow(2,0);

        addButton(0,1,"Foo").addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e)
            {
                System.out.println(characterName.getText());
            }   
        });

        endVertical(0,2);

        mainWindow.setSize(1400, 900);

        mainWindow.setVisible(true);
    }

    /**
     * Inserts a spacer to signify the end of components for this row (effects layout so it doesn't center)
     */
    private void endRow(int x, int y)
    {
        cons.weightx = 100.0;
        addLabel(x,y,"");
        cons.weightx = 1.0;
    }

    /**
     * Inserts a spacer to signify the end of components vertically (effects layout so it doesn't center)
     */
    private void endVertical(int x, int y)
    { 
        cons.weighty = 100.0;
        addLabel(x,y,"");
        cons.weighty = 1.0;
    }

    /**
     * Shorthand command to add label at coordinates with text
     * @param x non-negative integer
     * @param y non-negative integer
     * @param text Display Text for label
     */
    private JLabel addLabel(int x, int y, String text)
    {
        JLabel temp = new JLabel(text);
        addC(temp,x,y);
        return temp;
    }

    /**
     * Shorthand command to add Button at coordinates with text
     * @param x non-negative integer
     * @param y non-negative integer
     * @param text Display Text for Button
     * @return The component created
     */
    private JButton addButton(int x, int y, String text)
    {
        JButton temp = new JButton(text);
        addC(temp,x,y);
        return temp;
    }

    /**
     * Shorthand command to add Text Field at coordinates with text
     * @param x non-negative integer
     * @param y non-negative integer
     * @param value the default value for the text field
     * @param cols Number of Columns
     * @param updateListen If true will add listener that triggers UI updates when values change
     * @return The component created
     */
    private JTextField addTextF(int x, int y, String value, int cols, boolean updateListen)
    {
        JTextField temp = new JTextField(value, cols);

        // this prevents the common issue of the text fields turning into slits
        temp.setMinimumSize(temp.getPreferredSize());

        addC(temp,x,y);
        return temp;
    }

    /**
     * Shorthand to add new components to the UI tab at given coords
     * @param comp Component to add to UI
     * @param x non-negative integer
     * @param y non-negative integer
     * 
     */
    private void addC(JComponent comp, int x, int y) {
        cons.gridx = x;
        cons.gridy = y;
        currentComponent.add(comp,cons);
    }


    /**
     * @param args
     */
    public static void main(String[] args) {

        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                LifePathUI2 ui = new LifePathUI2();
                ui.init();
            }
        }); 

    }

}

我已经在这里搜索过每一个问题,但是没有一个问题似乎特别对应于这个问题。并不完全是在期待。

我为更大的片段道歉,但由于所有部分都在创建文本字段,阅读它们,创建GUI本身,所有部分似乎都与我在网上看到的例子相符......我'我只是聪明地知道我必须在这里做一些奇怪的事情,而不是看到它。

编辑:简化示例。尽管将其分解为更简单的测试用例,但仍然没有骰子 编辑2:完成压缩事物。我实际上期待这个工作,因为这是我之前编写的工作代码级别。但仍然没有

1 个答案:

答案 0 :(得分:5)

一个疯狂的猜测,但是您的update()方法看起来似乎可能试图从其收听的文档中提取文本(您不会说),并且如果是,则使用DocumentEvent获取Document,然后提取文本。类似的东西:

private class TextChangeListener implements DocumentListener {
  @Override
  public void changedUpdate(DocumentEvent e) {
     update(e);
  }

  @Override
  public void insertUpdate(DocumentEvent e) {
     update(e);
  }

  @Override
  public void removeUpdate(DocumentEvent e) {
     update(e);
  }
}

private void update(DocumentEvent e) {
  String text;
  try {
     Document doc = e.getDocument();
     text = e.getDocument().getText(0, doc.getLength());
     // do something with text here! ************
     System.out.println(text);
  } catch (BadLocationException e1) {
     e1.printStackTrace();
  }
}

除此之外,我在你的代码中丢失了。简化。重构。简化一些。重构一些。想想可以单独完全测试的小类。

修改

您拨打init() TWICE ,这就是问题所在,因为这意味着您创建了两个,一个显示,一个不显示。

你先在这里打电话:

public LifePathUI2() throws HeadlessException {
  // ....
  init();
}

然后在你的主要部分再次调用它:

  javax.swing.SwingUtilities.invokeLater(new Runnable() {
     public void run() {
        LifePathUI2 ui = new LifePathUI2();
        ui.init();
     }
  });

仅将其称为一次

改变这个:

public LifePathUI2() throws HeadlessException {
  cons = new GridBagConstraints();
  windowLayout = new BorderLayout();
  layout = new GridBagLayout();
  mainWindow = new JFrame();
  mainPanel = new JPanel();
  mainWindow.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  init();
}

到此:

public LifePathUI2() throws HeadlessException {
  cons = new GridBagConstraints();
  windowLayout = new BorderLayout();
  layout = new GridBagLayout();
  mainWindow = new JFrame();
  mainPanel = new JPanel();
  mainWindow.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  // init();
}
相关问题