fin*_*nnw 8 java swing jcheckbox
是否有一个外观和感觉无关对准组件的方式(例如JLabel)水平与文本的JCheckBox?
我试图使用来自的值UIDefaults来预测文本相对于左上角的位置JCheckBox.我找到了一个组合,可以为Metal,Windows,Motif和Aqua Look-and-Feels提供合适的结果:

但不是在Nimbus:

是否有某种实用方法能够可靠地为所有外观中的文本提供X,Y偏移量?
代码(注意:为避免任何布局副作用,我在此测试中使用了null布局):
import java.awt.Insets;
import javax.swing.JApplet;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.UIManager;
import javax.swing.border.Border;
public class AlignCheckBoxText extends JApplet {
public AlignCheckBoxText() {
setLayout(null);
checkBox = new JCheckBox("Hello, World!");
label = new JLabel("Hello, World!");
add(checkBox);
add(label);
}
@Override
protected void validateTree() {
checkBox.setLocation(0, 0);
checkBox.setSize(checkBox.getPreferredSize());
int labelX = UIManager.getIcon("CheckBox.icon").getIconWidth();
Insets cbInsets = UIManager.getInsets("CheckBox.margin");
if (cbInsets != null) labelX += cbInsets.left + cbInsets.right;
Border cbBorder = UIManager.getBorder("CheckBox.border");
if (cbBorder != null) {
Insets borderInsets = cbBorder.getBorderInsets(checkBox);
if (borderInsets != null) {
labelX += borderInsets.left;
}
}
label.setLocation(labelX, checkBox.getHeight());
label.setSize(label.getPreferredSize());
super.validateTree();
}
private JCheckBox checkBox;
private JLabel label;
}
Run Code Online (Sandbox Code Playgroud)
(致OP:请不接受我之前的错误答案,我将删除它。抱歉!)
您可以使用不为标签绘制复选框的复选框。这适用于 Windows JDK6 中的所有 LAF,包括 Nimbus。我没有 Mac,所以无法测试 Aqua。
class CheckBoxLabel extends JCheckBox
{
public CheckBoxLabel(String string)
{
super(string);
}
public void updateUI()
{
setUI(new CheckBoxLabelUI());
}
}
class CheckBoxLabelUI extends BasicCheckBoxUI
{
public void installUI(JComponent c)
{
super.installUI(c);
Icon i = super.getDefaultIcon();
icon_ = new EmptyIcon(i.getIconWidth(), i.getIconHeight());
}
public Icon getDefaultIcon()
{
return icon_;
}
private Icon icon_;
}
class EmptyIcon implements Icon
{
public EmptyIcon()
{
this(0, 0);
}
public EmptyIcon(int width, int height)
{
width_ = width;
height_ = height;
}
public int getIconHeight()
{
return height_;
}
public int getIconWidth()
{
return width_;
}
public void paintIcon(Component c, Graphics g, int x, int y)
{
}
private int width_;
private int height_;
}
Run Code Online (Sandbox Code Playgroud)