【发布时间】: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);
}
});
}
}
【问题讨论】: