gpt4 book ai didi

java - 缩放 JCheckBox 框

转载 作者:行者123 更新时间:2023-11-29 05:25:54 25 4
gpt4 key购买 nike

我想缩放一个 JCheckBox 例如与其设置的文本的字体大小相同。例如,当我增加 Font 大小时,复选框本身保持很小,但它应该随着文本增长,或者我想自己设置框的大小:

JCheckBox chckbxTest = new JCheckBox("Test");
chckbxTest.setFont("Arial", Font.BOLD, 27));

如果可能,我需要为 JRadioButton 提供相同的功能。不幸的是,我还没有找到关于此功能的任何文档。


解决方案:
标记的答案帮助我创建了一个完全可扩展的自己样式的 JCheckbox。下面的示例绘制了一个简单的矩形,选中时用另一个矩形填充:

    [...]
JCheckBox myCheckBox = new JCheckBox("Test");
myCheckBox.setIcon(new SimpleCheckboxStyle(20));
[...]

class SimpleCheckboxStyle implements Icon {

int dim = 10;

public SimpleCheckboxStyle (int dimension){
this.dim = dimension;
}

protected int getDimension() {
return dim;
}

public void paintIcon(Component component, Graphics g, int x, int y) {
ButtonModel buttonModel = ((AbstractButton) component).getModel();

int y_offset = (int) (component.getSize().getHeight() / 2) - (int) (getDimension() / 2);
int x_offset = 2;

if (buttonModel.isRollover()) {
g.setColor(new Color(0, 60, 120));
} else if (buttonModel.isRollover()) {
g.setColor(Color.BLACK);
} else {
g.setColor(Color.DARK_GRAY);
}
g.fillRect(x_offset, y_offset, fontsize, fontsize);
if (buttonModel.isPressed()) {
g.setColor(Color.GRAY);
} else if (buttonModel.isRollover()) {
g.setColor(new Color(240, 240, 250));
} else {
g.setColor(Color.WHITE);
}
g.fillRect(1 + x_offset, y_offset + 1, fontsize - 2, fontsize - 2);
if (buttonModel.isSelected()) {
int r_x = 1;
g.setColor(Color.GRAY);
g.fillRect(x_offset + r_x + 3, y_offset + 3 + r_x, fontsize - (7 + r_x), fontsize - (7 + r_x));
}
}

public int getIconWidth() {
return getDimension();
}

public int getIconHeight() {
return getDimension();
}
}

最佳答案

For example when i increase the Font size the checkbox itself stays small but it should grow with the text or i want to set the size of the box myself

然后您需要为文本的字体大小提供自定义图标。请参阅以下方法:

setIcon(....)
setSelectedIcon(...)

您需要对 JRadioButton 执行相同的操作。此外,您需要为每个 LAF 使用不同的图标。

关于java - 缩放 JCheckBox 框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22691353/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com