상세 컨텐츠

본문 제목

자바 Setting the text field in editable JComboBox 커스텀 라벨, 에디터

JAVA/JAVA UI

by AlrepondTech 2020. 9. 15. 14:57

본문

반응형
728x170

 

 

=================================

=================================

=================================

 

 

 

출처: 여기

void setUI() {
    JComboBox _diagrams = new JComboBox() {
        @Override public Object getSelectedItem() { // TODO Auto-generated method stub
            ItemDiagrams itm = (ItemDiagrams)super.getSelectedItem();
            if (itm != null) {
                return itm.getText();
            }
            return null;
        }
    };
    this.add(_diagrams, new GridBagConstraints(1, 8, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
    // _diagrams.setModel(jComboBox1Model);
    _diagrams.setFont(new java.awt.Font("Arial", 0, 11));
    _diagrams.setActionCommand("DIAGRAMS");
    _diagrams.setPrototypeDisplayValue("Short");
    _diagrams.setRenderer(new DefaultListCellRenderer() {
        @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            if (index == -1) {
                _diagrams.setToolTipText(value.toString());
                return this;
            }
            ItemDiagrams item = (ItemDiagrams)value;
            setToolTipText(item.getText());
            int arrowWidthSiz = 30;
            Rectangle textRect = new Rectangle(_diagrams.getSize().width - arrowWidthSiz, getPreferredSize().height);
            String shortText = SwingUtilities.layoutCompoundLabel(this, getFontMetrics(getFont()), item.getText(), null, getVerticalAlignment(), getHorizontalAlignment(), getHorizontalTextPosition(), getVerticalTextPosition(), textRect, new Rectangle(), textRect, getIconTextGap());
            setText(shortText);
            return this;
        }
    });
}
// 밑에 아이템 리스트를 추가해준 아이템을 넣어준다.
public void addDiagram(String dia) {
    _diagrams.addItem(new ItemDiagrams(dia);
}
class ItemDiagrams {
    private String _text = "";
    private String _textShort = "";
    private Icon icon;
    private String text;
    public ItemDiagrams(Icon icon, String text) {
        this.icon = icon;
        this.text = text;
    }
    public ItemDiagrams(String text) {
        this._text = text;
    }
    public Icon getIcon() {
        return icon;
    }
    public String getText() {
        if (_textShort.length() > 0) {
            return _textShort;
        }
        return _text;
    }
    public void setShortText(String txt) {
        _textShort = txt;
    }
}

 

 

=================================

=================================

=================================

 

 

 

출처: http://stackoverflow.com/questions/10776416/setting-the-text-field-in-editable-jcombobox-from-custom-render

 

Setting the text field in editable JComboBox from custom render

up vote-1down votefavorite







Both comboBox use the same code, the only exeption is that "combo 1" is set as editable and "Combo 2" is not. Both have "item 1" selected. As you can see, "Combo 1" is printing "[Ljava.lang.Object;@77905258" in the combo text feild and "Combo 2" print the selected name.
How can "Combo 1" print the same text in the combo box text feild as "Combo 2"?
To comply with E:(refer to attached image) If you click on "Combo 1" you will see the list of item 1, item 2... But the Text feild will show "[Ljava.lang.Object;@77905258" when item is selected (here it is item 1 that is selected).
If you click on "Combo 2" you will see the list of item 1, item 2... And the non-editable Text feild will show "item 1" when "item 1" is selected.
Here is the code:
I'm using a custom renderer:
Here is the code to set the 2 combo boxes list:
Here is the code of the events. This set the text feilds per selected item:
Here is the full code that can be cut and past to Comply with SC and C. Do not forget to add the custom renderer "MyListRenderer" class. (compiled with NetBean 7.1) :
java swing jcombobox


show 5 more comments

2 Answers

activeoldestvotes

up vote2down vote Renderer(the same concept for JTable, JList and JComboBox too) is for formatting value that already exist (Color, Font, Background, Foreground), don't add, put, change or modifywhatever inside Renderer
put data as Items to the JComboBox directly, in your case to update the ComboBoxModel, noticeadd, put, change or modify must be done on Event Dispatch Thread

up vote0down vote Finally...To accomplish this, I had to add a basic custom ComboBox editor and set the custom editor to my combobox in my original code (included in my question):
The custom Combo Box Editor class need to implement ComboBoxEditor. i had 6 method to override. But here are the 3 main one. In getEditorComponent, i return a text feild, but i could return any type of component.
Then I set the text in the textFeild as per my selected object data[1] in setItem() (note that I’m keeping my original objet to be return later "myReturnObject"):
I then return the original object if it selected from list or a custom object if the text feild has been edited.
This is a lot of work for a combo box, but it worth it in my case. Hope this can help someone else.
Here are referance for this work: http://www.java2s.com/Code/Java/Swing-JFC/AfancyexampleofJComboBoxwithacustomrendererandeditor.htmhttp://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html Here is the full code for the custom combo editor "MyComboEditor()":
 

 

 

 

=================================

=================================

=================================

 

 

반응형
그리드형


관련글 더보기

댓글 영역