效果图:
代码实现:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class demo01 {
JFrame frame = new JFrame();
JMenuBar menuBar = new JMenuBar();
JMenu file = new JMenu("文件");
JMenu edit = new JMenu("编辑");
JMenuItem auto = new JMenuItem("自动换行");
JMenuItem copy = new JMenuItem("复制");
JMenuItem paste = new JMenuItem("粘贴");
JMenu format = new JMenu("格式");
JMenuItem comment = new JMenuItem("注释");
JMenuItem cancelComment = new JMenuItem("取消注释");
//文本域
JTextArea ta = new JTextArea(8,20);
//下拉列表框
JComboBox<String> colorSelect = new JComboBox<>();
//单选按钮
ButtonGroup bg = new ButtonGroup();
JRadioButton male = new JRadioButton("男",true);
JRadioButton female = new JRadioButton("女");
JCheckBox isMarried = new JCheckBox("是否已婚?",true);
JTextField tf = new JTextField(40);
JButton ok = new JButton("确定");
//组装界面
public void init(){
JPanel p1 = new JPanel();
p1.add(tf);//文本框
p1.add(ok);//按钮
frame.add(p1,BorderLayout.SOUTH);//将其放在南部
//组装选择相关组件
JPanel p2 = new JPanel();
colorSelect.addItem("蓝色");
colorSelect.addItem("绿色");
colorSelect.addItem("红色");
p2.add(colorSelect);//下拉选择
//将男女单选按钮添加到分组
bg.add(male);
bg.add(female);
p2.add(male);//男
p2.add(female);//女
p2.add(isMarried);//是否已婚
//组装文本域和选择相关组件
Box topLeft = Box.createVerticalBox();//垂直排列
topLeft.add(ta);//文本域
topLeft.add(p2);
frame.add(topLeft);
//组装顶部菜单
format.add(comment);//往格式中添加注释
format.add(cancelComment);//往格式中添加取消注释
edit.add(auto);//往编辑中添加自动换行
edit.addSeparator();//分隔线
edit.add(copy);//复制
edit.add(paste);//粘贴
edit.addSeparator();
edit.add(format);//格式
//将子类添加到菜单条里
menuBar.add(file);//文件
menuBar.add(edit);//编辑
frame.setJMenuBar(menuBar);//设置菜单条
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new demo01().init();
}
}