java笔记 常用组件

    科技2026-02-20  6

    import javax.swing.*; import java.awt.*; class Window extends JFrame { // 文本框部分 JTextField textField ; // 单行输入 JTextArea textArea; // 多行输入 JCheckBox checkBox1, checkBox2; // 多选框 // 单选框 JRadioButton radioButton1, radioButton2; ButtonGroup group; // 单选框必须要加在按钮组里面 // 下拉菜单,String是下拉的内容类型 JComboBox<String> comboBox; // 按钮 JButton button; // 标签 JLabel label; // 密码框 JPasswordField passwordField; public Window(){}; public Window(String s, int x, int y, int w, int h) { inits(s); setLocation(x, y); setSize(w, h); setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE); // 点击x关闭窗口 } void inits(String s) { setTitle(s); setLayout(new FlowLayout()); // 设置背景颜色 Container con = this.getContentPane(); con.setBackground(Color.black); // this.setBackground(Color.black); 不能用 // 单行文本 textField = new JTextField(50); // 长度 add(textField); // 多行文本 textArea = new JTextArea(10,10); // 行数和列数 add(textArea); // 下拉菜单 comboBox = new JComboBox<String >(); comboBox.addItem("c++"); comboBox.addItem("java"); add(comboBox); // 加入到窗口中 // 多选 checkBox1 = new JCheckBox("喜欢方帅"); checkBox2 = new JCheckBox("喜欢路强"); add(checkBox1); // 加入到窗口中 add(checkBox2); // 单选 group = new ButtonGroup(); radioButton1 = new JRadioButton("一般人"); radioButton2 = new JRadioButton("二般人"); group.add(radioButton1); group.add(radioButton2); add(radioButton1); add(radioButton2); // 按钮 button = new JButton("点我"); button.setForeground(Color.red); // 设置按钮前景颜色 add(button); // 标签 label = new JLabel("标签"); label.setForeground(Color.red); add(label); // 密码框 passwordField = new JPasswordField(10); add(passwordField); } } public class test { public static void main(String args[]) { Window win = new Window("常用组件",100,100,450,260); } }

    注意设置背景颜色那部分

    Processed: 0.014, SQL: 9