Java JComboBox set size based on font size

Description

Java JComboBox set size based on font size

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.FontMetrics;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

class Demo extends JPanel {
  public Demo() {

    String options[] = { "CSS", "HTML", "Java", "Javascript" };
    setLayout(new FlowLayout());
    JComboBox<String> jcb = new JComboBox<String>(options);

    FontMetrics fm = jcb.getFontMetrics(jcb.getFont());
    jcb.setPreferredSize(new Dimension(150, fm.getHeight()));
    jcb.setMinimumSize(new Dimension(75, fm.getHeight()));

    add(jcb);/*  w w  w.java  2s. c om*/

    jcb.setSelectedIndex(1);
  }
}

public class Main {
  public static void main(String[] args) {
    Demo panel = new Demo();
    JFrame application = new JFrame();
    application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    application.add(panel);
    application.setSize(250, 250);
    application.setVisible(true);
  }
}



PreviousNext

Related