是否有一种外观独立的方式来将组件(例如 a JLabel
)与a的文本JCheckBox
水平对齐?
我正在尝试使用 中的值UIDefaults
来预测文本相对于JCheckBox
. 我找到了一种组合,可以为 Metal、Windows、Motif 和 Aqua 外观提供正确的结果:
但不在 Nimbus 中:
是否有一种实用方法可以可靠地为所有外观中的文本提供 X、Y 偏移?
代码(注意:为避免任何布局副作用,我在此测试中使用了空布局):
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;
}