taz*_*boy 5 java swing jpanel jtextfield layout-manager
那JTextField是因为当我将鼠标移动到它应该是鼠标图标变为光标的位置时,当我点击它时就显示出来了.但它在发布时是看不见的.我错过了什么?
public class JavaSwingTextfield extends JFrame {
private static final long serialVersionUID = 1L;
JTextField myTextField;
public JavaSwingTextfield(){
/***** JFrame setup *****/
// Set the size of the window
setSize(600,600);
// Make the application close when the X is clicked on the window
setDefaultCloseOperation(EXIT_ON_CLOSE);
// Makes the JFrame visible to the user
setVisible(true);
/***** JFrame setup END *****/
/***** JButton setup *****/
// Create a JLabel and set its label to "Start"
myTextField = new JTextField("Start");
// Set the label's size
myTextField.setSize(100, 50);
// Put the label in a certain spot
myTextField.setLocation(200, 50);
// Set a font type for the label
//Font myFont = new Font("Serif", Font.BOLD, 24);
//myTextField.setFont(myFont);
// Add the label to the JFrame
add(myTextField);
/***** JButton setup END *****/
}
/***** The main method *****/
public static void main(String[] args){
new JavaSwingTextfield();
}
}
Run Code Online (Sandbox Code Playgroud)
Dav*_*amp 11
Event Dispatch Thread用于创建GUI组件setVisible(..)在将所有组件添加到之前不要调用JFrame(这是上面的代码片段实际错误+1到@Clark)JFrame课程setSize(..),而只是简单地打电话JFrame#pack()JFramesetSize()上JTextField,而看它的构造函数:JTextField(String text,int columns)LayoutManagers,请参阅此处以获取一些示例:布局管理器的可视指南这是我做的一个例子(基本上你的代码有修复):
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class JavaSwingTextfield {
private JTextField myTextField;
public JavaSwingTextfield() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myTextField = new JTextField("Start");
// Add the label to the JFrame
frame.add(myTextField);
//pack frame to component preferred sizes
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Create UI on EDT
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new JavaSwingTextfield();
}
});
}
}
Run Code Online (Sandbox Code Playgroud)