|
我的代码如下,请各位指教:
自定义的item类:
- class Item extends Object{
- private String text;
- private int value;
-
- public Item()
- {
- this.text = null;
- this.value = 0;
- }
-
- public Item(String text)
- {
- this.text = text;
- this.value = 0;
- }
-
- public Item(int value,String text)
- {
- this.text = text;
- this.value = value;
- }
-
- public void setValue(int value)
- {
- this.value = value;
- }
-
- public void setText(String text)
- {
- this.text = text;
- }
-
- public int getValue()
- {
- return this.value;
-
- }
- public String getText()
- {
- return this.text;
- }
- }
复制代码
通过继承JComboBox自定义的JDBComboBox类
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import javax.swing.JComboBox;
- import javax.swing.JOptionPane;
- public class JDBComboBox extends JComboBox{
-
- private String SqlString;
- private ResultSet rs;
- private Item Item;
-
- public JDBComboBox(){
- super();
- }
-
- //重写addItem
- public void addItems(String SqlStr){
- this.removeAllItems();
- SqlString = SqlStr;
- Lib DBLib = new Lib();
- ResultSet rs;
- rs = DBLib.getResultSet(SqlStr);
- try{
- while(rs.next()){
- Item = new Item(rs.getInt(1),rs.getString(2));
- /**问题出在这里,加入的是一个String类型,而不是自定义的Item类型
- 但如果用this.addItem(Item)方法,则显示在JDBComboBox中的是乱码*/ this.addItem(Item.getText());
- this.Item.setValue(rs.getInt(1));
- this.Item.setText(rs.getString(2));
- }
- }catch(SQLException e){
- JOptionPane.showMessageDialog(this, e.getMessage(),"错误",JOptionPane.ERROR_MESSAGE);
- }
- }
- public String getText(){
- String Text = ((Item)this.getSelectedItem()).getText();
- return Text;
- }
-
- public int getvalue(){
- int value = ((Item)this.getSelectedItem()).getValue();
- return value;
- }
- }
复制代码
下面是主程序的调用语句:
JDBComboBox CBNodeName = new JDBComboBox();
int i = ((Item)CBNodeName.getSelectedItem()).getValue();
[ 本帖最后由 misscai 于 2008-4-9 19:37 编辑 ] |
|