Java建立窗口并通过按钮实现窗口跳转

mac2024-03-13  28

为之前的游戏做了一个菜单的模型

这是菜单类

import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Menu extends JFrame implements ActionListener { //定义两个按钮 private JButton Game_Start; private JButton Game_Over; public Menu(){ //定义按钮的排列方式 setLayout(new FlowLayout()); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); this.setSize(300,200); this.setLocation(300,400); Game_Start = new JButton("开始游戏"); Game_Over = new JButton("结束游戏"); this.add(Game_Start); this.add(Game_Over); Game_Start.addActionListener(this); Game_Over.addActionListener(this); this.setVisible(true); } public static void main(String[] args) { Menu menu = new Menu(); } /** * Invoked when an action occurs. * * @param e */ @Override public void actionPerformed(ActionEvent e) { if(e.getSource() == Game_Start){ this.dispose(); new Newframe(); } if(e.getSource() == Game_Over){ this.dispose(); System.exit(0); } } }

这是新的一个类(模拟我的游戏主类)

import javax.swing.*; public class Newframe extends JFrame { public Newframe(){ this.setSize(300,200); this.setLocation(300,400); this.setVisible(true); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } }

演示: 当点击按钮开始游戏的时候,会跳转到下一个新的窗口,而点击结束游戏的时候会关闭窗口,并停止运行这个程序。

这个是点击开始游戏之后的新窗口 ↑ ↑ ↑

有什么问题可以指出,谢谢各位观看。

最新回复(0)