use*_*292 2 java swing form-layout
我使用了FormLayout,我想将所有组件(JLabel和JtextField)设置在JFrame的中心。
我尝试使用panel.setAlignmentX和panel.setAlignmentY,但是它不起作用。
panel.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.setAlignmentY(Component.CENTER_ALIGNMENT);
Run Code Online (Sandbox Code Playgroud)
下面显示的是我的代码,请帮助谢谢。
import java.awt.Component;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
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(
"pref, pref, pref, pref",
"pref, pref, pref, pref");
panel.setLayout(layout);
CellConstraints cc = new CellConstraints();
panel = new JPanel (layout);
panel.add(new JLabel("L1 "), cc.xy(2, 2));
panel.add(new JTextField(15), cc.xy(3, 2));
panel.add(new JLabel("L2 "), cc.xy(2, 3));
panel.add(new JTextField(15), cc.xy(3, 3));
panel.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.setAlignmentY(Component.CENTER_ALIGNMENT);
add(panel);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
pack();
setSize(510,400);
setLocationRelativeTo(null);
setResizable(false);
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new UI().setVisible(true);
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
使用GridBagLayout。默认情况下,添加到布局的所有组件(面板)都将居中:
//add(panel);
setLayout( new GridBagLayout() );
add(panel, new GridBagConstraints());
Run Code Online (Sandbox Code Playgroud)
这将允许您FormLayout在包含组件的面板上使用。现在,内容窗格正在使用GridBagLayout,因此您的表单将居中。
| 归档时间: |
|
| 查看次数: |
2048 次 |
| 最近记录: |