请来看看我的一个Swing小问题

llm0528 2009-07-08 10:25:47
我将JComboBox做了一些改动(即第2段代码,没改动过的可以),然后想得到我所选择项的值(也就是文字),但是我试了好几种方法,都没有办法将选项值取出。所以发贴问问大家,我只找到了一个替代方法,就是读取 SelectedIndex 然后再对比再输出,那我还是希望得到的是其String 得形式,下面代码的方法1 就是得到数字,方法2就是得到String但是会出错。

public class Test2 extends JFrame {
static Object[][] item = {{"A", Color.BLUE, Color.WHITE},{"B", Color.BLUE, Color.WHITE},
{"C", Color.BLUE, Color.WHITE}};
static JComboBox comboBox = null;

public Test2(){
comboBox = new JComboBox(item);
comboBox.setRenderer(new ComboBoxListCellRenderer());
comboBox.setBackground(Color.white);
this.add(comboBox, BorderLayout.NORTH);

comboBox.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//方法1: int s = ((JComboBox)e.getSource()).getSelectedIndex();
//方法2: String s = (String)((JComboBox)e.getSource()).getSelectedItem();
// System.out.println(s);
}
});
}

public static void main(String[] args){
Test2 test2 = new Test2();
test2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
test2.setSize(200, 100);
test2.setVisible(true);
}
}


public class ComboBoxListCellRenderer implements ListCellRenderer{
DefaultListCellRenderer defaultRanderer = new DefaultListCellRenderer();

public Component getListCellRendererComponent(JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus){

String theText = null;
Color backGround = null;
Color foreGround = null;

JLabel renderer = (JLabel)defaultRanderer.getListCellRendererComponent(list,
value, index, isSelected, cellHasFocus);
if(value instanceof Object[]){
Object[] values = (Object[])value;
theText = (String)values[0];
backGround = (Color)values[1];
foreGround = (Color)values[2];
}
if(isSelected){
renderer.setBackground(backGround);
renderer.setForeground(foreGround);
}
renderer.setText(theText);
list.setSelectionBackground(Color.WHITE);
return renderer;
}
}
...全文
58 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
llm0528 2009-07-09
  • 打赏
  • 举报
回复
呵呵,主要是我想要的是字符串形式的结果,像我添加了A、B、C,我想得到的还是 A B C, 主要是我想对选择的结果进行比较。
而且哦,如果是个默认的JComboBox 就可以用方法2的方式得到结果。(即便通过一个 JTextField.setText(方法2) 也可以)
diggywang 2009-07-09
  • 打赏
  • 举报
回复
不管是在,用String a =(String)otherObj方式获取String字符串并赋值的时候,otherObj必须是一个String对象才可以,否则是无法转换的,向JTextField里的setText,getText之类就是如此。
diggywang 2009-07-09
  • 打赏
  • 举报
回复
Object型不能强制转换成String,应该这样写:

//方法2:
String s = ((JComboBox)e.getSource()).getSelectedItem().toString();

62,621

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧