상세 컨텐츠

본문 제목

자바 JComboBox 콤보 리스트들의 텍스트 말줄임 ELLIPSIS 관련

JAVA/JAVA UI

by AlrepondTech 2020. 9. 15. 14:54

본문

반응형

 

 

 

 

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

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

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

 

 

 

 

 

출처: http://www.java-forums.org/awt-swing/16196-item-too-big-jcombobox.html

 

콤보 박스에서 아래와 같이 설정해 주면 긴 텍스트 문자열 끝부분에 "..." 설정 ELLIPSIS 

되는걸 볼수 있다.

final JComboBox combo = new JComboBox(data);
combo.setPrototypeDisplayValue("Short");
combo.setPrototypeDisplayValue("Short");
combo.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) {
            combo.setToolTipText(value.toString());
            return this;
        }
        setToolTipText(value.toString());
        Rectangle textRect = new Rectangle(combo.getSize().width, getPreferredSize().height);
        String shortText = SwingUtilities.layoutCompoundLabel(this, getFontMetrics(getFont()), value.toString(), null, getVerticalAlignment(), getHorizontalAlignment(), getHorizontalTextPosition(), getVerticalTextPosition(), textRect, new Rectangle(), textRect, getIconTextGap());
        setText(shortText);
        return this;
    }
});

 

[SOLVED] Item too big for JComboBox

Is there a simple way to prevent the JComboBox from resizing in order to display a really long value? I have a combo box that displays the absolute path of a given file. The problem is that paths can get rather long. The panel my combo box is placed in has a minimum size, but no maximum size. So when the user resizes the window, it's possible that the combo box will grow along with the window.

I'd like the combo box to stay within the bounds of the container it's in. Maybe display elipses (...) and when the user hovers over the item, the full text is displayed as a hint. Any ideas?
    1. Join DateSep 2008LocationMadgaon, Goa, IndiaPosts9,904Rep Power16
    2.  
You could try setPrototypeDisplayValue or setPreferredSize/setMaximumSize (which is used depends on your layout manager, which you haven't told us about).

To get better help sooner, post a Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that clearly demonstrates your problem. Link:
SSCCE : Java Glossary

And post the code in code tags.

db
Last edited by DarrylBurke; 02-22-2009 at 03:41 PM.

View, validate and edit X9.37, X9.100-180 and UCD ICL files.
http://www.digertech.com

To the OP, you're far better off going with Darryl's suggestion of changing the component's preferred size or maximum size than forgoing layout managers entirely as suggested by Jason. Neither of these suggestions will show ellipses (...) by default, nor will they show the entire String on mouse hover. To do that, you'll likely need to do some fancy coding including creating a new renderer and a mouse listener that shows a tooltip or a small non-decorated window. Needless to say this will take a bit of work I think.
Displaying tooltips is not too fancy and there's no need for a mouse listener. setToolTipText can be invoked from within the renderer code. Getting ellipses in the values displayed in the drop-down list may be a little fancy though. Im thinking SwingUtilities#layoutCompoundLabel.

EDIT: done, but I sure hope there's a better way ;)

Java Code:

import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.Rectangle;
import javax.swing. *;
public class ShortCombo {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override public void run() {
                new ShortCombo().makeUI();
            }
        });
    }
    public void makeUI() {
        Object[] data = {
            "Longish Data one",
            "Longish Data two",
            "Longish Data three",
            "Longish Data four",
            "Longish Data five"
        };
        final JComboBox combo = new JComboBox(data);
        combo.setPrototypeDisplayValue("Short");
        combo.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) {
                    combo.setToolTipText(value.toString());
                    return this;
                }
                setToolTipText(value.toString());
                Rectangle textRect = new Rectangle(combo.getSize().width, getPreferredSize().height);
                String shortText = SwingUtilities.layoutCompoundLabel(this, getFontMetrics(getFont()), value.toString(), null, getVerticalAlignment(), getHorizontalAlignment(), getHorizontalTextPosition(), getVerticalTextPosition(), textRect, new Rectangle(), textRect, getIconTextGap());
                setText(shortText);
                return this;
            }
        });
        JFrame frame = new JFrame("");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(200, 200);
        frame.setLayout(new FlowLayout());
        frame.setLocationRelativeTo(null);
        frame.add(combo);
        frame.setVisible(true);
    }
}
    1.  
Thanks everyone. My problem was that I had my container in a scrollpane and didn't notice that the horizontal scrollbar was there. Looks like combo boxes automatically implement the ellipses feature when the layout manager forces the box to be smaller than its contents.

 

 

 

 

 

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

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

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

 

 

 

출처: http://www.coderanch.com/t/560277/GUI/java/JComboBox-long-items-rendered-HTML

JComboBox and "long" items rendered via HTML


Usually in this case the "code" is not displayed in the combo box since the user generally doesn't care about the code value that is used to access data in the database. So the user would only see the "description". Then when you program gets the selected Item it can access the code value for further processing. 

However, if you really want to display both values then here are a couple of other options for displaying a multi column combo box that might help: 

import java.awt.*;  
import java.awt.event.*;  
import java.util.*;  
import javax.swing.*;  
import javax.swing.text.*; 

public class ComboBoxMultiColumn extends JFrame {
    public ComboBoxMultiColumn() {
        getContentPane().setLayout(new GridLayout(0, 2));
        Vector items = new Vector();
        items.addElement(new Item("123456789", "Car"));
        items.addElement(new Item("23", "Plane"));
        items.addElement(new Item("345", "Train"));
        items.addElement(new Item("4567", "Nuclear Submarine"));
        // Use a JTextArea as a renderer
        JComboBox comboBox1 = new JComboBox(items);
        comboBox1.setRenderer(new TextAreaRenderer(5));
        getContentPane().add(new JLabel("TextArea Renderer"));
        getContentPane().add(comboBox1);
        // Use a JTextPane as a renderer
        JComboBox comboBox2 = new JComboBox(items);
        comboBox2.setRenderer(new TextPaneRenderer(10));
        getContentPane().add(new JLabel("TextPane Renderer"));
        getContentPane().add(comboBox2);
        // Use a JPanel as a renderer
        JComboBox comboBox3 = new JComboBox(items);
        comboBox3.setRenderer(new PanelRenderer(50));
        getContentPane().add(new JLabel("Panel Renderer"));
        getContentPane().add(comboBox3);
        // Using HTML
        JComboBox comboBox4 = new JComboBox(items);
        comboBox4.setRenderer(new HTMLRenderer());
        getContentPane().add(new JLabel("HTML Renderer"));
        getContentPane().add(comboBox4);
    }
    class Item {
        private String id;
        private String description;
        public Item(String id, String description) {
            this.id = id;
            this.description = description;
        }
        public String getId() {
            return id;
        }
        public String getDescription() {
            return description;
        }
        public String toString() {
            return description;
        }
    }
    public static void main(String[] args) {
        JFrame frame = new ComboBoxMultiColumn();
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }
    /* 
    **  Tabs are easier to use in a JTextArea, but not very flexible 
    */
    class TextAreaRenderer extends JTextArea implements ListCellRenderer {
        public TextAreaRenderer(int tabSize) {
            setTabSize(tabSize);
        }
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            Item item = (Item)value;
            setText(item.getId() + "\t" + item.getDescription());
            setBackground(
                isSelected
                    ? list.getSelectionBackground()
                    : null
            );
            setForeground(
                isSelected
                    ? list.getSelectionForeground()
                    : null
            );
            return this;
        }
    }
    /* 
    **  Tabs are harder to use in a JTextPane, but much more flexible 
    */
    class TextPaneRenderer extends JTextPane implements ListCellRenderer {
        public TextPaneRenderer(int tabColumn) {
            setMargin(new Insets(0, 0, 0, 0));
            FontMetrics fm = getFontMetrics(getFont());
            int width = fm.charWidth('w') * tabColumn;
            TabStop[] tabs = new TabStop[1];
            tabs[0] = new TabStop(width, TabStop.ALIGN_LEFT, TabStop.LEAD_NONE);
            TabSet tabSet = new TabSet(tabs);
            SimpleAttributeSet attributes = new SimpleAttributeSet();
            StyleConstants.setTabSet(attributes, tabSet);
            getStyledDocument().setParagraphAttributes(0, 0, attributes, false);
        }
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            Item item = (Item)value;
            if (index == -1) 
                setText(item.getDescription());
             else 
                setText(item.getId() + "\t" + item.getDescription());
            
            setBackground(
                isSelected
                    ? list.getSelectionBackground()
                    : null
            );
            setForeground(
                isSelected
                    ? list.getSelectionForeground()
                    : null
            );
            return this;
        }
    }
    /* 
    **  Use a panel to hold multiple components 
    */
    class PanelRenderer implements ListCellRenderer {
        private JPanel renderer;
        private JLabel first;
        private JLabel second;
        public PanelRenderer(int firstColumnWidth) {
            renderer = new JPanel();
            renderer.setLayout(new BoxLayout(renderer, BoxLayout.X_AXIS));
            first = new JLabel(" ");
            Dimension d = first.getPreferredSize();
            d.width = firstColumnWidth;
            first.setMaximumSize(d);
            second = new JLabel();
            renderer.add(first);
            renderer.add(second);
        }
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            Item item = (Item)value;
            first.setText(item.getId());
            second.setText(item.getDescription());
            renderer.setBackground(
                isSelected
                    ? list.getSelectionBackground()
                    : null
            );
            renderer.setForeground(
                isSelected
                    ? list.getSelectionForeground()
                    : null
            );
            return renderer;
        }
    }
    /* 
    **  Use HTML to format the text 
    */
    class HTMLRenderer extends DefaultListCellRenderer {
        private static final String START = "<html><table><tr><td width=40>";
        private static final String MIDDLE = "</td><td width=120>";
        private static final String END = "</td></tr></table></html>";
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            Item item = (Item)value;
            setText(START + item.getId() + MIDDLE + item.getDescription() + END);
            return this;
        }
    }
}

 

 

 

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

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

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

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

반응형


관련글 더보기

댓글 영역