是否有一种简单的方法可以将只是JCheckBox
的复选框与右侧对齐,而无需创建单独的标签和复选框组件?我知道setHorizontalTextPosition(SwingConstants.LEADING);
这只会导致框位于文本的右侧,但不是右对齐。
我想要的是什么:
| Some sample text ☑ |
而不是
| Some sample text ☑ |
提前致谢!
答案 0 :(得分:3)
您可以在合适的布局中分隔标签和复选框。我用一个任意因子使封闭框架更宽,以显示效果。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
/** @see http://stackoverflow.com/a/2933256/230513 */
public class Test {
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.setLayout(new GridLayout(0, 1));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createPanel("Some label"));
frame.add(createPanel("Another label"));
frame.add(createPanel("Yet another label"));
frame.pack();
frame.setSize(frame.getWidth() * 2, frame.getHeight());
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createPanel(String s) {
JPanel p = new JPanel(new BorderLayout());
p.add(new JLabel(s, JLabel.LEFT), BorderLayout.WEST);
p.add(new JCheckBox(), BorderLayout.EAST);
p.setBorder(BorderFactory.createLineBorder(Color.blue));
return p;
}
});
}
}
答案 1 :(得分:2)
每次复选框大小发生变化时,您都可以通过在复选框中添加ComponentListener
来手动操作图标文本间隙:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SSCCE extends JPanel
{
public SSCCE()
{
setLayout( new BorderLayout() );
JCheckBox checkBox = new JCheckBox("Some Sample Text");
checkBox.setHorizontalTextPosition(JCheckBox.LEADING);
add(checkBox, BorderLayout.PAGE_START);
checkBox.addComponentListener( new ComponentAdapter()
{
@Override
public void componentResized(ComponentEvent e)
{
JCheckBox checkBox = (JCheckBox)e.getComponent();
int preferredWidth = getPreferredSize().width;
int actualWidth = getSize().width;
int difference = actualWidth - preferredWidth;
int gap = checkBox.getIconTextGap() + difference;
gap = Math.max(UIManager.getInt("CheckBox.textIconGap"), gap);
checkBox.setIconTextGap( gap );
}
});
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new SSCCE());
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater( () -> createAndShowGUI() );
/*
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
*/
}
}