天天看點

Java 下拉清單

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPasswordField;

class text2 extends JFrame{
	
	public text2() {
		// TODO Auto-generated constructor stub
		setBounds(400, 100, 400, 100);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		
		Container container = getContentPane();
		container.setLayout(null);
		
		
		//向下拉清單添加資料
//		JComboBox<String> comboBox = new JComboBox<>();
//		comboBox.addItem("身份證");
//		comboBox.addItem("學生證");
//		comboBox.addItem("工作證");

//		String string[] = {"1","2","3"};
//		JComboBox<String> comboBox = new JComboBox<>(string);
		
		
		String string[] = {"身份證","學生證","工作證"};
		JComboBox<String> comboBox = new JComboBox<>();
		ComboBoxModel comboBoxModel = new DefaultComboBoxModel<>(string);//建立下拉清單模型
		comboBox.setModel(comboBoxModel);//向清單中添加資料模型
		
		JButton jButton = new JButton("列印");
		jButton.setBounds(120, 5, 100, 30);//設定按鈕分布大小
		container.add(jButton);
		jButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				System.out.println(comboBox.getSelectedIndex());//擷取選中的索引
				System.out.println(comboBox.getSelectedItem());//擷取選中的項
				
			}
		});
		
		comboBox.setEditable(true);//設定可以編輯
		
		comboBox.setBounds(10, 10, 100, 21);
		container.add(comboBox);
		
		setVisible(true);
	}
	
	public static void main(String[] args) {
		new text2();
	}
}           

複制