在Java Swing中,要将JTextField添加到JPanel并显示它们,您需要遵循以下步骤:
import javax.swing.*;
import java.awt.*;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("JTextField Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 200);
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
JTextField textField1 = new JTextField(10);
JTextField textField2 = new JTextField(10);
panel.add(textField1);
panel.add(textField2);
frame.add(panel);
frame.setVisible(true);
}
}
完整代码如下:
import javax.swing.*;
import java.awt.*;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("JTextField Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 200);
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
JTextField textField1 = new JTextField(10);
JTextField textField2 = new JTextField(10);
panel.add(textField1);
panel.add(textField2);
frame.add(panel);
frame.setVisible(true);
}
}
这个代码示例将在JFrame中创建一个包含两个JTextField的JPanel,并显示它们。
领取专属 10元无门槛券
手把手带您无忧上云