我为我的游戏制作菜单。我希望背景动画。因此我使用带有gif的JLabel。除此之外,我想要我的按钮。但是,我希望按钮和窗口左侧之间有一些空气。这让我很麻烦。
这是我的结果。这很不错!但我无法让灰色条消失!而且,看起来我的背景JLabel被推到了右边。
我有三个班级:
1创建JFrame的启动器
public class Launcher extends JFrame{
public int speed = 0;
int c = 0;
public final static int WIDTH = 1200;
public final static int HEIGHT = 800;
Game game;
JFrame frame;
public static void main(String[] args) throws IOException{
new Launcher();
}
public Launcher() throws IOException{
game = new Game();
JFrame frame = new JFrame("PingPong!");
frame.add(game);
frame.setFocusable(true);
frame.setPreferredSize(new Dimension(WIDTH, HEIGHT) );
frame.setVisible(true);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
}
}
2使用OverlayLayout创建JPanel的游戏
public class Game extends JPanel implements Runnable{
public State menuState;
public Game() throws IOException{
this.removeAll();
this.setLayout(new OverlayLayout(this));
menuState = new MenuState(this, handler);
}
}
3最后我的MenuState创建了一个带有BoxoLayout的JPanel,我添加了元素
public class MenuState extends State{
JPanel menuPanel;
JLabel background;
private Icon backgroundIcon;
private Icon newgameIcon;
private Icon loadgameIcon;
private JButton newGame;
private JButton loadGame;
Border border;
public MenuState(Game game, Handler handler) {
super(game, handler);
init();
}
public void init(){
menuPanel = new JPanel();
menuPanel.setLayout(new BoxLayout(menuPanel, BoxLayout.PAGE_AXIS));
menuPanel.setBackground(Color.green);
menuPanel.add(Box.createHorizontalStrut(100));
menuPanel.setVisible(true);
menuPanel.setOpaque(false);
Box left = Box.createVerticalBox();
backgroundIcon = new ImageIcon("res/images/menu/back.gif");
background = new JLabel(backgroundIcon);
newGame = new JButton("New Game");
loadGame = new JButton("Load Game");
game.add(menuPanel);
menuPanel.add(newGame);
left.add(newGame);
left.add(Box.createRigidArea(new Dimension(0, 40)));
left.add(loadGame);
left.add(Box.createRigidArea(new Dimension(0, 300)));
left.setOpaque(false);
menuPanel.add(left);
background.setSize(1200, 800);
game.add(background);
}
}
我尝试过添加组件的不同顺序。我尝试过Opacity真假。
我希望我可以设置newGame.setLocation(100, 500)
并将该框放在我想要的位置。
答案 0 :(得分:3)
但是,我希望按钮和窗口左侧之间有一些空气。
EmptyBorder
,以便在面板中提供按钮间距。您可以使用此处的演示代码来播放对齐值:Java Layout with Component always in Top Right
如果我理解你的要求你应该使用setAlignmentX(0.0)和setAlignmentY(0.5);
所以简单地说你的代码应该是这样的:
JLabel background = new JLabel(...);
background.setAlignmentX(0.0f);
background.setAlignmentY(0.5f);
JPanel buttonsPanel = new JPanel( set your layout );
buttonsPanel.setOpaque( false );
buttonsPanel.setBorder( new EmptyBorder(...) );
buttonsPanel.setAlignmentX(0.0f);
buttonsPanel.setAlignmentY(0.5f);
JPanel overlayPanel = new JPanel( new OverLayLayout(...) );
overlayPanel.add(background);
overlayPanel.add(buttonsPanel);