【问题标题】:How to edit JTextField?如何编辑 JTextField?
【发布时间】:2015-10-12 18:48:07
【问题描述】:

我想编写一个简单的 Swing 应用程序,底部有一个按钮和一个文本字段。我正在使用JTextField,但它不可点击。我在网上搜索过,但我找不到解决方案。在问题How to Set Focus on JTextField? 中,我发现了以下内容:

addWindowListener( new WindowAdapter() {
        public void windowOpened( WindowEvent e ){
            entry.requestFocus();
        }
    });

但这无济于事。在另一个问题(How do you set a focus on Textfield in Swing?)中,我找到了Component.requestFocus(),但这也不起作用。我也试过了

    entry.setFocusable(true);
    entry.setEditable(true);
    entry.setEnabled(true);

没有效果。我的代码:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class StackSample extends JFrame {

    public StackSample() {
        initUI();
        pack();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    private void initUI() {
        JPanel panel = new JPanel(new BorderLayout());
        add(panel, BorderLayout.CENTER);
        JPanel bottomPanel = new JPanel(new FlowLayout());
        panel.add(bottomPanel, BorderLayout.SOUTH);
        JButton buttonDraw = new JButton("Draw");
        bottomPanel.add(buttonDraw);
        JTextField entry = new JTextField();
        bottomPanel.add(entry);
        setPreferredSize(new Dimension(250, 150));
        setLocationRelativeTo(null);
    }

    private static final long serialVersionUID = 8359448221778584189L;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                MyApp app = new MyApp();
                app.setVisible(true);
            }
        });
    }
}

【问题讨论】:

    标签: java swing


    【解决方案1】:

    您的 JTextField 是可点击的。唯一的问题是它太小了。

    这是因为您使用的是 FlowLayout,它将使组件尽可能小。

    一种解决方案是简单地切换到允许组件填充尽可能多的空间的布局,例如 BoxLayout:

        JPanel bottomPanel = new JPanel();
        bottomPanel.setLayout(new BoxLayout(bottomPanel,BoxLayout.X_AXIS));
    

    【讨论】:

    • bottomPanel.setLayout(new BoxLayout(bottomPanel,BoxLayout.X_AXIS));有帮助;显然应该是“StackSample app = new StackSample();”
    【解决方案2】:

    您没有为 JTextField 指定大小,因此它默认为零字符宽。尝试使用指定列数的构造函数。

    另外,什么是 MyApp?我看不到任何证据表明您的 StackSample 曾经被创建或使用过。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-22
      • 2015-10-29
      • 1970-01-01
      • 1970-01-01
      • 2022-07-24
      • 2017-09-26
      相关资源
      最近更新 更多