簡體   English   中英

GridLayout Center溢出組件

[英]GridLayout Center Overflow Components

我有一組按鈕。 我的JPanel具有GridLayout的布局。 我希望任何組件都可以走出廣場中心。 這是一張圖片: http : //screencast.com/t/z86ldR9vh

我希望“選項”按鈕位於該組的中央。

提前致謝!

為“選項”按鈕創建另一個JPanel,並將其設置為流布局。 例如,假設頂部面板名為“ panel1”,底部面板為“ panel2”:

// create top panel with first four buttons
JPanel panel1 = new JPanel(new GridLayout(2, 2));
panel1.add(new JButton("Play"));
panel1.add(new JButton("New Game"));
panel1.add(new JButton("Save Game"));
panel1.add(new JButton("Load Game"));

// create bottom panel with "Options" button
JPanel panel2 = new JPanel(new FlowLayout());
panel2.add(new JButton("Options"));

或者,如果您想要該類的完整代碼(包括所有導入):

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;

public class Buttons {
    public static void main(String[] args) {
        Buttons gui = new Buttons();
    }

    public Buttons() {
        // create frame
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(new Dimension(250, 150));
        frame.setLayout(new FlowLayout());
        frame.setVisible(true);

        // create top panel with first four buttons
        JPanel panel1 = new JPanel(new GridLayout(2, 2));
        panel1.add(new JButton("Play"));
        panel1.add(new JButton("New Game"));
        panel1.add(new JButton("Save Game"));
        panel1.add(new JButton("Load Game"));

        // create bottom panel with "Options" button
        JPanel panel2 = new JPanel(new FlowLayout());
        panel2.add(new JButton("Options"));

        // add panels to frame
        frame.add(panel1);
        frame.add(panel2);
    }   
}  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM