0

我想将布局设置如下: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(); 
       }
  }
4

2 回答 2

2
GridLayout grid = new GridLayout(5, 0);
cp.setLayout(grid);

...

grid.addComponent(btOK, 0, 0);
grid.setComponentAlignment(btOK, Alignment.MIDDLE_CENTER);

...
于 2011-07-21T10:47:30.697 回答
0

查看MigLayout——这是一个一站式现代布局管理器。您永远不会回头看任何其他布局管理器。它为我节省了大量制作 Swing UI 的时间。

于 2011-07-21T20:38:46.477 回答