package com.jcgl.db;import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ttt extends JFrame implements ActionListener{
private JLabel sqlLabel;
private JComboBox sqlComboBox;
JButton jb;
static String text;
public ttt() 
{

}
 public Container douwnMenu(String args0,String []args1)
{
sqlLabel=new JLabel(args0);
sqlComboBox = new JComboBox();
sqlComboBox.setEditable(true);
    jb=new JButton("确定");
    jb.addActionListener(this);

for(int i=0;i<args1.length;i++)
{
sqlComboBox.addItem(args1[i]);
}
sqlComboBox.setBackground(Color.WHITE);
sqlComboBox.setPreferredSize(new Dimension(500,12));
sqlComboBox.addItemListener(new ItemListener() 
{
public void itemStateChanged(ItemEvent event) {
if (event.getStateChange() == ItemEvent.SELECTED){
if(sqlComboBox.getSelectedIndex()==-1){
String currentSQL=(String)event.getItem();
System.out.println("currentSQL : "+currentSQL);
sqlComboBox.addItem(currentSQL);
}
}
}
}); Container cp=getContentPane();
cp.setLayout(new FlowLayout());
cp.add(sqlLabel);
cp.add(sqlComboBox);
cp.add(jb);
pack();
setVisible(true);

addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
System.exit(0);
}
});
return cp;

}public static void main(String[] args){
String []arg={"1111","2222222","3333","444","5555"};
    ttt m=new ttt();
    m.douwnMenu("bookname",arg);
    text=m.sqlComboBox.getSelectedItem().toString();
    text=m.sqlComboBox.getSelectedItem().toString();
System.out.println("=============="+text);
;

    }
private Object getSelectedItem() {
// TODO Auto-generated method stub
return null;
}
public void actionPerformed(ActionEvent arg0) {
if(arg0.getSource()==jb)
{
System.out.println("=============="+text);
}
// TODO Auto-generated method stub

}
}
我自己做的一个测试类,不。管选择那一列,用getSelectedItem()获取总是"1111",怎么样才能显示最新选中的值,
因为要后面要做二级菜单。
在线等,快要毕业答辩了

解决方案 »

  1.   

    你都没有动态获取啊...你只在main函数里获取了两次,当选项改变的时候,你都没有重新改变text的值
    要么这样,点击确定的时候再重新获取值
    if(arg0.getSource()==jb)
    {
    text=sqlComboBox.getSelectedItem().toString(); System.out.println("=============="+text);
    }
    要么就是在选项改变的时候重新获取它的值public void itemStateChanged(ItemEvent event) {
    if (event.getStateChange() == ItemEvent.SELECTED){
    text=sqlComboBox.getSelectedItem().toString(); if(sqlComboBox.getSelectedIndex()==-1){
    String currentSQL=(String)event.getItem();
    System.out.println("currentSQL : "+currentSQL);
    sqlComboBox.addItem(currentSQL);
    }
    }
    }