我正在创建一个游戏并按照我想要的方式设置框架,我需要一些如何创建服装布局。我尝试使用不同的布局创建多个面板,例如Flow和Border,并在主面板上添加面板,但我仍然无法获得所需的结果。我想要的是附图。如果任何代码段有帮助,请告诉我 问题: 1.有可能获得这样的布局吗? (我希望它得到修复。)
答案 0 :(得分:4)
关于我在评论中所写的内容,有一点点变化,因为BoxLayout
是某种东西,我从不使用,因为我不擅长: - )
虽然我所要克服的,但我的这个缺点是需要2 JPanel
s,JTextField
和JButton
各一个,其余的相同,如图所示这个例子:
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 );
}
}
输出: