1

Имеется обычный JComboBox и кнопка JButton, по нажатию которой необходимо вернуть выбранный из списка элемент. В качестве элементов JComboBox там содержится список элементов класса Item, к котором определено некое поле private String name.

При отображении в JComboBox элементы записаны в виде pack.pack1.Item@###### , т.е. как я понимаю, используется метод toString. Если использовать метод getSelectedItem() из JComboBox то при нажатии кнопки получаем на выходе элемент класса Item.

Такой подход не совсем подходит, т.к. отображение не совсем корректно выглядит. Если же в классе Item переопределять toString(), и в нем прописывать getName(), то при использовании getSelectedItem() получаем объект типа String.

Как можно решить данную проблемы: чтобы при отображении приписывалось содержимое поля name, а при нажатии на кнопку получали объект класса Item? Была идея как-то через Map попробовать, но может есть какое-то более хорошее решение?

public class ChooseHashtagsPanel extends JPanel {

private JComboBox comboBox;

private HashtagController controller;

public ChooseHashtagsPanel(HashtagController hashtagController){
    super();
    this.controller = hashtagController;
    this.setBorder(new TitledBorder("Choose hashtags"));
    this.setBounds(20, 240, 340, 70);
    this.setLayout(new GridLayout(1, 3));

    JLabel label = new JLabel("Choose tag");

    //TODO set mapping of hashtags in (completed)
    //TODO Change dummy
    Searchable<Hashtag, String> s = new HashtagSearchable(hashtagController);
    comboBox = new AutocompleteJComboBox(s);
    JButton button = new JButton("Choose Hashtag");
    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("Choosen: " + ((Hashtag)comboBox.getSelectedItem()).getTagname());
        }
    });

    this.add(label);
    this.add(comboBox);
    this.add(button);
}

}

Сам ComboBox:

public class AutocompleteJComboBox extends JComboBox {

    private final Searchable<Hashtag, String> searchable;

    public AutocompleteJComboBox(final Searchable<Hashtag, String> searchable1){
        super();
        this.searchable = searchable1;
        setModel(new DefaultComboBoxModel());
        setEditable(true);
        Component c = getEditor().getEditorComponent();
        if ( c instanceof JTextComponent){
            final JTextComponent tc = (JTextComponent)c;
            tc.getDocument().addDocumentListener(new DocumentListener(){
                @Override
                public void changedUpdate(DocumentEvent arg0) {
                }
                @Override
                public void insertUpdate(DocumentEvent arg0) {
                    System.out.println("ACTION!insertUpdate " + arg0.getDocument().toString());
                    update();
                }
                @Override
                public void removeUpdate(DocumentEvent arg0) {
                    System.out.println("ACTION!removeUpdate " + arg0.getDocument().toString());
                    update();
                }
                public void update(){
                    //perform separately, as listener conflicts between the editing component
                    //and JComboBox will result in an IllegalStateException due to editing
                    //the component when it is locked.
                    SwingUtilities.invokeLater(new Runnable(){
                        @Override
                        public void run() {
                            System.out.println("public void run() text " + tc.getText());
                            java.util.List<Hashtag> founds = new ArrayList<Hashtag>(searchable.search(tc.getText()));
                            Set<Hashtag> foundSet = new HashSet<Hashtag>();

                            for ( Hashtag s : founds ){
                                foundSet.add(s);
                            }
                            //Collections.sort(founds);//sort alphabetically
                            setEditable(false);
                            removeAllItems();
                            //if founds contains the search text, then only add once.
                            if ( !foundSet.contains( tc.getText().toLowerCase()) ){
                                addItem( tc.getText() );
                            }
                            for (Hashtag s : founds) {
                                addItem(s);
                            }
                            setEditable(true);
                            setPopupVisible(true);
                        }
                    });
                }
            });
            //When the text component changes, focus is gained
            //and the menu disappears. To account for this, whenever the focus
            //is gained by the JTextComponent and it has searchable values, we show the popup.
            tc.addFocusListener(new FocusListener() {
                @Override
                public void focusGained(FocusEvent arg0) {
                    System.out.println("public void focusGained");
                    if (tc.getText().length() > 0) {
                        setPopupVisible(true);
                    }
                }

                @Override
                public void focusLost(FocusEvent arg0) {
                    System.out.println("public void focusLost");
                }
            });
        }else{
            throw new IllegalStateException("Editing component is not a JTextComponent!");
        }
    }
}
3
  • проблема понятна, но можно чуть-чуть кода?
    – dirkgntly
    25 янв 2016 в 7:35
  • 1
    Swing сильно устарел, в следующий раз попробуй освоить javafx, он будет поновее, получше. 25 янв 2016 в 7:54
  • @АлексейПересторонин, да, как раз думал между swing и fx, но просто swing это считай как азы, поэтому решил остановиться на это библиотеке)
    – I. Smirnov
    25 янв 2016 в 8:03

1 ответ 1

1

Переопределяйте метод toString() в классе, который помещаете в JComboBox, чтобы он возвращал то, что вам нужно(name). Типизировать JComboBox не нужно дженериком. При вызове нажатия на кнопку вызывайте просто каст:

...............
class A{
   public String name;
   public String descr;

   @Override
   public String toString() {
      return name;
   }
}
...................
A a1 = new A();
a1.name("Элкемент 1");
a1.descr("Нечто");
jComboBox1.addItem(a1);
...............
A a = (A) jComboBox1.getSelectedItem();
System.out.println(a.descr)
.....................

Где А - ваш класс. И получите в итоге весь объект. А отображение должно быть в порядке.

Полный пример

public class TestFrame extends javax.swing.JFrame {

    private class A {

        public String name;
        public String desrc;

        @Override
        public String toString() {
            return name;
        }
    }

    /**
     * Creates new form TestFrame
     */
    public TestFrame() {
        initComponents();
        jComboBox1.removeAllItems();;
        A a1 = new A();
        a1.name = "Test";
        a1.desrc = "Hello";
        jComboBox1.addItem(a1);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jComboBox1 = new javax.swing.JComboBox();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jButton1.setText("jButton1");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 162, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(26, 26, 26)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(83, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addContainerGap(266, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        System.out.println(((A) jComboBox1.getSelectedItem()).desrc);
    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TestFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TestFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TestFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TestFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new TestFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JComboBox jComboBox1;
    // End of variables declaration                   
}
6
  • так там же ClassCastException вылетать будет. Это был второй мой описанный вариант.
    – I. Smirnov
    25 янв 2016 в 9:09
  • Добавил полный пример. У меня не вылетает. Попробуйте скомпилировать и запустить у себя
    – chubatiy
    25 янв 2016 в 9:32
  • По всем видимости ошибка была в том, что setModel для JComboBox не использовался. Подправил у себя ошибки нет.
    – I. Smirnov
    25 янв 2016 в 9:57
  • Хорошо, что получилось)
    – chubatiy
    25 янв 2016 в 10:08
  • Странно, но после того, как вроде бы все исправно заработало, запустил еще раз а в итоге опять получил эксепшн) странно как-то.. да и похоже, что дело не в setModel, а вот понять в чем именно не могу
    – I. Smirnov
    25 янв 2016 в 12:39

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.