JTextField added to JPanel does not display properly.
(There is a problem analysis in the back, after reading will definitely help you solve the problem oh!!)
Code examples:
package CSDN;
import javax.swing.*;
public class JtextjoinJpanel {
public static void main(String[] args) {
JFrame f=new JFrame("Text Box Add Panel");
JPanel jp = new JPanel();
JTextField jt = new JTextField(). f.setBounds(400,400,500,500); // Set the window position size;
f.setBounds(400,400,500,500); // set window position size
jp.setSize(200,200); //set panel size
jt.setSize(100,100); //set textbox size
jp.add(jt); //add the text box to the panel
f.add(jp);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
Results:
solution:
- sets textbox parameters.
JTextField jt = new JTextField();
Change to:JTextField jt = new JTextField(10);
- set the panel layout to null.
Add jp.setLayout(null);
Results:
Note :10 means the number of characters that can be entered in a text box.
Reasons for the problem (personal opinion):
Due to the panel USES is flow layout, create a text box, if no input default arguments (string), then the text box default is empty, will cover its flow way, leaving only border (so see like a vertical bar, click can still input characters), if 10 to its input parameters, is equivalent to 10 characters have been input, so will not cover; Not setting it to flow layout also solves the problem.
Therefore, if
TextField jt = new JTextField();
to TextField jt = new JTextField("Hello");
The result is