如何正确设置布局?

时间:2014-05-15 23:19:05

标签: java button user-interface grid-layout

public class Gridlayout extends JFrame {

   public Gridlayout()
   {
         setTitle("xxx");

         setSize(540,635);
         this.setResizable(false);
         this.setLocation(500,50);

         initComponents();
         setDefaultCloseOperation(3);
   }

    JLabel etykieta = new JLabel("Poziom trudności: "); 

    JPanel top = new JPanel(new GridLayout(2, 2));
    JPanel mid = new JPanel(new GridLayout(0, 1));
    JPanel bot = new JPanel(new GridLayout(1, 0));

    JButton start= new JButton("Start");
    JButton zakoncz = new JButton("Zakoncz");

    JRadioButton latwy = new JRadioButton("Łatwy");
    JRadioButton sredni = new JRadioButton("Średni");
    JRadioButton trudny = new JRadioButton("Trudny");


    ButtonGroup poziomTrudnosci= new ButtonGroup();


public void initComponents() {


        this.getContentPane().add(top, BorderLayout.NORTH);
        this.getContentPane().add(mid, BorderLayout.CENTER);
        this.getContentPane().add(bot, BorderLayout.SOUTH);

        start.setPreferredSize(new Dimension(1, 40));
        zakoncz.setPreferredSize(new Dimension(1, 40));

         mid.add(etykieta);
         mid.add(latwy);
         mid.add(sredni);
         mid.add(trudny);
         bot.add(start);


        poziomTrudnosci.add(latwy);
        poziomTrudnosci.add(sredni);
        poziomTrudnosci.add(trudny);

     }


    public static void main(String[] args) {

        new Gridlayout().setVisible(true);
    }

}

如何将此按钮从左侧移动到窗口中央?他们应该保持密切联系我尝试了一切,但他们仍在左侧。 Screenshot

1 个答案:

答案 0 :(得分:0)

如果我正确理解您的问题,您希望将JRadioButtons水平居中JFrame,是吗?试试setHorizontalAlignment()方法。将以下行添加到initComponents()函数中:

    latwy.setHorizontalAlignment(JRadioButton.CENTER);
    sredni.setHorizontalAlignment(JRadioButton.CENTER);
    trudny.setHorizontalAlignment(JRadioButton.CENTER);