一直在用C\C++,還沒開始認真學Java,但這幾天課堂上的Java Swing 圖形使用者界面引起了我的興趣。正好前段時間在玩Qt的圖形化界面,發現兩者有很多相似之處,學起來也容易很多。(但實際上JavaSwing的各種事件特别複雜,名字也特别多,怪不得老師說JavaSwing實際開發用的很少)
效果圖:
具體用法見代碼:
Test.java
public class Test {
public static void main(String args[]) {
ComponentInWindow win = new ComponentInWindow();
win.setBounds(, , , );
win.setTitle("常見元件");
}
}
ComponentInWindow.java
import java.awt.FlowLayout;
import javax.swing.*;
public class ComponentInWindow extends JFrame{
JTextField text; //文本框
JButton button;
JCheckBox checkBox1, checkBox2, checkBox3; //選擇框
JRadioButton radio1, radio2; //單選按鈕
ButtonGroup group;
JComboBox<String> comBox; //下拉清單
JTextArea area; //文本區
public ComponentInWindow() {
init();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
void init() {
setLayout(new FlowLayout()); //流水式布局
add(new JLabel("文本框")); //添加标簽
text = new JTextField();
add(text);
add(new JLabel("按鈕:"));
button = new JButton("确定");
add(button);
add(new JLabel("選擇框"));
checkBox1 = new JCheckBox("音樂");
checkBox2 = new JCheckBox("文學");
checkBox3 = new JCheckBox("遊泳");
add(checkBox1);
add(checkBox2);
add(checkBox3);
add(new JLabel("單選按鈕:"));
group = new ButtonGroup(); //單選按鈕所在的組
radio1 = new JRadioButton("理科"); //建立單選按鈕,右面的文本是“理科”
radio2 = new JRadioButton("文科");
group.add(radio1);
group.add(radio2);
add(radio1);
add(radio2);
add(new JLabel("下拉清單:"));
comBox = new JComboBox<String>(); //建立下拉清單
comBox.addItem("一季度");
comBox.addItem("二季度");
comBox.addItem("三季度");
comBox.addItem("四季度");
add(comBox);
add(new JLabel("文本區:"));
area = new JTextArea(, );
add(new JScrollPane(area)); //添加帶有滾動條件的文本區
}
}