I was about to program a little game. I have my main class MenuFrame
from which I call my Gui
class which draws my Game.
MenuFrame.java:
public class MenuFrame extends JFrame implements ActionListener {
private JButton start;
public static void main(String[] args) {
MenuFrame mainframe = new MenuFrame("Menu");
mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainframe.setSize(600, 400);
mainframe.setLayout(null);
mainframe.setVisible(true);
}
public MenuFrame(String title) {
super(title);
start = new JButton("Start game");
start.setBounds(220, 60, 160, 40);
start.addActionListener(this);
add(start);
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == start) {
game(hauptSpiel);
}
}
public static void game() {
JFrame game = new JFrame;
game.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
game.setUndecorated(true);
game.setResizable(false);
game.setSize(480, 800);
game.setLocation(1920/2-480/2, 1080/2-800/2);
game.setVisible(true);
game.add(new Gui());
}
}
As you can see, I call my class Gui()
from my void game()
.
In my Gui
class, I do some painting.
The class looks a little bit like this:
public class Gui extends JPanel implements ActionListener {
public Gui() {
setFocusable(true);
ImageIcon i = new ImageIcon(background.jpg);
background = i.getImage();
ImageIcon b = new ImageIcon("ball.png");
ball = b.getImage();
}
public void paint(Graphics g) {
Graphics2D f2 = (Graphics2D)g;
f2.drawImage(background, 0, 0, null);
f2.drawImage(ball, 0, 600, null);
}
}
I removed my game logic for reasons of clarity and comprehensibility.
However, if the game is over, I want to dispose my game()
JFrame
in the MenuFrame
Class.
Is there any way to do this clean and smooth?