[英]Java: What Layout Manager would be best for a game menu?
===================
游戏名称
玩
出口
===================
以上就是我以前的游戏菜单。 我使用Box Layout来创建它,但是这很繁琐。 有没有我可以使用的更好的布局管理器?
这是主窗格中询问的代码。
private JButton JB;
private JButton EB;
private JOptionPane JO;
public StartUpWindow(){
super("Pong");
JPanel outside = new JPanel();
JPanel inside = new JPanel();
setLayout(new BorderLayout());
outside.setLayout(new BoxLayout(outside, BoxLayout.LINE_AXIS));
inside.setLayout(new BoxLayout(inside, BoxLayout.PAGE_AXIS));
outside.add(Box.createHorizontalStrut(280));
outside.add(inside);
outside.add(Box.createHorizontalStrut(20));
inside.add(Box.createVerticalStrut(20));
JLabel title = new JLabel(" "+"Pong");
title.setFont( new Font("Serif", Font.BOLD, 40));
inside.add(title);
inside.add(Box.createVerticalStrut(20));
JButton btt1 = new JButton("Start");
Dimension d = new Dimension(200,40);
btt1.setSize(d);
btt1.setMinimumSize(d);
btt1.setMaximumSize(d);
btt1.setPreferredSize(d);
JButton btt2 = new JButton("Credits");
btt2.setSize(d);
btt2.setMinimumSize(d);
btt2.setMaximumSize(d);
btt2.setPreferredSize(d);
JButton btt3 = new JButton("Exit");
btt3.setSize(d);
btt3.setMinimumSize(d);
btt3.setMaximumSize(d);
btt3.setPreferredSize(d);
inside.add(btt1);
btt1.addActionListener(this);
btt1.setActionCommand("start");
inside.add(Box.createVerticalStrut(5));
inside.add(btt2);
btt2.addActionListener(this);
btt2.setActionCommand("credits");
inside.add(Box.createVerticalStrut(5));
inside.add(btt3);
btt3.addActionListener(this);
btt3.setActionCommand("exit");
inside.add(Box.createVerticalStrut(20));
add(outside);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(800,600);
this.setVisible(true);
this.setResizable(false);
this.setLocation(450,200);
inside.setBackground(Color.GRAY);
outside.setBackground(Color.GRAY);
}
我同意BoxLayout是乏味的,但是我很欣赏它的相对简单性。
另一个快速简便的选择是使用“ javax.swing.Box”类,而不是直接使用布局管理器。
Box box = Box.createVerticalBox();
box.add(new JLabel("Game"));
box.add(Box.createVerticalStrut(20));
box.add(new JLabel("Button 1"));
box.add(new JLabel("Button 2"));
JFrame frame = new JFrame();
frame.add(box);
frame.pack();
frame.setVisible(true);
Box提供了许多有用的方法。 您可以使用它创建垂直和水平框,创建“支柱”以保留水平和垂直空间,并创建“胶水”以在布局增长时填充可用空间。
当然,您也可以使用GridBagLayout,但我倾向于将其保留用于更复杂的布局。 Box及其表兄BoxLayout通常足以满足简单的布局要求,并且对于维护应用程序的新程序员来说,易于理解和调试。
为什么不简单地不使用布局,而使用Graphics
对象绘制所有内容呢?
您可以通过创建绑定到Window
对象的BufferStrategy
(在后者上调用createBufferStrategy
)然后调用一些简单的方法轻松地重绘屏幕来轻松实现此目的。
这也意味着在玩游戏时对游戏的显示进行编码更简单。
当应用程序处于全屏独占模式时, BufferStrategy
还允许使用页面翻转和其他形式的缓冲,从而允许它在许多应用程序中非常快速地刷新屏幕。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.