这就是我设法使用 JCheckBox 作为父类来实现它的方法。这是缺少设置标签文本和颜色的方法。
package mock.dlect;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.LayoutManager;
import javax.swing.Icon;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
public class LeftRightCheck extends JCheckBox {
private final static JCheckBox DEFAULT_CHECK_BOX = new JCheckBox();
private final JLabel rightLabel;
public LeftRightCheck(String leftText, String rightText, Icon icon,
boolean selected) {
super(leftText, icon, selected);
rightLabel = new JLabel(rightText, TRAILING);
// TODO figure out how to make the font work right on OSX
this.setLayout(new BaseLineSingleElementLayoutManager(10));
this.add(rightLabel);
}
@Override
public final void setFont(Font font) {
font = font.deriveFont(DEFAULT_CHECK_BOX.getFont().getSize2D());
super.setFont(font);
if (rightLabel != null) {
rightLabel.setFont(font);
}
}
private class BaseLineSingleElementLayoutManager implements LayoutManager {
private int hgap;
private Component component;
public BaseLineSingleElementLayoutManager(int hgap) {
this.hgap = hgap;
}
@Override
public void addLayoutComponent(String name, Component comp) {
// Do Nothing
}
@Override
public void removeLayoutComponent(Component comp) {
// Do Nothing
}
@Override
public Dimension preferredLayoutSize(Container parent) {
if (parent != null && parent instanceof JCheckBox) {
JCheckBox cc = (JCheckBox) parent;
// These 2 lines will add the size of the checkbox to the
// preferred size
Dimension parentSize = DEFAULT_CHECK_BOX.getPreferredSize();
parentSize.width += cc.getFontMetrics(cc.getFont()).
stringWidth(cc.getText()) + hgap;
if (checkComponent(cc)) {
Dimension childSize = this.component.getPreferredSize();
parentSize.height = Math.max(parentSize.height,
childSize.height);
parentSize.width += childSize.width;
}
return parentSize;
}
return new Dimension();
}
@Override
public Dimension minimumLayoutSize(Container parent) {
return preferredLayoutSize(parent);
}
@Override
public void layoutContainer(Container parent) {
if (!checkComponent(parent)) {
return;
}
this.component.setSize(parent.getSize());
this.component.setLocation(0, getBaseline(parent)
- getBaseline(this.component));
}
private int getBaseline(Component c) {
return c.getBaseline(c.getWidth(), c.getHeight());
}
protected boolean checkComponent(Container parent) {
if (parent == null) {
return false;
} else if (parent.getComponentCount() >= 1
&& parent.getComponent(0).isVisible()) {
this.component = parent.getComponent(0);
return true;
} else {
return false;
}
}
}
}