爲了鍛鍊大家閱讀代碼的能力,本代碼無註釋。
演示的組件有:JFrame, JPanel, JMenuBar, JMenu, JMenuItem, JComboBox, JRadioButton, ButtonGroup, JCheckBox, JLabel, JTextField, JTextArea, JPasswordField。
——————————————————————————————————————————————————————
-,-媽的,我說怎麼單選按鈕 radio2 一直顯示不出來,原來是把 radio2.setBound() 也給寫成 radio1.setBound() 了。
——————————————————————————————————————————————————————
import java.awt.*;
import javax.swing.*;
public class Demo1 {
public static void main(String[] args) {
JFrame wnd = new JFrame("Main Window"); JPanel pnl = new JPanel();
wnd.setContentPane(pnl); wnd.setBounds(640, 360, 640, 360);
wnd.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); wnd.setVisible(true);
pnl.setBackground(Color.lightGray); pnl.setLayout(null);
JMenuBar menuBar = new JMenuBar();
JMenu menuFile = new JMenu("File"), submenu1Settings = new JMenu("Settings");
JMenuItem menuItemNew = new JMenuItem("New"), menuItemOpen = new JMenuItem("Open"),
menuItemSave = new JMenuItem("Save"), menuItemSaveAs = new JMenuItem("Save As"),
menuItemExit = new JMenuItem("Exit"), menuItemGeneral = new JMenuItem("General");
menuBar.add(menuFile); menuFile.add(submenu1Settings);
menuFile.add(menuItemNew); menuFile.add(menuItemOpen); menuFile.add(menuItemSave);
menuFile.add(menuItemSaveAs); menuFile.add(menuItemExit);
submenu1Settings.add(menuItemGeneral);
wnd.setJMenuBar(menuBar);
JComboBox combo1 = new JComboBox<String>();
combo1.addItem("File1"); combo1.addItem("File2"); combo1.setBounds(10, 5, 140, 20);
pnl.add(combo1);
JRadioButton radio1 = new JRadioButton("Valid"), radio2 = new JRadioButton("Invalid");
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(radio1); buttonGroup.add(radio2);
radio1.setBounds(160, 10, 70, 10); radio2.setBounds(240, 10, 70, 10);
pnl.add(radio1); pnl.add(radio2);
JCheckBox check1 = new JCheckBox("Enable"), check2 = new JCheckBox("Enable");
check1.setBounds(320, 10, 70, 10); check2.setBounds(400, 10, 70, 10);
pnl.add(check1); pnl.add(check2);
JLabel label = new JLabel("Input:");
label.setBounds(10, 30, 600, 15);
pnl.add(label);
JTextField textField = new JTextField("C:\\Windows\\system32\\");
textField.setBounds(10, 50, 600, 20);
pnl.add(textField);
JTextArea textArea = new JTextArea("****DEMO****");
textArea.setBounds(10, 75, 600, 100);
pnl.add(textArea);
JPasswordField pwField = new JPasswordField();
pwField.setBounds(10, 180, 200, 20);
pnl.add(pwField);
wnd.validate();
}
}
運行截圖: