单选按钮控制颜色
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RadioDemo {
public static void main(String[] args) {
new MyRadio();
}
}
class MyRadio extends JFrame{
JRadioButton rad1,rad2;
JPanel jp,jp2;
ButtonGroup bg;
public MyRadio(){
bg=new ButtonGroup();
rad1=new JRadioButton("绿色");
rad2=new JRadioButton("红色");
rad1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
jp2.setBackground(Color.red);
}});
rad2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
jp2.setBackground(Color.green);
}});
bg.add(rad1);
bg.add(rad2);
jp=new JPanel();
jp2=new JPanel();
add(jp2);
jp.add(rad1);
jp.add(rad2);
add(jp,"South");
jp2.setBackground(Color.blue);
this.setLocation(300, 200);
this.setSize(300,200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
}
下拉框组件
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ComboDemo {
public static void main(String[] args) {
new MyCombo();
}
}
class MyCombo extends JFrame{
JPanel jp;
JComboBox comb;
JTextField jtf;
public MyCombo(){
jp=new JPanel();
comb=new JComboBox();
comb.addItem("请选择城市");
comb.addItem("北京");
comb.addItem("上海");
comb.addItem("天津");
comb.addItem("南京");
ActionListener m=new ActionListener(){
public void actionPerformed(ActionEvent e){
String item=(String)comb.getSelectedItem();
if("请选择城市:".equals(item));
jtf.setText("");
jtf.setText("你选择的城市是:"+item);
}};
comb.addActionListener(m);
jtf=new JTextField(12);
add(jp,BorderLayout.PAGE_START);
jp.add(comb);
jp.add(jtf);
this.setLocation(300,200);
this.setSize(350,200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
}
菜单组件
package lianxi;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Menu {
public static void main(String[] args) {
}
}
class MyMenu extends JFrame{
JMenuBar bar;
JMenu menu1,menu2,menu3;
JMenuItem item1,item2,item3,item4;
public MyMenu(String title){
super(title);
init();
}
public void init(){
bar=new JMenuBar();
menu1=new JMenu("文件(F)");
menu2=new JMenu("帮助");
menu3=new JMenu("子菜单");
item1=new JMenuItem("新建");
item1=new JMenuItem("退出");
item3=new JMenuItem("复制");
item4=new JMenuItem("剪切");
menu1.add(item1);
menu1.add(item2);
menu1.insertSeparator(1);
menu2.add(menu3);
menu3.add(item3);
menu3.add(item4);
bar.add(menu1);
bar.add(menu2);
this.setJMenuBar(bar);
this.setLocation(300, 200);
this.setSize(350,200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
}