package com.lzw;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CheckBoxTest extends JFrame{
/**
* 複選框
*/
private static final long serialVersionUID = 1L;
private JPanel panel1 = new JPanel();
private JPanel panel2 = new JPanel();
private JTextArea jt=new JTextArea(3,10);
private JCheckBox jc1=new JCheckBox("1");
private JCheckBox jc2=new JCheckBox("2");
private JCheckBox jc3=new JCheckBox("3");
public CheckBoxTest(){
Container c=getContentPane();
setSize(200,160);
setVisible(true);
setTitle("複選框的使用");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
c.setLayout(new BorderLayout());
c.add(panel1, BorderLayout.NORTH);
final JScrollPane scrollPane = new JScrollPane(jt);
panel1.add(scrollPane);
c.add(panel2, BorderLayout.SOUTH);
panel2.add(jc1);
jc1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(jc1.isSelected())
jt.append("複選框1被選中\n");
}
});
panel2.add(jc2);
jc2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(jc2.isSelected())
jt.append("複選框2被選中\n");
}
});
panel2.add(jc3);
jc3.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(jc3.isSelected())
jt.append("複選框3被選中\n");
}
});
}
public static void main(String[] args) {
new CheckBoxTest();
}
}
下拉列表
package com.lzw;
import java.awt.*;
import javax.swing.*;
public class JComboBoxModelTest extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
JComboBox<String> jc = new JComboBox<>(new MyComboBox());
JLabel jl = new JLabel("請選擇證件:");
public JComboBoxModelTest() {
setSize(new Dimension(160, 180));
setVisible(true);
setTitle("在窗口中設置下拉列表框");
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
cp.add(jl);
cp.add(jc);
}
public static void main(String[] args) {
new JComboBoxModelTest();
}
}
class MyComboBox extends AbstractListModel<String> implements ComboBoxModel<String> {
/**
*
*/
private static final long serialVersionUID = 1L;
String selecteditem = null;
String[] test = { "身份證", "軍人證", "學生證", "工作證" };
public String getElementAt(int index) {
return test[index];
}
public int getSize() {
return test.length;
}
public void setSelectedItem(Object item) {
selecteditem = (String) item;
}
public Object getSelectedItem() {
return selecteditem;
}
public int getIndex() {
for (int i = 0; i < test.length; i++) {
if (test[i].equals(getSelectedItem()))
return i;
}
return 0;
}
}