我想在右侧创建一个带复选框的按钮。 我试过这个但是复选框停留在按钮标签文本顶部的按钮中心。
任何想法welkom。
提前感谢:
public class MainTest extends JPanel {
JButton button;
JPanel panel;
public MainTest() {
createComponents();
layoutComponents();
}
public void createComponents() {
// attempting to add checkbox to button
button = new JButton("Print with Edge");
JCheckBox checkBox = new JCheckBox();
jcb.setHorizontalAlignment(SwingConstants.RIGHT);
button.add(checkBox,new BorderLayout());
panel = new JPanel(new BorderLayout());
}
public void layoutComponents() {
panel.add(button,BorderLayout.SOUTH);
add(panel);
}
public static void main(String[] args) {
MainTest demo = new MainTest();
JFrame frame = new JFrame();
Container cp = frame.getContentPane();
cp.add(demo);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setLocation(500, 500);
frame.setVisible(true);
}
}
答案 0 :(得分:2)
您可以将JCheckBox包装在JPanel中,并使JPanel看起来像一个按钮。例如:
public class Test {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(new Dimension(100, 100));
JCheckBox button = new JCheckBox();
final JPanel buttonWrapper = new JPanel();
buttonWrapper.add(new JLabel("Button Text"));
buttonWrapper.add(button);
buttonWrapper.setBorder(BorderFactory.createRaisedBevelBorder());
buttonWrapper.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent me) {
buttonWrapper.setBorder(BorderFactory.createEtchedBorder());
}
@Override
public void mouseReleased(MouseEvent me) {
buttonWrapper.setBorder(BorderFactory.createRaisedBevelBorder());
}
@Override
public void mouseClicked(MouseEvent me) {
System.out.println("mouse clicked");
}
});
JPanel mainPanel = new JPanel();
mainPanel.add(buttonWrapper);
frame.getContentPane().add(mainPanel);
frame.setVisible(true);
}
}
答案 1 :(得分:1)
我想在右侧创建一个带复选框的按钮。
也许您只想要文本右侧的复选框?
如果是这样,你可以这样做:
JCheckBox cb = new JCheckBox("Print with Edge");
cb.setHorizontalTextPosition(SwingConstants.LEADING);