簡體   English   中英

如何更改JComboBox的字體

[英]How to change font of 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;
    }
}

您可以簡單地為組合框設置字體。 像這樣:

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;

/**
 * <code>ComboTest</code>.
 */
public class ComboTest {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new ComboTest()::startUp);
    }

    private void startUp() {
        JComboBox<String> combo = new JComboBox<>(new String[] {"A", "B", "C"});
        combo.setFont(new Font("Serif", Font.BOLD, 30));
        combo.setRenderer(new ComboRenderer());
        JFrame frm = new JFrame("Combo test");
        frm.add(combo);
        frm.pack();
        frm.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        frm.setLocationRelativeTo(null);
        frm.setVisible(true);
    }

    private static class ComboRenderer extends BasicComboBoxRenderer {

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 80);
        }
    }
}

如果我的建議對您的情況沒有幫助,請創建一個小的可運行示例,以便我們也可以啟動和調試它。

您可以使用combo.setFont(new FontUIResource(“ Roboto”,Font.PLAIN,12);為組合框設置字體。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM