我必须创建一个文本字段,一个文本区域和两个按钮,但是我被困在文本字段上,因为我无法在运行程序时显示它。我的JFrame一直显得空洞。
public class SentanceBuilder extends JFrame {
private JTextField textField = new JTextField(50);
private JTextArea textArea = new JTextArea(200,200);
private JButton Submit = new JButton();
private JButton Cancel = new JButton();
public SentanceBuilder(){
textField.setVisible(true);
textField.setLocation(50, 50);
this.textField();
this.setSize(400, 300);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public void textField(){
String textContent = textField.getText();
}
}
答案 0 :(得分:3)
您永远不会将textField变量添加到容器,例如由顶级窗口保存的JPanel,例如JFrame。实际上,在您的代码中,您将无添加到您的JFrame中!
如果这是我的GUI,我就
add(...)
方法将其和其他组件添加到主JPanel。add(...)
方法将主要JPanel添加到JFrame的contentPane。pack()
然后调用setVisible(true)
,但之后仅添加所有组件,而不是之前。如,
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class MyFoo extends JFrame {
private static final long serialVersionUID = 1L;
private JTextField textField = new JTextField(10);
private JButton button = new JButton("Foo Button");
public MyFoo() {
super("My JFrame");
// so Java will end when GUI is closed
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// code to be called when button is pushed
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO code that runs when button is pushed.
}
});
// panel to hold everything
JPanel mainPanel = new JPanel();
// add all to the panel
mainPanel.add(new JLabel("Text Field:"));
mainPanel.add(textField);
mainPanel.add(button);
// add the panel to the main GUI
add(mainPanel);
}
// start up code
private static void createAndShowGui() {
JFrame mainFrame = new MyFoo();
mainFrame.pack();
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
}
public static void main(String[] args) {
// call start up code in a Swing thread-safe way
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}