Mouse event doesn't work in java for some reason - java

Mouse event appears not to work, and i can't find out, why.
I added a debug output at imgEdit.drawDot and there's no output at the console. I'm a newbie in java, so my code may seem to be very bad, as well as my english
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
/**
* Created by doctor on 12/29/15.
*/
public class MainUI {
Window mainWindow;
MainUI() {
mainWindow = new Window();
}
}
class Window extends JFrame {
Window() {
setBounds(0, 0, 600, 400);
setTitle("RebBrush");
Panel mainPanel = new Panel();
Container mainCont = getContentPane();
mainCont.setLayout(null);
mainCont.add(mainPanel);
setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
class Panel extends JPanel {
private ImageEdit imgEdit;
private JLabel imgLabel;
Panel() {
setLayout(null);
imgEdit = new ImageEdit(600, 400);
imgLabel = new JLabel(new ImageIcon(imgEdit.getImage()));
imgLabel.setBounds(0, 0, 600, 400);
add(imgLabel);
addMouseMotionListener(new MouseMotionListener() {
#Override
public void mouseDragged(MouseEvent e) {
imgEdit.drawDot(e.getX(), e.getY());
}
#Override
public void mouseMoved(MouseEvent e) {
}
});
}
}

Simply getting rid of the null layouts did the trick for me. I'm not sure what ImageEdit is (some other class you've defined?), but by running the following I see "Mouse Dragged" show up in the console, so the mouseDragged method is definitely being called. Just uncomment the imageEdit stuff to put it back in.
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
/**
* Created by doctor on 12/29/15.
*/
public class MainUI {
Window mainWindow;
MainUI() {
mainWindow = new Window();
}
public static void main(String[] args) {
new MainUI();
}
}
class Window extends JFrame {
Window() {
setBounds(0, 0, 600, 400);
setTitle("RebBrush");
Panel mainPanel = new Panel();
Container mainCont = getContentPane();
mainCont.add(mainPanel);
setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
class Panel extends JPanel {
//private ImageEdit imgEdit;
private JLabel imgLabel;
Panel() {
//imgEdit = new ImageEdit(600, 400);
//imgLabel = new JLabel(new ImageIcon(imgEdit.getImage()));
//imgLabel.setBounds(0, 0, 600, 400);
//add(imgLabel);
addMouseMotionListener(new MouseMotionListener() {
#Override
public void mouseDragged(MouseEvent e) {
System.out.println("Mouse Dragged");
//imgEdit.drawDot(e.getX(), e.getY());
}
#Override
public void mouseMoved(MouseEvent e) {
}
});
}
}

Related

Mouse Coordinates keep getting on top of one another -Java

I am trying to get the mouse coordinates display in the panel but each time I move the cursor the message and new coordinates are being displayed on the previous one.I am using MouseMotionListener with JPanel. I can't figure out the problem.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.event.MouseMotionListener;
public class Main extends JPanel implements MouseMotionListener {
public JLabel label;
public static void main(String[] args) {
new Main();
JFrame frame = new JFrame();
frame.setTitle("MouseCoordinates");
frame.setSize(400, 400);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
Container contentPane = frame.getContentPane();
contentPane.add(new Main());
frame.setVisible(true);
}
public Main() {
setSize(400, 400);
label = new JLabel("No Mouse Event Captured", JLabel.CENTER);
add(label);
addMouseMotionListener(this);
}
public void mouseMoved(MouseEvent e) {
label.setText("Mouse Cursor Coordinates => X:" + e.getX() + " |Y:" + e.getY());
}
public void mouseDragged(MouseEvent e) {}
}
You're creating Main twice.
public class Main extends JPanel implements MouseMotionListener {
public JLabel label;
public static void main(String[] args) {
Main m = new Main();// create an object and reference it
JFrame frame = new JFrame();
frame.setTitle("MouseCoordinates");
frame.setSize(400, 400);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
Container contentPane = frame.getContentPane();
contentPane.add(m);
frame.setVisible(true);
}
//...
your problem was creating the Main object twice (which is a jpanel) and then the writing appeared twice. if you give the Main object a reference, then your problem should be fixed.

I've got a few problems resizing Java Swing Components

I am building a Java Swing app, which I want it will work this way:
When you resize the window, the JScrollPane object (which is within a JSplitPane) should redimension its minimum, maximum and preferred size taking as reference the current window width.
I fixed this settings on the method componentResized() of ComponentAdapter class, however, it doesn't work as suppose must do.
This is the code. I wish you test it on your pc and can help me.
Thanks a lot for your time payed.
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.*;
public class ComVisor extends JFrame
{
private JList imagesList;
private JPanel imagePanel;
private JSplitPane mainPanel;
private JScrollPane scrollPanelRight;
private int width;
public ComVisor(String nameApplication)
{
setFrame(nameApplication);
setComponents();
}
private void setFrame(String nameApplication)
{
setLayout(new BorderLayout(1, 3));
setTitle(nameApplication);
setMinimumSize(new Dimension(400, 200));
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(new Dimension(Toolkit.getDefaultToolkit().getScreenSize()));
setLocationRelativeTo(null);
this.addWindowListener(
new WindowAdapter()
{
#Override
public void windowClosing(WindowEvent e)
{
JOptionPane.showMessageDialog(ComVisor.this, nameApplication + "-Salida");
return;
}
}
);
this.addComponentListener(
new ComponentAdapter()
{
#Override
public void componentResized(ComponentEvent E)
{
width = getWidth();
scrollPanelRight.setPreferredSize(new Dimension(width / 3, 0));
scrollPanelRight.setMinimumSize(new Dimension(width / 7, 0));
scrollPanelRight.setMaximumSize(new Dimension(width / 5 * 4, 0));
return;
}
}
);
}
private void setComponents()
{
String[] a = {"dsdsdsd", "dsdsdkkhskj", "dskhkjdhskjdhksdh", "sdskdhskjhds"};
JButton b = new JButton("Soy un boton xD");
JPanel p = new JPanel();
imagesList = new JList(a);
p.add(b);
imagesList.setVisibleRowCount(100);
scrollPanelRight = new JScrollPane(imagesList);
mainPanel = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, scrollPanelRight, p);
add(mainPanel, BorderLayout.CENTER);
return;
}
private class Manejador implements ActionListener
{
#Override
public void actionPerformed(ActionEvent listener)
{
return;
}
}
}
and this is the main class, which calls a Comvisor object
import static javax.swing.SwingUtilities.invokeLater;
public class Principal
{
public static void main(String[] args)
{
invokeLater(
new Runnable()
{
#Override
public void run()
{
new ComVisor("ComVisor").setVisible(true);
return;
}
}
);
return;
}
}

How do you make text in a frame change dependent on cursor position?

I have a program that is basically just supposed to change the text of a label when your cursor enters a polygon that is shown on the JPanel. I have tried a few different things with nothing working. Currently I am trying an if statement to make it choose which button to add but it still doesn't change if i move my cursor into the polygon. when the cursor is outside of the polygon the label should say "point is not in the polygon" and when inside it should say "point is in the polygon". Any help would be greatly appreciated.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Chapter3Lab1 extends JFrame{
private RegularPolygonPanel canvas = new RegularPolygonPanel();
public Chapter3Lab1()
{
JPanel panel = new JPanel();
add(canvas, BorderLayout.CENTER);
add(panel, BorderLayout.SOUTH);
canvas.setFocusable(true);
canvas.requestFocusInWindow();
}
public static void main (String[] args)
{
String isInside = "The point is in the polygon";
String notInside = "The point is not in the polygon";
//Create a Polygon object
Polygon polygon = new Polygon();
polygon.addPoint(40,20);
polygon.addPoint(70,40);
polygon.addPoint(60,80);
polygon.addPoint(45,45);
polygon.addPoint(20,60);
JLabel label = new JLabel(isInside, JLabel.CENTER);
JLabel notlabel = new JLabel(notInside, JLabel.CENTER);
Chapter3Lab1 frame = new Chapter3Lab1();;
frame.setTitle("Chapter 3 Lab 1");
frame.setLayout(new FlowLayout());
frame.setLocationRelativeTo(null);// Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200,200);
while (true)
{
PointerInfo a = MouseInfo.getPointerInfo();
Point b = a.getLocation();
int x = (int) b.getX();
int y = (int) b.getY();
if(polygon.contains(x, y) == false)
{
frame.remove(label);
frame.add(notlabel);
}
else
{
frame.remove(notlabel);
frame.add(label);
}
frame.setVisible(true);
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
class RegularPolygonPanel extends JPanel
{
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
//Create a Polygon object
Polygon polygon = new Polygon();
polygon.addPoint(40,20);
polygon.addPoint(70,40);
polygon.addPoint(60,80);
polygon.addPoint(45,45);
polygon.addPoint(20,60);
//Draw the polygon
g.drawPolygon(polygon);
}
public Dimension getPreferredSize()
{
return new Dimension(200,200);
}
}
}
Start by taking a look at How to Write a Mouse Listener
You will need to maintain a reference to the Polygon object and make use of it's contains method to determine if the mouse is within the Polygon itself...
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private RegularPolygonPanel polyPanel;
private JLabel label;
public TestPane() {
polyPanel = new RegularPolygonPanel();
polyPanel.addMouseMotionListener(new MouseAdapter() {
#Override
public void mouseMoved(MouseEvent e) {
if (polyPanel.isWithinPolygon(e.getPoint())) {
label.setText("Is inside");
} else {
label.setText("Is outside");
}
}
});
label = new JLabel("...");
setLayout(new BorderLayout());
add(polyPanel);
add(label, BorderLayout.SOUTH);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
class RegularPolygonPanel extends JPanel {
private Polygon polygon;
public RegularPolygonPanel() {
//Create a Polygon object
polygon = new Polygon();
polygon.addPoint(40, 20);
polygon.addPoint(70, 40);
polygon.addPoint(60, 80);
polygon.addPoint(45, 45);
polygon.addPoint(20, 60);
}
public boolean isWithinPolygon(Point p) {
return polygon.contains(p);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
//Draw the polygon
g.drawPolygon(polygon);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}

Making a single component full screen

I'm trying to make a JPanel go full screen when you click a button, and back again when you press escape.
I've managed to get the window to go full screen, but because of the whole thing about adding components removing them from other containers, I end up with a blank JPanel.
I chose to make a separate JFrame to render full screen, the class of which is as follows (note that this is an inner class, so myPanel refers to a panel that already exists in MyJFrame):
public class FullScreen extends JFrame {
private static final long serialVersionUID = 1L;
private GraphicsDevice device;
private boolean isFullScreen;
public FullScreen() {
this.setContentPane(myPanel);
this.setUndecorated(true);
// Fullscreen return
this.addKeyListener(new KeyListener() {
#Override
public void keyPressed(KeyEvent e) {
// Exit fullscreen when ESC pressed
if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
exitFullScreen();
}
}
#Override
public void keyReleased(KeyEvent e) {
}
#Override
public void keyTyped(KeyEvent e) {
}
});
}
public void enterFullScreen() {
if (!isFullScreen) {
// Get the current device
GraphicsEnvironment graphicsEnvironment =
GraphicsEnvironment.getLocalGraphicsEnvironment();
device = graphicsEnvironment.getDefaultScreenDevice();
if (device.isFullScreenSupported()) {
// Make the current window invisible
MyJFrame.this.setVisible(false);
// Set the full screen window
device.setFullScreenWindow(this);
isFullScreen = true;
}
}
}
public void exitFullScreen() {
if (isFullScreen) {
// Reset the full screen window
device.setFullScreenWindow(null);
MyJFrame.this.setVisible(true);
isFullScreen = false;
}
}
}
Any other bright ideas on how to accomplish this?
Something like this seems to do it alright (to be improved and adapted):
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
class TestFullScreenPanel {
private static class FSPanel implements ActionListener {
private JPanel panel;
private JButton button;
private boolean fullScreen = false;
private Container previousContentPane;
public FSPanel(String label) {
panel = new JPanel(new BorderLayout());
button = new JButton(label);
button.addActionListener(this);
panel.add(button);
}
public JComponent getComponent() {
return panel;
}
#Override
public void actionPerformed(ActionEvent e) {
if (!fullScreen) {
goFullScreen();
} else {
ungoFullScreen();
}
}
private void goFullScreen() {
Window w = SwingUtilities.windowForComponent(button);
if (w instanceof JFrame) {
JFrame frame = (JFrame) w;
frame.dispose();
frame.setUndecorated(true);
frame.getGraphicsConfiguration().getDevice().setFullScreenWindow(w);
previousContentPane = frame.getContentPane();
frame.setContentPane(button);
frame.revalidate();
frame.repaint();
frame.setVisible(true);
fullScreen = true;
}
}
private void ungoFullScreen() {
Window w = SwingUtilities.windowForComponent(button);
if (w instanceof JFrame) {
JFrame frame = (JFrame) w;
frame.dispose();
frame.setUndecorated(false);
frame.getGraphicsConfiguration().getDevice().setFullScreenWindow(null);
frame.setContentPane(previousContentPane);
panel.add(button);
frame.revalidate();
frame.repaint();
frame.setVisible(true);
fullScreen = false;
}
}
}
TestFullScreenPanel() {
final JFrame f = new JFrame(TestFullScreenPanel.class.getSimpleName());
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
f.add(new FSPanel("Center").getComponent(), BorderLayout.CENTER);
f.add(new FSPanel("North").getComponent(), BorderLayout.NORTH);
f.add(new FSPanel("South").getComponent(), BorderLayout.SOUTH);
f.add(new FSPanel("West").getComponent(), BorderLayout.WEST);
f.add(new FSPanel("East").getComponent(), BorderLayout.EAST);
f.setSize(800, 600);
f.setLocationByPlatform(true);
f.setVisible(true);
}
public static void main(String[] args) {
// start the GUI on the EDT
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestFullScreenPanel();
}
});
}
}
PS: disposal of the JFrame is only there to change the setUndecorated state.
don't extend JFrame, create this Object an local variable
JFrame by default never react to the KeyEvents, set KeyListener to the JPanel
don't to use KeyListener for Swing JComponents, otherwise have to JPanel#setFocusable
use KeyBindings instead of KeyListener
use Escape by #camickr
.
import java.awt.Dimension;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
public class FullScreen {
private static final long serialVersionUID = 1L;
private GraphicsDevice device;
private JButton button = new JButton("Close Meeee");
private JPanel myPanel = new JPanel();
private JFrame frame = new JFrame();
public FullScreen() {
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
myPanel.setFocusable(true);
myPanel.add(button);
frame.add(myPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setUndecorated(true);
frame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke("ENTER"), "clickENTER");
frame.getRootPane().getActionMap().put("clickENTER", new AbstractAction() {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
exitFullScreen();
}
});
enterFullScreen();
frame.setVisible(true);
// code line for #MOD
// from http://stackoverflow.com/questions/15152297/how-to-get-extendedstate-width-of-jframe
Runnable doRun = new Runnable() {
#Override
public void run() {
System.out.println(frame.getBounds());
}
};
SwingUtilities.invokeLater(doRun);
}
private void enterFullScreen() {
GraphicsEnvironment graphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
device = graphicsEnvironment.getDefaultScreenDevice();
if (device.isFullScreenSupported()) {
device.setFullScreenWindow(frame);
frame.validate();
}
}
private void exitFullScreen() {
device.setFullScreenWindow(null);
myPanel.setPreferredSize(new Dimension(400, 300));
frame.pack();
}
public static void main(String[] args) {
Runnable doRun = new Runnable() {
#Override
public void run() {
FullScreen fullScreen = new FullScreen();
}
};
SwingUtilities.invokeLater(doRun);
}
}
Here's my class built into an example that works very nicely. I'm sure I'm not disposing and validating the frame properly so please comment on it so I can update it.
public class FullScreenExample extends JFrame {
public class FullScreen {
private GraphicsDevice device;
private JFrame frame;
private boolean isFullScreen;
public FullScreen() {
frame = new JFrame();
JPanel content = new JPanel();
content.setLayout(new BorderLayout());
frame.setContentPane(content);
frame.setUndecorated(true);
// Full screen escape
frame.addKeyListener(new KeyListener() {
#Override
public void keyPressed(KeyEvent e) {
// Exit full screen when ESC pressed
if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
exitFullScreen();
}
}
#Override
public void keyReleased(KeyEvent e) {}
#Override
public void keyTyped(KeyEvent e) {}
});
}
public void enterFullScreen() {
if (!isFullScreen) {
// Get the current device
GraphicsConfiguration config = FullScreenExample.this.getGraphicsConfiguration();
device = config.getDevice();
// Remove the panel from the wrapper
myWrapper.remove(myPanel);
// Add the panel to the full screen frame
frame.getContentPane().add(myPanel);
// Set the full screen window
device.setFullScreenWindow(frame);
isFullScreen = true;
}
}
public void exitFullScreen() {
if (isFullScreen) {
// Remove the fractal from the full screen frame
frame.getContentPane().remove(myPanel);
// Add the panel back to the wrapper
myWrapper.add(myPanel);
// Disable full screen
device.setFullScreenWindow(null);
// Dispose frame
frame.dispose();
// Revalidate window
FullScreenExample.this.validate();
isFullScreen = false;
}
}
}
/*
* This example uses a main content panel, myPanel
* and a wrapper to host the panel in the main JFrame, myWrapper.
*/
private JPanel myPanel, myWrapper;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
FullScreenExample frame = new FullScreenExample();
frame.init();
frame.setVisible(true);
}
});
}
public void init() {
// Generate example main window
JPanel content = new JPanel();
content.setBorder(new EmptyBorder(5, 5, 5, 5));
content.setLayout(new BorderLayout());
this.setContentPane(content);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myPanel = new JPanel();
myPanel.setBackground(Color.BLUE);
// Full screen button and listener
JButton fullscreen = new JButton("Full Screen");
final FullScreen fs = new FullScreen();
fullscreen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
fs.enterFullScreen();
}
});
myWrapper = new JPanel();
myWrapper.setLayout(new BorderLayout());
myWrapper.add(myPanel);
content.add(myWrapper, BorderLayout.CENTER);
content.add(fullscreen, BorderLayout.SOUTH);
this.setBounds(100, 100, 350, 350);
}
}

Removing JPanel from a JFrame

I am trying to remove a JPanel not hide it but i can't find anything that works.
This is the code in the panel that needs to remove itself when a button is pressed:
play.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Frame frame = new Frame(); //referencing to my JFrame class (this class is a JPanel)
//need to remove this panel on this line
frame.ThreeD(); // adds a new panel
}
});
UPDATED
This is the full code:
package ThreeD;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.UIManager;
import Run.Frame;
public class Launcher extends JPanel{
private JButton play, options, help, mainMenu;
private Rectangle rplay, roptions, rhelp, rmainMenu;
private int buttonWidthLocation, buttonWidth, buttonHeight;
private int width = 1280;
public Launcher() {
this.setLayout(null);
drawButtons();
}
private void drawButtons() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(Exception e) {
e.printStackTrace();
}
play = new JButton("Play");
options = new JButton("Options");
help = new JButton("Help");
mainMenu = new JButton("Main Menu");
buttonWidthLocation = (width / 2) - (buttonWidth / 2);
buttonWidth = 80;
buttonHeight = 40;
rplay = new Rectangle(buttonWidthLocation, 150, buttonWidth, buttonHeight);
roptions = new Rectangle(buttonWidthLocation, 300, buttonWidth, buttonHeight);
rhelp = new Rectangle(buttonWidthLocation, 450, buttonWidth, buttonHeight);
rmainMenu = new Rectangle(buttonWidthLocation, 600, buttonWidth, buttonHeight);
play.setBounds(rplay);
options.setBounds(roptions);
help.setBounds(rhelp);
mainMenu.setBounds(rmainMenu);
add(play);
add(options);
add(help);
add(mainMenu);
play.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Frame frame = new Frame();
//need to remove this panel here
frame.ThreeD();
}
});
options.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("options");
}
});
help.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("help");
}
});
mainMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("mainMenu");
}
});
}
}
And this is my Frame class:
package Run;
import javax.swing.*;
import ThreeD.Display;
import ThreeD.Launcher;
import TowerDefence.Window;
import java.awt.*;
import java.awt.image.BufferedImage;
public class Frame extends JFrame{
public static String title = "Game";
/*public static int GetScreenWorkingWidth() {
return java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().width;
}*/
/*public static int GetScreenWorkingHeight() {
return java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().height;
}*/
//public static Dimension size = new Dimension(GetScreenWorkingWidth(), GetScreenWorkingHeight());
public static Dimension size = new Dimension(1280, 774);
public static void main(String args[]) {
Frame frame = new Frame();
System.out.println("Width of the Frame Size is "+size.width+" pixels");
System.out.println("Height of the Frame Size is "+size.height+" pixels");
}
public Frame() {
setTitle(title);
setSize(size);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ThreeDLauncher();
}
public void ThreeDLauncher() {
Launcher launcher = new Launcher();
add(launcher);
setVisible(true);
}
public void TowerDefence() {
setLayout(new GridLayout(1, 1, 0, 0));
Window window = new Window(this);
add(window);
setVisible(true);
}
public void ThreeD() {
BufferedImage cursor = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
Cursor blank = Toolkit.getDefaultToolkit().createCustomCursor(cursor, new Point(0, 0), "blank");
getContentPane().setCursor(blank);
Display display = new Display();
add(display);
setVisible(true);
display.start();
}
}
Basically - you are creating new instance of Frame in line:
Frame frame = new Frame(); //referencing to my JFrame class (this class is a JPanel)
New instance of Frame is not visible, and you're try to remove your Launcher from not visible new Frame. But this is wrong - you should remove Launcher from Frame that you created previously in main function (that is: parent of Launcher component).
Here goes an example:
public class TestFrame extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
TestFrame frame = new TestFrame();
frame.getContentPane().add(new MyPanel(frame));
frame.setSize(200, 200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
And MyPanel class:
public class MyPanel extends JPanel {
public MyPanel(final TestFrame frame) {
JButton b = new JButton("Play");
add(b);
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Container pane = frame.getContentPane();
pane.remove(MyPanel.this);
JPanel otherPanel = new JPanel();
otherPanel.add(new JLabel("OtherPanel"));
pane.add(otherPanel);
pane.revalidate();
}
});
}
}
In your example you should add a reference to Frame in your Launcher constructor:
public Launcher(Frame frame) {
this.frame = frame;
...
Init Launcher:
public void ThreeDLauncher() {
Launcher launcher = new Launcher(this);
and use:
play.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//need to remove this panel here
frame.getContentPane().remove(Launcher.this);
frame.ThreeD();
}
});
Say your panel is myPanel you can remove it from the main frame by:
frame.getContentPane().remove(myPanel);

Categories