自定义Swing布局

时间:2015-05-29 00:26:00

标签: java swing layout-manager

我正在创建一个游戏并按照我想要的方式设置框架,我需要一些如何创建服装布局。我尝试使用不同的布局创建多个面板,例如Flow和Border,并在主面板上添加面板,但我仍然无法获得所需的结果。我想要的是附图。如果任何代码段有帮助,请告诉我 问题: 1.有可能获得这样的布局吗? (我希望它得到修复。)enter image description here

  1. 在“按钮”下面有你在图片中看到的JLabel。我希望它的文本从左边开始,沿着列向下,从中间开始,然后到右边列。那可能吗?

1 个答案:

答案 0 :(得分:4)

关于我在评论中所写的内容,有一点点变化,因为BoxLayout是某种东西,我从不使用,因为我不擅长: - )

虽然我所要克服的,但我的这个缺点是需要2 JPanel s,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