【问题标题】:Set text size of JComboBox in Swing在 Swing 中设置 JComboBox 的文本大小
【发布时间】:2013-09-13 06:48:40
【问题描述】:
我在 java 中创建了一个组合框(使用 Netbeans)。我想设置列表中每个项目的文本大小,但不知道该怎么做。 (最好我想使用默认字体样式)。
有人知道怎么做吗?
代码片段:
private javax.swing.JComboBox ComboBox_agent = new javax.swing.JComboBox();
ComboBox_agent.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "TCP", "UDP", "Sink", "NULL" }));
【问题讨论】:
标签:
java
swing
fonts
jcombobox
font-size
【解决方案1】:
如果您在 Netbeans GUI 编辑器中创建了 JComboBox,则有一个“字体”字段允许您更改大小。
【解决方案2】:
使用具有适当字体大小的列表单元格渲染组件。此示例使用 20 像素。
import java.awt.*;
import javax.swing.*;
class ShowFonts {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
GraphicsEnvironment ge = GraphicsEnvironment.
getLocalGraphicsEnvironment();
String[] fonts = ge.getAvailableFontFamilyNames();
JComboBox fontChooser = new JComboBox(fonts);
fontChooser.setRenderer(new FontCellRenderer());
JOptionPane.showMessageDialog(null, fontChooser);
});
}
}
class FontCellRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
JLabel label = (JLabel)super.getListCellRendererComponent(
list,value,index,isSelected,cellHasFocus);
Font font = new Font((String)value, Font.PLAIN, 20);
label.setFont(font);
return label;
}
}