繁体   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