如屏幕截图所示,我的第二个textLabel和textField被推下来了 在我在左边添加textarea之后。
我希望将第二个textLabel和textField放在我的第一个textLabel和textField下面,同时保持左边的TextLabal和textArea。我怎样才能实现它?
我使用了formLayout。
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
@SuppressWarnings("serial")
public class UI extends JFrame {
private JPanel panel = new JPanel();
public UI() {
FormLayout layout = new FormLayout(
"right:pref, 3dlu, pref, 30dlu, pref", // columns
"p, 3dlu, p"); //rows
panel.setLayout(layout);
CellConstraints cc = new CellConstraints();
panel = new JPanel (layout);
panel.add (new JLabel ("textf1:"), cc.xy (1, 1));
panel.add (new JTextField (15), cc.xy (3, 1));
panel.add (new JLabel ("textf2:"), cc.xy (1, 3));
panel.add (new JTextField (15), cc.xy (3, 3));
panel.add (new JLabel ("TextL"), cc.xy (5, 1));
panel.add (new JTextArea (10, 10), cc.xy (5, 3));
add(panel);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
pack();
setSize(1024,768);
setLocationRelativeTo(null);
//frame.setVisible(true);
setResizable(false);
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new UI().setVisible(true);
}
});
}
}
答案 0 :(得分:1)
为元素添加CellConstraints值:
panel.add(new JLabel("textf2:"), cc.xy(1, 3, CellConstraints.LEFT, CellConstraints.TOP));
panel.add(new JTextField(15), cc.xy(3, 3, CellConstraints.LEFT, CellConstraints.TOP));