问题问的有点怪?~~现在只知道,可以获得当前选中的元素值。可是,我要做的东东是,在加入一个元素前,先对当前列表框里的元素进行搜索,当这个将要被加入的元素不存在时,才能加入~这个…… 怎么实现?

解决方案 »

  1.   

    combobox.getItemCount() 返回列表中的项数
    combobox.getItemAt(int index) 返回指定索引处的列表项
    这两个差不多够用了
      

  2.   

    import java.awt.*;
    import javax.swing.*;
    import java.awt.Rectangle;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;/**
     * <p>Title: </p>
     *
     * <p>Description: </p>
     *
     * <p>Copyright: Copyright (c) 2007</p>
     *
     * <p>Company: </p>
     *
     * @author not attributable
     * @version 1.0
     */
    public class Frame3
        extends JFrame {
      public Frame3() {
        try {
          jbInit();
          this.setBounds(0,0,300,200);
          this.setVisible(true);
        }
        catch (Exception exception) {
          exception.printStackTrace();
        }
      }  private void jbInit() throws Exception {
        getContentPane().setLayout(null);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jLabel1.setText("值:");
        jLabel1.setBounds(new Rectangle(175, 55, 39, 15));
        txtValue.setBounds(new Rectangle(201, 56, 66, 17));
        btnAdd.setBounds(new Rectangle(200, 86, 68, 25));
        btnAdd.setText("添加");
        btnAdd.addActionListener(new Frame3_btnAdd_actionAdapter(this));
        jScrollPane1.setBounds(new Rectangle(21, 33, 125, 126));
        this.getContentPane().add(jLabel1);
        this.getContentPane().add(txtValue);
        this.getContentPane().add(btnAdd);
        this.getContentPane().add(jScrollPane1);
        jScrollPane1.getViewport().add(jList1);    dlm.addElement("abc1");
        dlm.addElement("abc2");
        dlm.addElement("abc3");
        this.jList1.setModel(dlm);
      }  public static void main(String[] args) {
        Frame3 frame3 = new Frame3();
      }  JList jList1 = new JList();
      JLabel jLabel1 = new JLabel();
      JTextField txtValue = new JTextField();
      JButton btnAdd = new JButton();
      DefaultListModel dlm=new DefaultListModel();
      JScrollPane jScrollPane1 = new JScrollPane();
      public void btnAdd_actionPerformed(ActionEvent e) {
    //    System.out.println(this.jList1.getModel().getClass());
        DefaultListModel dlm=(DefaultListModel)this.jList1.getModel();
        int rowCount=dlm.getSize();
        for(int i=0;i<rowCount;i++){
          if(dlm.get(i).toString().equals(this.txtValue.getText())){
            JOptionPane.showMessageDialog(this,"该值已经存在!","提示",JOptionPane.WARNING_MESSAGE);
            return ;
          }
        }
        dlm.addElement(txtValue.getText());
        
      }
    }
    class Frame3_btnAdd_actionAdapter
        implements ActionListener {
      private Frame3 adaptee;
      Frame3_btnAdd_actionAdapter(Frame3 adaptee) {
        this.adaptee = adaptee;
      }
      public void actionPerformed(ActionEvent e) {
        adaptee.btnAdd_actionPerformed(e);
      }
    }
    看看是不是你要的!