簡體   English   中英

自定義秋千布局

[英]Custom Swing layout

我正在創建一個游戲,並按照我想要的方式設置框架,因此需要一些如何創建服裝布局的方法。 我嘗試創建多個具有不同布局(例如“流”和“邊框”)的面板,並在主面板上添加面板,但是仍然無法獲得理想的結果。 附件中顯示了我想要的內容。 請告訴我是否有任何代碼段會有所幫助。
問題:1.是否有可能獲得這種布局? (我希望將其修復。) 在此處輸入圖片說明

  1. 在“按鈕”下方,有您在圖片中看到的JLabel。 我希望它的文本從左開始,在列中向下,從中間開始,然后到右列。 那可能嗎?

關於我在評論中寫的內容,有一個細微的差異,因為BoxLayoutBoxLayout ,我從未使用過,因為我不太擅長:-)

盡管我要克服的是我的缺點,但我的缺點是要使用2個JPanel ,每個分別用於JTextFieldJButton ,其余的相同,如本示例所示:

import java.awt.*;
import javax.swing.*;

public class LayoutExample {    

    private static final int GAP = 5;
    private static final int TOTAL_LABELS = 18;

    private JTextField tField;
    private JButton button;
    private JLabel[] labels;

    private void displayGUI () {
        JFrame frame = new JFrame ( "Layout Example" );
        frame.setDefaultCloseOperation ( JFrame.DISPOSE_ON_CLOSE );

        JPanel contentPane = getPanel ();
        contentPane.setLayout ( new BorderLayout ( GAP, GAP ) );

        JPanel headerPanel = getPanel ();
        headerPanel.setLayout ( new GridLayout ( 0, 1, GAP, GAP ) );
        JPanel textFieldPanel = getPanel ();
        tField = new JTextField ( 10 );
        textFieldPanel.add ( tField );
        JPanel buttonPanel = getPanel ();
        button = new JButton ( "Button" );
        buttonPanel.add ( button );     
        headerPanel.add ( textFieldPanel );
        headerPanel.add ( buttonPanel );
        contentPane.add (headerPanel, BorderLayout.PAGE_START );

        JPanel centerPanel = getPanel ();
        centerPanel.setLayout ( new GridLayout ( 0, 3, GAP, GAP ) );
        labels = new JLabel [ TOTAL_LABELS ];
        for ( int i = 0; i < labels.length; ++i ) {
            labels [ i ] = new JLabel ( String.valueOf ( i ), JLabel.CENTER );
            centerPanel.add ( labels [ i ] );
        }
        contentPane.add ( centerPanel, BorderLayout.CENTER );


        frame.setContentPane ( contentPane );
        frame.pack ();
        frame.setLocationByPlatform ( true );
        frame.setVisible ( true );
    }

    private JPanel getPanel () {
        JPanel panel = new JPanel ();
        panel.setOpaque ( true );
        panel.setBorder ( BorderFactory.createEmptyBorder ( GAP, GAP, GAP, GAP ) );

        return panel;
    }

    public static void main ( String[] args ) {
        Runnable runnable = new Runnable () {
            @Override
            public void run () {
                new LayoutExample ().displayGUI ();
            }
        };
        EventQueue.invokeLater ( runnable );
    }
}

輸出:

http://i.imgur.com/FMcV9GS.png

暫無
暫無

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

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