【问题标题】:Swing getText won't read user inputSwing getText 不会读取用户输入
【发布时间】:2015-09-30 12:31:55
【问题描述】:

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

这在 JTextArea/JTextField、引用文本字段的各种方式(直接变量与从 HashMap 中提取)以及无论访问哪种线程都保持一致。有时我使用调试器尝试通过其他测试 sn-ps 来查看正在发生的事情,但仍然一无所获。自编辑以来,已经删除了很多这样的情况,但问题仍然存在。

在所有情况下,都不会获取用户输入。

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

    }

}

我已经在这里搜索了所有关于摇摆的问题,但似乎没有一个问题专门与这个问题相对应。完全没有预料到这一点。

我为更大的 sn-p 道歉,但由于所有围绕创建文本字段、阅读它们、创建 GUI 本身的部分,似乎都与我在网上看到的示例相匹配......我只是足够聪明,知道我在这里做了一些奇怪的事情,只是没有看到。

编辑:简化示例。尽管将其分解为一个更简单的测试用例,但仍然没有骰子 EDIT2:完成压缩。我实际上希望它能够工作,因为这是我之前编写的工作代码级别。但还是什么都没有

【问题讨论】:

  • I cannot understand why, across none of the different text components, if I type something into them, getText() will always return "" - 这可能是因为您创建了两个组件,并且您的代码引用了一个未显示在框架中的组件,因此您获得了 null。首先创建一个带有文本字段和按钮的简单框架。当您单击按钮时,您会显示文本。向自己证明这个简单的案例是有效的。然后确定为什么你有两个组件。您发布的代码太多,我无法查看。
  • 试试 temp.setText(getTextF(name));你必须确保你传递字符串..
  • 您的代码中的圈复杂度太多,这就是您难以调试代码和发布small的原因> 可测试的可运行程序。您应该重构您的代码以简化它,以便您拥有更小的类,这些类可以单独测试(使用适当的模拟),因为这将在现在和将来对您和我们都有帮助。
  • @HovercraftFullOfEels - 如果您看到具有文本字段 temp 的函数 getTextFVal(String name),它没有设置文本..您怎么看?
  • @BhavikPatel:我正在尝试将他的代码缩减为最小形式以了解它在做什么(他应该在发布之前为我们做的事情),但是还是太复杂了。

标签: java swing


【解决方案1】:

一个疯狂的猜测,但您的 update() 方法看起来可能试图从它正在收听的 Document 中提取文本(你没有说),如果是这样,那么使用 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();
}

然后在你的 main 中再次调用它:

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

【讨论】:

  • 就是这样!谢谢。我知道我已经根据其他人的回答涵盖了来自 cmets 的大部分意外事件,但我一直怀念这样的事情......
  • @Vigilant:再次感谢您的简化,因为它极大地帮助了
猜你喜欢
  • 2018-10-19
  • 1970-01-01
  • 2022-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-18
相关资源
最近更新 更多