菜单条,菜单,菜单项及Swing常用组件的简单总结
菜单条JMenubar,菜单JMenu,菜单项JMenuItem都是JComponent的子类。 菜单条直接放在窗体上,一个窗体上只能有一个菜单条。 方法:setJMenuBar(JMenuBar bar) 将菜单条添加到窗口的顶端。 把菜单放在菜单条上(menubar.add(menu)),菜单中包含可供选择的菜单项,创建JMenuItem对象,加在菜单里。
常用组件: 文本框 JTexField 文本区 JTextArea 按钮 JButton 标签 JLabel 选择框 JCheckBox 单选按钮 JRadioButton //必须加在ButtonGroup上才能单选 下拉列表 JComboBox 密码框 JPasswordField
最基础的东西也要去总结,反复去应用才能在使用它们的时候得心应手。通过下面这个简单程序,可以对常用组件有一个更好的掌握。 package Swing;
import javax.swing.JFrame;
public class Example3 { public static void main(String args) { Componentwindon win=new Componentwindon(); win.setSize(500,500); win.setTitle("常用组建件"); } }
package Swing;
import java.awt.FlowLayout;
import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField;
public class Componentwindon extends JFrame{ JTextField text; JButton button; JCheckBox checkbox1,checkbox2,checkbox3; JRadioButton radio1,radio2; ButtonGroup group; JComboBox comBox; JTextArea area; public Componentwindon(){ init(); setVisible(true); setDefaultCloseOperation(3); } void init(){ setLayout(new FlowLayout()); add(new JLabel("文本框")); text=new JTextField(20); button=new JButton("确定"); add(text); 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();
comBox.addItem("音乐天地");
comBox.addItem("武术天地");
comBox.addItem("象棋乐园");
add(comBox);
add(new JLabel("文本区"));
area=new JTextArea(10,20);
add(new JScrollPane(area));
}
}