我想将布局设置为以下内容:1列和5行,位于中心。
我尝试使用GridLayout(5,0)
,但它仍然在左侧,是否有任何建议如何使其成为中心?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JPanel;
public class TestSwingListeners1 {
private static int cnt1;
private static int cnt2;
public static void main(String[] args) {
JFrame fr1 = new JFrame("Swing Window");
Container cp;
JButton bt1;
JButton bt2;
cnt1 = 0;
cnt2 = 0;
final String scr = null;
final String wnr = null;
JButton btOK, btCancel;
fr1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fr1.setSize(200, 200);
fr1.setResizable(true);
cp = fr1.getContentPane();
cp.setLayout(new GridLayout(5,0));
// cp.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
btOK = new JButton("AC Milan");
btCancel = new JButton("Real Madrid");
final JLabel lbl1 = new JLabel("Result: " + cnt1 + "X" + cnt2);
final JLabel lbl2 = new JLabel("Last Scorer: " + scr);
final JLabel lbl3 = new JLabel("Winner: " + wnr);
cp.add(btOK);
cp.add(btCancel);
cp.add(lbl1);
cp.add(lbl2);
cp.add(lbl3);
fr1.add(cp, BorderLayout.CENTER);
cp.setLayout(new BoxLayout(lbl1, BoxLayout.LINE_AXIS));
//lbl1.setText(displayText);
btOK.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
cnt1++;
lbl1.setText("Result: " + cnt1 + "X" + cnt2);
lbl2.setText("Last Scorer: AC Milan");
if(cnt1>cnt2){
lbl3.setText("Winner: AC Milan");
}
else if(cnt1<cnt2){
lbl3.setText("Winner: Real Madrid");
}
else if(cnt1 == cnt2){
lbl3.setText("Winner: Draw");
}
}
});
btCancel.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
cnt2++;
lbl1.setText("Result: " + cnt1 + "X" + cnt2);
lbl2.setText("Last Scorer: Real Madrid");
if(cnt1>cnt2){
lbl3.setText("Winner: AC Milan");
}
else if(cnt1<cnt2){
lbl3.setText("Winner: Real Madrid");
}
else if(cnt1 == cnt2){
lbl3.setText("Winner: Draw");
}
}
});
fr1.show();
}
}
答案 0 :(得分:2)
GridLayout grid = new GridLayout(5, 0);
cp.setLayout(grid);
...
grid.addComponent(btOK, 0, 0);
grid.setComponentAlignment(btOK, Alignment.MIDDLE_CENTER);
...
答案 1 :(得分:0)
查看MigLayout - 这是一站式现代布局管理器。你永远不会回头看任何其他布局经理。它为我节省了大量时间制作Swing UI。