请看下面的代码
import java.awt.GridLayout;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class TestSend extends JFrame
{
private Box names, emails;
private JButton ok;
private Map mMap;
private JLabel nameLabel, emailLabel;
private JPanel mainPanel;
private JScrollPane scroll;
public TestSend()
{
names = new Box(BoxLayout.Y_AXIS);
emails = new Box(BoxLayout.Y_AXIS);
nameLabel = new JLabel("Names");
emailLabel = new JLabel("Email");
mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout(2,2));
scroll = new JScrollPane(mainPanel);
mainPanel.add(nameLabel);
mainPanel.add(emailLabel);
mainPanel.add(names);
mainPanel.add(emails);
mMap = new HashMap();
mMap.put("yohan", "yy@yahoo.com");
mMap.put("Gihan", "gihan@yahoo.com");
mMap.put("Sumi", "sumi@yahoo.com");
mMap.put("mac", "mac@yahoo.com");
mMap.put("Jay", "jay@yahoo.com");
mMap.put("Rom", "rom@yahoo.com");
mMap.put("shane", "shane@yahoo.com");
mMap.put("Mafe", "mafe@yahoo.com");
mMap.put("willi", "willi@yahoo.com");
Iterator iter = mMap.entrySet().iterator();
while(iter.hasNext())
{
Map.Entry mEntry = (Map.Entry)iter.next();
JCheckBox cBox = new JCheckBox((String)mEntry.getKey());
names.add(cBox);
if((String)mEntry.getValue() != null && ((String)mEntry.getValue()).length() != 0 && !((String)mEntry.getValue()).equals(""))
{
JLabel lLabel = new JLabel((String)mEntry.getValue());
// lLabel.setPreferredSize(new Dimension(cBox.getPreferredSize().width,cBox.getPreferredSize().height));
emails.add(lLabel);
emails.add(new JPanel());
}
else
{
JLabel lLabel = new JLabel();
//lLabel.setPreferredSize(new Dimension(cBox.getPreferredSize().width,cBox.getPreferredSize().height));
emails.add(lLabel);
emails.add(new JPanel());
}
}
this.add(scroll);
this.pack();
this.setVisible(true);
}
public static void main(String[]args)
{
new TestSend();
}
}
当您执行它时,您可以看到与 JCheckBox 相比,JLabel 包含的垂直间隙更少。因此,“电子邮件地址”(JLabel) 不会显示在显示“名称”(JCheckBox) 的同一行中。我怎样才能解决这个问题?