1. Swing之列表和文本框
1.1 列表
1.11 下拉框(JComboBox)
示例:
package GUI.Swing;
import javax.swing.*;
import java.awt.*;
public class TestJComboBox extends JFrame {
public TestJComboBox() throws HeadlessException {
Container container = getContentPane();
JComboBox jComboBox = new JComboBox();
jComboBox.addItem("First");
jComboBox.addItem("Second");
jComboBox.addItem("Last");
container.add(jComboBox);
setBounds(100, 100, 200, 100);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new TestJComboBox();
}
}
运行结果:
1.1.2 列表框(JList)
示例:
package GUI.Swing;
import javax.swing.*;
import java.awt.*;
public class TestJComboBox2 extends JFrame {
public TestJComboBox2() throws HeadlessException {
Container container = getContentPane();
// 生成列表的内容
String[] contents = {"First", "Second", "Last"};
// 列表中需要放入内容
JList jList = new JList(contents);
container.add(jList);
setBounds(100, 100, 200, 100);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new TestJComboBox2();
}
}
运行结果:
1.2 文本框
1.2.1 文本框(JTextField)
示例:
package GUI.Swing;
import javax.swing.*;
import java.awt.*;
public class TestText extends JFrame {
public TestText() throws HeadlessException {
Container container = getContentPane();
// 文本框
JTextField jTextField01 = new JTextField("Hello");
JTextField jTextField02 = new JTextField("World");
container.add(jTextField01, BorderLayout.NORTH);
container.add(jTextField02, BorderLayout.SOUTH);
setVisible(true);
setBounds(100, 100, 300, 150);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestText();
}
}
运行结果:
1.2.2 密码框(JPasswordField)
示例:
package GUI.Swing;
import javax.swing.*;
import java.awt.*;
public class TestText2 extends JFrame {
public TestText2() throws HeadlessException {
Container container = getContentPane();
// 密码框
JPasswordField jPasswordField = new JPasswordField();
jPasswordField.setEchoChar('*');// 设置替换字符 默认是小圆圈
container.add(jPasswordField);
setVisible(true);
setBounds(100, 100, 400, 200);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestText2();
}
}
运行结果:
1.2.3 文本域(JTextArea )
示例:
package GUI.Swing;
import javax.swing.*;
import java.awt.*;
public class TextJScroll extends JFrame {
public TextJScroll() throws HeadlessException {
Container container = getContentPane();
// 文本域
JTextArea jTextArea = new JTextArea(20, 50);
jTextArea.setText("李旭永远的神!");
// Scroll面板
JScrollPane scrollPane = new JScrollPane(jTextArea);
container.add(scrollPane);
setBounds(100, 100, 300, 200);
setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TextJScroll();
}
}
运行结果: