下拉列表框组件
Posted 4565892
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了下拉列表框组件相关的知识,希望对你有一定的参考价值。
package com.java.charpter13;
import java.awt.Container;
import java.awt.FlowLayout;
import java.util.concurrent.locks.AbstractOwnableSynchronizer;
import javax.swing.AbstractListModel;
import javax.swing.ComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.WindowConstants;
public class JComBoxModelTest extends JFrame{
private static final long serialVesionUID=1L;
JComboBox<String> jc=new JComboBox<>(new MycomboBox());
JLabel j1=new JLabel("请选择证件");
public JComBoxModelTest()
{
setSize(160, 180);
setVisible(true);
setTitle("在窗口中设置下拉列表 ");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Container cp=getContentPane();
cp.setLayout(new FlowLayout());
cp.add(j1);
cp.add(jc);
}
public static void main(String[] args) {
new JComBoxModelTest();
}
}
class MycomboBox extends AbstractListModel<String> implements ComboBoxModel<String>
{
String selecteditem=null;
String[] test={"身份证","军人证","学生证","工作证"};
@Override
public int getSize() {
// TODO Auto-generated method stub
return test.length;
}
@Override
public String getElementAt(int index) {
// TODO Auto-generated method stub
return test[index];
}
@Override
public void setSelectedItem(Object anItem) {
selecteditem=(String) anItem;
}
@Override
public Object getSelectedItem() {
// TODO Auto-generated method stub
return selecteditem;
}
public int getIndex() {
for (int i = 0; i < test.length; i++) {
if (test[i].equals(getSelectedItem()))
return i;
}
return 0;
}
}
以上是关于下拉列表框组件的主要内容,如果未能解决你的问题,请参考以下文章
java GUI编程(swing)之四swing下拉框,列表框,滚动窗口