如何改变JComboBox的字体

我想更改 JComboBox 的字体大小。但是,只有未选择的项目会发生变化,就像那样:


https://imgur.com/a/WnnyPA6


所以我希望所选项目也加粗。


我做了一个像这样的自定义组合框类:


public class CustomComboBox extends JLabel implements ListCellRenderer {

    public Component getListCellRendererComponent(

            JList list, 

            Object value, 

            int index, 

            boolean isSelected, 

            boolean cellHasFocus) {


        JLabel label = new JLabel(){

            public Dimension getPreferredSize(){

                return new Dimension(200, 80);

            }       

        };

        label.setText(String.valueOf(value));

        label.setFont(new Font("Serif", Font.BOLD, 30));


        return label;

    }

}


摇曳的蔷薇
浏览 166回答 2
2回答

慕森卡

您可以简单地为组合框设置字体。是这样的:import java.awt.Dimension;import java.awt.Font;import javax.swing.JComboBox;import javax.swing.JFrame;import javax.swing.SwingUtilities;import javax.swing.WindowConstants;import javax.swing.plaf.basic.BasicComboBoxRenderer;/**&nbsp;* <code>ComboTest</code>.&nbsp;*/public class ComboTest {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; SwingUtilities.invokeLater(new ComboTest()::startUp);&nbsp; &nbsp; }&nbsp; &nbsp; private void startUp() {&nbsp; &nbsp; &nbsp; &nbsp; JComboBox<String> combo = new JComboBox<>(new String[] {"A", "B", "C"});&nbsp; &nbsp; &nbsp; &nbsp; combo.setFont(new Font("Serif", Font.BOLD, 30));&nbsp; &nbsp; &nbsp; &nbsp; combo.setRenderer(new ComboRenderer());&nbsp; &nbsp; &nbsp; &nbsp; JFrame frm = new JFrame("Combo test");&nbsp; &nbsp; &nbsp; &nbsp; frm.add(combo);&nbsp; &nbsp; &nbsp; &nbsp; frm.pack();&nbsp; &nbsp; &nbsp; &nbsp; frm.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);&nbsp; &nbsp; &nbsp; &nbsp; frm.setLocationRelativeTo(null);&nbsp; &nbsp; &nbsp; &nbsp; frm.setVisible(true);&nbsp; &nbsp; }&nbsp; &nbsp; private static class ComboRenderer extends BasicComboBoxRenderer {&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; public Dimension getPreferredSize() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return new Dimension(200, 80);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}当我的建议对您的情况没有帮助时,请创建一个小的可运行示例,以便我们也可以启动和调试它。

料青山看我应如是

您可以使用 combo.setFont(new FontUIResource("Roboto",Font.PLAIN,12); 为组合框设置字体。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java