|
| 1 | +package org.openapex.samples.misc.swing; |
| 2 | + |
| 3 | +import javax.swing.*; |
| 4 | +import java.awt.*; |
| 5 | +import java.awt.font.FontRenderContext; |
| 6 | +import java.awt.geom.AffineTransform; |
| 7 | +import java.util.Arrays; |
| 8 | + |
| 9 | +public class JComboBoxDynamicWidth57224561 { |
| 10 | + private JFrame f; |
| 11 | + |
| 12 | + public JComboBoxDynamicWidth57224561() { |
| 13 | + f = new JFrame("ComboBox Example"); |
| 14 | + String country[] = {"Long Item 5", "Long Item 2", "Long Item 1", "Long Item 8", "Long Item 4"}; |
| 15 | + String longest = Arrays.stream(country).max((e1, e2) -> e1.length() - e2.length()).get(); |
| 16 | + System.out.println(longest); |
| 17 | + MyDropdown cb = new MyDropdown(country); |
| 18 | + int width = findTextWidth(longest); |
| 19 | + //Graphics2D g = (Graphics2D)f.getGraphics(); |
| 20 | + //cb.setBounds(50, 50, (int)g.getFont().getStringBounds(longest, g.getFontRenderContext()).getWidth()*2 ,20); |
| 21 | + cb.setBounds(50, 50, findTextWidth(longest) * 2, 20); |
| 22 | + f.add(cb); |
| 23 | + f.setLayout(null); |
| 24 | + f.setSize(400, 500); |
| 25 | + f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); |
| 26 | + //f.pack(); |
| 27 | + System.out.println(f.getGraphics()); |
| 28 | + f.setVisible(true); |
| 29 | + } |
| 30 | + |
| 31 | + public static int findTextWidth(String text) { |
| 32 | + AffineTransform affinetransform = new AffineTransform(); |
| 33 | + FontRenderContext frc = new FontRenderContext(affinetransform, true, true); |
| 34 | + Font font = new Font("Lucida Grande", Font.PLAIN, 13); |
| 35 | + return (int) (font.getStringBounds(text, frc).getWidth()); |
| 36 | + } |
| 37 | + |
| 38 | + public static void main(String[] args) { |
| 39 | + new JComboBoxDynamicWidth57224561(); |
| 40 | + } |
| 41 | + |
| 42 | + private static class MyDropdown extends JComboBox { |
| 43 | + private boolean layoutInProgress = false; |
| 44 | + |
| 45 | + public MyDropdown(Object[] items) { |
| 46 | + super(items); |
| 47 | + } |
| 48 | + |
| 49 | + public void doLayout() { |
| 50 | + layoutInProgress = true; |
| 51 | + try { |
| 52 | + super.doLayout(); |
| 53 | + } finally { |
| 54 | + layoutInProgress = false; |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + public Dimension getSize() { |
| 59 | + Dimension dimension = getSize(); |
| 60 | + if (!layoutInProgress) { |
| 61 | + dimension.width = Math.max(dimension.width, super.getPreferredSize().width); |
| 62 | + } |
| 63 | + return dimension; |
| 64 | + } |
| 65 | + } |
| 66 | +} |
0 commit comments