Im attempting to make a standard menu UI in java and I'm having an issue.
So essentially Code 1
sets up the Jframe and calls code 2
.
The problem I'm having is that when the menu button is pressed I want it to load code 3
and then stay there until the exit button is pressed. But what is happening at the moment is that the mouse pressed is detected, it runs through the entirety of code 3
and returns to code 2
without repainting the menu bar or exit button that code 3
contains.
So what I'm looking to happen is that when code 3
is called I want it to stay there and display the content (that being the menu) until a mouse click is detected in the area on the exit_but
.
Any help would be great.
My code is show below;
Code 1:
import java.awt.*;
import java.awt.Graphics;
import javax.swing.*;
public class demo_project
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Funhaus Project");
frame.setSize(720, 1280);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new demo_main_screen());
frame.pack();
frame.setVisible(true);
}
}
Code 2:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class demo_main_screen extends JPanel
{
private ImageIcon menu_button;
private MouseListener listener = new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
// Detects if the Video button was pressed
if (e.getPoint().x > 15 && e.getPoint().x < 183 && e.getPoint().y > 15 && e.getPoint().y < 85)
{
System.out.println("Menu Button Pressed");
new demo_menu();
}
}
};
// Paints the content to the screen
public void paint(Graphics g)
{
super.paintComponent(g);
menu_button.paintIcon(this, g, 15, 15);
}
// main screen constructor
public demo_main_screen()
{
addMouseListener(listener);
menu_button = new ImageIcon("res/menu_but.png");
setBackground(Color.white);
setPreferredSize(new Dimension(1280, 720));
setFocusable(true);
}
}
Code 3:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class demo_menu extends JPanel
{
private ImageIcon menu, exit_but;
private MouseListener listener = new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
if (e.getPoint().x > 230 && e.getPoint().x < 255 && e.getPoint().y > 15 && e.getPoint().y < 48)
{
return;
}
}
};
// main screen constructor
public demo_menu()
{
addMouseListener(listener);
menu = new ImageIcon("res/menu.png");
exit_but = new ImageIcon("res/exit_but.png");
setBackground(Color.white);
setPreferredSize(new Dimension(1280, 720));
setFocusable(true);
}
// Paints the content to the screen
public void paint(Graphics g)
{
super.paintComponent(g);
menu.paintIcon(this, g, 0, 0);
exit_but.paintIcon(this, g, 230, 15);
System.out.println("repaint");
}
}