我想显示一个“表”,其中
JLabel
在第1列中右对齐,在第2列中为每行的组件左对齐。当第2列组件
标签类
,
JTextField
JCheckBox
. 但我很难理解
JComboBox
.
我认为有两种方法(可能有三种)可以解决这个问题。
-
-
将所有组件的插入置零,并让布局管理器处理间隙
-
摆弄UIManager以将JComboBox插入置零?
在我尝试之前,2选项看起来更容易理解、实现和维护。我从
FormLayout
但是自从我有同样的“错位”问题
GridLayout
,我选择发布GridLayout版本以使其更易于验证。请告诉我,我可以在没有太多麻烦的情况下选择2工作,或者选择3如何工作。
下面是我的
MCV
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.plaf.basic.*;
public class TestFrame3 extends JFrame {
public TestFrame3 () {
JLabel l1 = new JLabel("l1"); l1.setBorder(new EmptyBorder(0, 0, 0, 0));
JLabel r1 = new JLabel("r1"); r1.setBorder(new EmptyBorder(0, 0, 0, 0));
JLabel l2 = new JLabel("l2"); l2.setBorder(new EmptyBorder(0, 0, 0, 0));
JComboBox r2 = new JComboBox(); r2.setBorder(new EmptyBorder(0, 0, 0, 0));
r2.setRenderer(new BasicComboBoxRenderer() {
@Override
public Component getListCellRendererComponent (JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
JComponent comp = (JComponent) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
comp.setBorder(new EmptyBorder(0, 0, 0, 0));
return comp;
}
});
JPanel p = new JPanel();
p.setLayout(new GridLayout(2, 2));
p.add(l1);
p.add(r1);
p.add(l2);
p.add(r2);
getContentPane().add(p);
setSize(new Dimension(100, 200));
}
public static void main (String args[]) {
new TestFrame3().setVisible(true);
}
}
下面是显示的内容,显示“r1”中的“r”未与
:
wonder
. 在他的提示下,我尝试将UI设置为
BasicComboBoxUI
而不是使用默认值
com.apple.laf.AquaComboBoxUI
而对齐问题并没有显现出来。不幸的是,这个用户界面在另一个方面没有吸引力。