gpt4 book ai didi

java - 如何更改 Java Swing 中显示的内容?

转载 作者:行者123 更新时间:2023-11-30 02:58:46 26 4
gpt4 key购买 nike

我真的不知道如何表达这个问题,但我可以解释我想要做什么。我让我的程序绘制一个基本菜单,其中带有背景图像和底部的 3 个按钮。我想要做到这一点,以便当我按下其中一个按钮时,菜单和背景图像会更改为不同的场景。就像按“开始”键开始游戏或按“选项”进入选项菜单。

这是我的主菜单代码:

private final void initUI() {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
add(panel);

panel.add(Box.createVerticalGlue());

JPanel bottom = new JPanel();
bottom.setAlignmentX(1f);
bottom.setLayout(new BoxLayout(bottom, BoxLayout.X_AXIS));

JButton plyBtn = new JButton("Play");
plyBtn.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent event){
GameFrame_Test1 game1 = new GameFrame_Test1();
game1.setVisible(true);
}
});

JButton opBtn = new JButton("Options");


JButton quitButton = new JButton("Exit");

quitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
bottom.add(plyBtn);
bottom.add(Box.createRigidArea(new Dimension(100, 0)));
bottom.add(opBtn);
bottom.add(Box.createRigidArea(new Dimension(100, 0)));
bottom.add(quitButton);
bottom.add(Box.createRigidArea(new Dimension(100, 0)));

panel.add(new GraphicTest_1());
panel.add(bottom);
panel.add(Box.createRigidArea(new Dimension(0,15)));


setTitle("Justice GUI");
setSize(1280, 720);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args) {

EventQueue.invokeLater(new Runnable() {

@Override
public void run() {
DisplayFrame ex = new DisplayFrame();
ex.setVisible(true);
}
});
}

这是我到目前为止想要更改的框架的代码:

class GameFrame_Test1 extends JPanel{
private Image mshi;

public GameFrame_Test1() {

loadImage();
setSurfaceSize();
}

private void loadImage() {

mshi = new ImageIcon("content/Placeholder_Map.png").getImage();
}

private void setSurfaceSize() {

Dimension d = new Dimension();
d.width = mshi.getWidth(null);
d.height = mshi.getHeight(null);
setPreferredSize(d);
}

private void doDrawing(Graphics g) {

Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(mshi, 0, 0, null);
}

@Override
public void paintComponent(Graphics g) {

super.paintComponent(g);
doDrawing(g);
}
}

我对 Java Swing 非常陌生,这是一个测试程序,供我学习如何使用它。我在网上寻找解决方案,但无法说出我的问题使其变得困难。感谢任何可以提供帮助的人!

最佳答案

I want to make it so that when I press one of the buttons, the menu and the background image change to a different scene.

您应该使用卡片布局作为内容面板的布局管理器。然后,当单击按钮时,您可以在框架上交换不同的面板。

查看 Swing 教程中 How to Use CardLayout 的部分了解更多信息和工作示例。

关于java - 如何更改 Java Swing 中显示的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36480556/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com