按钮JButton,单选按钮JRadioButton,复选框JCheckBox
1、按钮JButton
public class Demo extends JFrame { public Demo() { setBounds(100, 100, 400, 200); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); Container c = getContentPane(); c.setLayout(new GridLayout(2, 3, 10, 10)); JButton btn[] = new JButton[6];//定义6个按钮数组 for (int i = 0; i < btn.length; i++) { btn[i] = new JButton();//创建按钮 c.add(btn[i]); } btn[0].setText("不可用"); btn[0].setEnabled(false); btn[1].setText("背景色"); btn[1].setBackground(Color.GREEN); btn[2].setText("无边框"); btn[2].setBorderPainted(false); btn[3].setText("有边框"); btn[3].setBorder(BorderFactory.createLineBorder(Color.RED)); setVisible(true); Icon icon=new ImageIcon("src/logo.png"); btn[4].setIcon(icon);//给按钮设置图片 btn[4].setToolTipText("图片按钮");//鼠标悬停提示 btn[5].setText("弹出提示框"); btn[5].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(Demo.this,"这是消息提示框"); } }); } public static void main(String[] args) { new Demo(); } }
2、单选按钮JRadioButton
public class Demo extends JFrame { public Demo() { setBounds(100, 100, 200, 100); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); Container c = getContentPane(); c.setLayout(new FlowLayout()); JRadioButton rb1 = new JRadioButton("男"); JRadioButton rb2 = new JRadioButton("女"); c.add(rb1); c.add(rb2); ButtonGroup group=new ButtonGroup();//按钮组,使按钮单选,而不被同时选中 group.add(rb1); group.add(rb2); rb1.setSelected(true);//默认选中 setVisible(true); } public static void main(String[] args) { new Demo(); } }
3、复选框JCheckBox
public class Demo extends JFrame { public Demo() { setBounds(100, 100, 200, 100); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); Container c = getContentPane(); c.setLayout(new FlowLayout()); JCheckBox cb1=new JCheckBox("桔子"); JCheckBox cb2=new JCheckBox("苹果"); JCheckBox cb3=new JCheckBox("香蕉"); cb1.setSelected(true);//默认选中 c.add(cb1);c.add(cb2);c.add(cb3); setVisible(true); } public static void main(String[] args) { new Demo(); } }