This question already has answers here:
Implementing back/forward buttons in Swing
(3 answers)
Closed 4 years ago.
I am building a menu for my java game and i need to be able to switch to my game JPanel when i click a button. Here is what i have
public class Menu extends JPanel implements ActionListener {
protected JFrame frame;
JButton btnStart = new JButton();
public Menu(JFrame j) {
super();
frame = j;
//creating and styling button
btnStart.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
StartGame();
}
});
}
private void StartGame(){
frame.getContentPane().removeAll();
frame.getContentPane().add(new Main(frame));
frame.repaint();
}
`
public class Main extends Universe implements ActionListener {
Timer timer = new Timer(75, this);
JFrame frame;
//#Override
public void actionPerformed(ActionEvent e) {
repaint();;
if(isLoss()){
timer.stop();
}
//update cretures
}
public Main(JFrame frame) {
super();
frame.setLayout(null);
frame.setLayout(null);
//frame.getContentPane().setLayout(null);
this.setBackground(Color.BLACK);
this.map = new Map();
StartUpHeight = 100;
this.Size = 30;
//this.playerCol = new Collision(map, pacman, Size);
pacman = new Player(1*Size, 4*Size, Size / 5, map, this.Size);
red = new RedGhost(9*Size, 8*Size, Size / 6, map, pacman, this.Size);
pinky = new PinkGhost(8*Size, 10*Size, Size / 6, map, pacman, this.Size);
inky = new BlueGhost(9*Size, 10*Size, Size / 6, map, pacman, this.Size, red);
clyde = new YellowGhost(10*Size, 10*Size, Size/6, map, pacman, this.Size);
timer.start();
this.frame = frame;
this.frame.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
pacman.keyPressed(e, Size);
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
pacman.keyReleased(e);
}
});
setUpPanel();
}
#Override
public void paint(Graphics g) {
//drawing map
//drawing pacman
//drawing ghosts
}
`
I tried everything i found on the internet so far. Main extends from jpanel and implements action listener just like Menu. After this code is executed my jframe just clears. I tried to repaint it did not help. Any help is appreciated. Thanks
When you call repaint() method you should also call revalidate() method.
Also, can you show your Main class code?
And have you added your button to your frame?
Related
So I created two objects from tank1 class, and their names are tank1 and tank2. I want tank1 to shift right with RIGHT key and to shift left with LEFT key, and tank2 to shift right with D and to shift left with A key. But when I finished compiling my code, the tank2 shift left with A, and LEFT keys, and shift right with D, and RIGHT keys, and tank1 doesn't shift with any key at all. Is there any way to fix this so tank 1 shift with LEFT, RIGHT key?
here is my gridbasegame class:
public class GridBasedGameDriver {
private JFrame frame = new JFrame("my world");
private JPanel panel;
private List<Drawable> drawables= new ArrayList();
private Terrain terrain;
private Tank1 Tank1;
private Tank1 Tank2;
public static void main(String[] args) {
new GridBasedGameDriver().start();
}
private void start() { // REPAINT
setUpGame();
frame.setBackground(new Color(127, 127, 127));
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel() { public void paintComponent(Graphics g) { super.paintComponent(g); drawGame(g); } }; // what does paint componet and draw game do,
//and where does the
//super come from?
panel.setPreferredSize(new Dimension(800,600)); // doesn't matter, can be set again manually
frame.add(panel); // so frame needs to add panel
frame.pack(); // no idea, probably not important
// int b= (int)(Math.random()*100+100); //100-199, only here for fun doesn't change a damn thing
panel.getInputMap().put(KeyStroke.getKeyStroke("RIGHT"),"slideRight");
panel.getActionMap().put("slideRight",new AbstractAction(){
public void actionPerformed(ActionEvent arg0) {
Tank1.moveRight();
panel.repaint();
}
});
panel.requestFocusInWindow();
panel.getInputMap().put(KeyStroke.getKeyStroke("LEFT"),"slideLeft");
panel.getActionMap().put("slideLeft",new AbstractAction(){
public void actionPerformed(ActionEvent arg0) {
Tank1.moveleft();
panel.repaint();
}
});
panel.requestFocusInWindow();
panel.getInputMap().put(KeyStroke.getKeyStroke("D"),"slideRight");
panel.getActionMap().put("slideRight",new AbstractAction(){
public void actionPerformed(ActionEvent arg0) {
Tank2.moveRight();
panel.repaint();
}
});
panel.requestFocusInWindow();
panel.getInputMap().put(KeyStroke.getKeyStroke("A"),"slideLeft");
panel.getActionMap().put("slideLeft",new AbstractAction(){
public void actionPerformed(ActionEvent arg0) {
Tank2.moveleft();
panel.repaint();
}
});
panel.requestFocusInWindow();
setUpObjects();
frame.repaint();
}
private void setUpObjects() {
terrain = new Terrain(panel.getWidth(), panel.getHeight()); // where does the panel come from?
terrain.initialize();
List<Integer> b=terrain.getlist();
Tank1 = new Tank1(20,0,b);
Tank2 = new Tank1(740,1,b);
drawables.add(terrain); // I get it, so the terrain has drawable, and once it gets added to drawable array it implements its own drawable
drawables.add(Tank1);
drawables.add(Tank2);
}
public void drawGame(Graphics g) {
for(Drawable dr:drawables) {
dr.draw(g);
}
}
and here is my tank1 class:
public class Tank1 implements Drawable {
public int gi;
public int it;
public List<Integer> b;
List<Integer> Krell = new ArrayList<>();
public Tank1(int gi, int it, List<Integer> b) {
this.b=b;
this.gi=gi;
this.it=it;
}
public void moveleft() {
gi=gi-1;
}
public void moveRight() {
gi=gi+1;
}
public void draw(Graphics g) {
// TODO Auto-generated method student
if (it==0) {
g.setColor(new Color(230,50,58)); // draws that recoatlve
}
if(it==1) {
g.setColor(new Color(120,160,60)); // draws that recoatlve
}
g.fillRect(gi, b.get(gi)-25, 25, 25); //draws that rectangle
}
}
Might first thought is, JPanel is not focusable by default, so requesting focus in the window won't do anything. Besides, the point of using key bindings like this is to avoid having to deal with "grab focus" style hacks.
There are a couple of variations to getInputMap, one which allows you to define the focus context in which the bindings will be triggered. You might consider using WHEN_IN_FOCUSED_WINDOW, for example...
panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("RIGHT"),"slideRight");
I have a Java program with two textareas and a button. I want to allow the user to write one one textarea using a touch pen or mouse and when he/she clicks the button, the drawn content should be send to textarea no 2.
So the textarea where the user is writing on, I gave a mousemotion listener with paintComponent method in it.
When I run the application, I have realized that texarea method getText() and setText() can't set or get the drawn content.
Is there way I can achieve the above task? I have also tried JPanel but it doesn't have the setContent() method.
I appreciate any help.
This is my first textarea where user is writing on with touchpen.
public class Area1 extends JTextArea {
int pointcount = 0;
Point[] points = new Point[10000];
public Area1() {
addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent event) {
if (pointcount < points.length) {
points[pointcount] = event.getPoint();
++pointcount;
repaint();
}
}
});
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 0; i < pointcount; i++) {
g.fillOval(points[i].x, points[i].y, 4, 4);
}
}
}
this is my overall application with textarea2 and button
public class Handwriting extends JFrame {
private JTextArea area2;
private JButton b1;
Area1 area1;
public Handwriting() {
Box box = Box.createHorizontalBox();
area1 = new Area1();
area1.setRows(30);
area1.setColumns(30);
area2 = new JTextArea(30, 30);
b1 = new JButton("Copy");
b1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
if (event.getSource() == b1) {
area2.setText(area1.getText());
}
}
});
box.add(area1);
box.add(b1);
box.add(area2);
add(box);
}
public static void main(String[] args) {
Handwriting hand = new Handwriting();
hand.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
hand.setSize(500, 500);
hand.setVisible(true);
}
}
One possible solution would be to make one class as a Inner Class of the other , that way even private instance fields can be accessed
Code works, my bad. But I'm still open to suggestions on how to improve or make the code more elegant.
I have created this layout and I want to be able to draw a circle whenever the user clicks on the white area.
Couldn't post an image, so here is the link
The white area is basically a rectangle. But something with my code isn't working, it just doesn't respond to mouse clicks. When I tried to see if it responds to mouseDragged it worked perfectly but this isn't what I need.
Here is my code, some "tests" are put as /comments/ but neither of them work as intended.
I would be very grateful for help. Here is my code:
import java.awt.*;
import java.awt.Graphics;
import javax.swing.*;
public class CitiesMapPanel extends JPanel implements MouseListener {
private JButton cmdAddWay, cmdFindPath, cmdClearMap, cmdClearPath;
private JLabel lblFrom, lblTo;
private JTextField txtFrom, txtTo;
public CitiesMapPanel() {
cmdAddWay = new JButton("Add Way");
cmdFindPath = new JButton("Find Path");
cmdClearMap = new JButton("Clear Map");
cmdClearPath = new JButton("Clear Path");
lblFrom = new JLabel("From");
lblTo = new JLabel("To");
txtFrom = new JTextField(6);
txtTo = new JTextField(6);
this.addMouseListener(this);
setLayout(new BorderLayout());
add(buildGui(), BorderLayout.SOUTH);
}
private JPanel buildGui() {
JPanel buttonsBar = new JPanel();
//The "south" of the BorderLayout consist of a (2,4) GridLayout.
buttonsBar.setLayout(new GridLayout(2,4));
buttonsBar.add(lblFrom);
buttonsBar. add(txtFrom);
buttonsBar.add(lblTo);
buttonsBar.add(txtTo);
buttonsBar.add(cmdAddWay);
buttonsBar.add(cmdFindPath);
buttonsBar.add(cmdClearMap);
buttonsBar.add(cmdClearPath);
return buttonsBar;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.white);
g.fillRect(0, 0, this.getSize().height, this.getSize().width);
}
public static void main(String[] args) {
JFrame frame = new JFrame("layout");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(530, 550);
CitiesMapPanel gui = new CitiesMapPanel();
frame.add(gui);
frame.setVisible(true);
}
/*abstract private class MyMouseListner implements MouseListener{
public void mouseClicked(MouseEvent e){
int x = e.getX();
int y = e.getY();
Graphics g = getGraphics();
g.setColor(Color.black);
g.fillOval(x,y,15,15);
}
}*/
#Override
public void mouseClicked(MouseEvent e) {
int x = e.getX();
int y = e.getY();
Graphics g = getGraphics();
g.setColor(Color.black);
g.fillOval(x,y,15,15);
System.out.println("test");
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
}
The click listener is not the problem. Your approach to painting is simply wrong. You can't do a getGraphic, paint on it, and expect the result to be presented. In Swing (AWT) things work fundamentally different. You need to either create an off screen image that you paint to and that you then present on screen in your paintComponent method, or you need to track the objects you want to paint in a data structure and paint those in your paintComponent method. You can trigger a repaint in your click listener by calling repaint so the UI subsystems knows about the changed state that requires a repaint of your component.
Read more about the basics in the Swing painting tutorial.
I followed steps from many articles but the undo system not behaving as expected. first, the undo button goes back correctly till the first edit but can't go beyond the first edit. also, when I click undo and then re-edit it circles back to the last edit. It's better if you execute the code and see yourself.
Another question, while I'm trying to figure out a solution I read that saving images in an Array is memory intensive, is that true even for this simple paint class, and what is the alternative? saving the image's graphic?
import java.awt.*;import java.awt.image.BufferedImage;import java.awt.event.*;import java.util.ArrayList;import javax.swing.*;import javax.swing.event.*;import javax.swing.undo.*;
public class Painter extends JFrame{
//attributes//
Painter.Canvas canvas;
JPanel controlPanel;
JButton undoButton;
JButton redoButton;
PainterHandler handler;
Container container;
//undo system elements//
UndoManager undoManager; // history list
UndoableEditSupport undoSupport; // event support
//constructor//
public Painter()
{
super("Painter-test");
controlPanel = new JPanel();
undoButton = new JButton("undo");
redoButton = new JButton("redo");
handler = new Painter.PainterHandler();
container = getContentPane();
canvas = new Painter.Canvas();
this.organizer();
}// end constructor
public void organizer()
{
controlPanel.setLayout(null);
controlPanel.setPreferredSize(new Dimension(120,350));
controlPanel.setBackground(null);
//add undo listeners to undo/redo buttons.
undoButton.addActionListener( new AbstractAction()
{
public void actionPerformed( ActionEvent evt )
{ undoManager.undo(); refreshCanvas(); refreshUndoRedo();}
});
redoButton.addActionListener(new AbstractAction()
{
public void actionPerformed(ActionEvent evt )
{ undoManager.redo(); refreshCanvas(); refreshUndoRedo(); }
});
// initilize the undo/redo system.
undoManager= new UndoManager();//history list
// event support, instance.
undoSupport = new UndoableEditSupport();
//add undoable edit listener to the support instance.
undoSupport.addUndoableEditListener(new UndoableEditListener()
{
public void undoableEditHappened (UndoableEditEvent event)
{
UndoableEdit edit = event.getEdit();
undoManager.addEdit( edit );
refreshUndoRedo();
}
});
refreshUndoRedo();
canvas.setPreferredSize(new Dimension(600,400));
//place buttons on panel.
undoButton.setBounds(10, 160, 80, 20);
redoButton.setBounds(10, 181, 80, 20);
//add components to panel.
controlPanel.add(undoButton);
controlPanel.add(redoButton);
//add panels to window.
container.add(canvas,BorderLayout.WEST);
container.add(controlPanel, BorderLayout.EAST);
}//end organizerTab3()
public void refreshCanvas() { canvas.repaint(); }
//refresh undo, redo buttons.
public void refreshUndoRedo()
{
// refresh undo
undoButton.setEnabled( undoManager.canUndo() );
// refresh redo
redoButton.setEnabled( undoManager.canRedo() );
}
//INNER CLASSES
ArrayList<BufferedImage> imagesArray = new ArrayList<BufferedImage>();
BufferedImage imageCopy;
Graphics graphics;
BufferedImage image;
int index;
private class Canvas extends JPanel
{
public Canvas()
{
//Panel properties
setSize(600,400);
setBackground(new Color(84,84,118));
image = new BufferedImage(getWidth(), getHeight(),BufferedImage.TYPE_INT_ARGB);
//add Listeners.
addMouseMotionListener(handler);
addMouseListener(handler);
}//end constructor
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
}//end inner class PaintPanel
private class PainterHandler extends MouseAdapter
{
#Override
public void mouseDragged(MouseEvent event)
{
if(event.getComponent().equals(canvas))
{
if (image != null)
{
// Paint into the image
graphics = image.getGraphics();
graphics.setColor(new Color(249,30,138));
graphics.fillOval(event.getX(), event.getY(), 20, 20);
imageCopy = new BufferedImage(canvas.getWidth(),canvas.getHeight(),BufferedImage.TYPE_INT_ARGB);
imageCopy.getGraphics().drawImage(image, 0, 0, null);
canvas.repaint();
}
}
}//end mouseDragged(MouseEvent event)
#Override
public void mouseReleased(MouseEvent event)
{
if(event.getComponent().equals(canvas))
{
//UNDO SYSTEM START//
//add image to the array.
imagesArray.add(imageCopy);
// get image's index.
index = imagesArray.indexOf(imageCopy);
//create AddEdit instance of type UndoableEdit.
UndoableEdit edit = new Painter.AddEdit(imagesArray, imageCopy,index);
// notify the listeners
undoSupport.postEdit( edit );
//UNDO SYSTEM END//
}
}
}//end MouseHandler class
private class AddEdit extends AbstractUndoableEdit
{
private ArrayList<BufferedImage> undoableImagesArray;
private BufferedImage undoableImage;
int undoableIndex;
public AddEdit(ArrayList<BufferedImage> v, BufferedImage img, int i)
{
undoableImagesArray = v;
undoableImage = img;
undoableIndex = i;
}
public void undo() throws CannotUndoException
{
undoableImagesArray.remove(undoableImage);
if(!undoableImagesArray.isEmpty())
image = (BufferedImage)undoableImagesArray.get(undoableImagesArray.size()-1);
canvas.repaint();
}
public void redo() throws CannotRedoException
{
undoableImagesArray.add(undoableImage);
image = (BufferedImage)undoableImagesArray.get(undoableImagesArray.size()-1);
canvas.repaint();
}
public boolean canUndo() { return true; }
public boolean canRedo() { return true; }
}//end class AddEdit
public static void main(String[] s)
{
Painter p = new Painter();
p.setSize(800, 500);
p.setVisible(true);
p.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}//END CLASS Painter
You don't use undoableIndex. In fact you should not remove the image from array but instead move the pointer.
canUndo() should return true if the list is not empty and the pointer >0
canRedo() should return true if the pointer!= size() of the list
Hi I want to make my JPanel disappear so I wrote these lines of code
removeAll();
updateUI();
revalidate();
That only made the JComponents and JButtons disappear. I would like to make the images that I have displayed with the paint method disappear also. If I do setVisible(false), then I cannot add another JPanel behind it.
This is my class:
package screens;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class menuScreen extends JPanel implements MouseListener{
private static final long serialVersionUID = 1L;
//-------------VARIABLES---------------//
Image wallpaper = (Image)Toolkit.getDefaultToolkit().getImage(getClass().getResource("images/wallpaper.jpg"));
Image title_text = (Image)Toolkit.getDefaultToolkit().getImage(getClass().getResource("images/title-text.png"));
ImageIcon startGameimg = new ImageIcon(Toolkit.getDefaultToolkit().getImage(getClass().getResource("images/startGame.png")));
ImageIcon optionsimg = new ImageIcon(Toolkit.getDefaultToolkit().getImage(getClass().getResource("images/options.png")));
//JButton start = new JButton(basketball);
JLabel options = new JLabel(optionsimg);
JLabel startGame = new JLabel(startGameimg);
gameScreen gS = new gameScreen();
CardLayout scenechange = new CardLayout();
JPanel scenechange1 = new JPanel (scenechange);
//-------------PAINT FUNCTION----------//
public void paintComponent(Graphics g){
g.drawImage(wallpaper,0,0,this);
g.drawImage(title_text,0,0,this);
//g.drawImage(basketball1,110,180,this);
}
//-------------CONSTRUCTOR-------------//
public menuScreen(){
scenechange.addLayoutComponent(this,"menuScreen");
scenechange.addLayoutComponent(gS,"gameScreen");
//scenechange.show(this,"menuScreen");
this.setLayout(null);
this.add(options);
this.add(startGame);
startGame.setBounds(110,180,110,110);
options.setBounds(110,300,110,110);
startGame.addMouseListener(this);
options.addMouseListener(this);
}
public void mouseClicked(MouseEvent e) {
if(e.getSource() == (startGame)){
removeAll();
revalidate();
add(gS);
}
if(e.getSource() == (options)){
setVisible(false);
}
}
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
}//END OF CLASS startingScreen
Thanks in advance.
First, don't call updateUI, it's related to the Look and Feel and not (directly) to updating your components.
If you have provided a custom paint routine within in your panel, then you need away to stop it from painting the images (without preventing it from painting it's own content). removeXxx will remove child components that you have previously added to the container.
A little more code would be useful
UPDATE
Fisrt, the images your painting aren't components of you container, they are been "stamped", you need some way to tell the component not to the paint the images
public void paintComponent(Graphics g){
super.paintComponent(g); // this is super important
if (paintImages){ // you need to define and set this flag
g.drawImage(wallpaper,0,0,this);
g.drawImage(title_text,0,0,this);
}
}
Now, this will stop the images from been painted.
If, however, you no longer want to use the component (ie, you want to remove it from the screen so you can place a new component on the screen in its place), you need to remove this component from it's parent, which Code-Guru has suggested (so I won't steal his answer ;))
UPDATE
Okay, you had a kernel of an idea but either didn't quite know how to implement it or decided to discard it.
Basically, from the looks of your code, you were either trying to, or had, implement a CardLayout, unfortunately, you kind of got the wrong idea with it.
With CardLayout, you need to "controller", a component that is responsible for switching the screens...
public class ScreenController extends JPanel {
private static final long serialVersionUID = 1L;
//-------------VARIABLES---------------//
MenuScreen ms = new MenuScreen();
GameScreen gs = new GameScreen();
CardLayout sceneChange;
//-------------CONSTRUCTOR-------------//
public ScreenController() {
sceneChange = new CardLayout();
this.setLayout(sceneChange);
add(ms, "menuScreen");
add(gs, "gameScreen");
sceneChange.show(this, "menuScreen");
ms.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equalsIgnoreCase("startgame")) {
sceneChange.show(ScreenController.this, "gameScreen");
}
}
});
}
}//END OF CLASS startingScreen
Then you have your menu and game screens...
public class MenuScreen extends JPanel implements MouseListener {
private static final long serialVersionUID = 1L;
//-------------VARIABLES---------------//
//JButton start = new JButton(basketball);
JLabel options = new JLabel("Options");
JLabel startGame = new JLabel(" >> Start << ");
// gameScreen gS = new gameScreen();
BufferedImage wallpaper;
//-------------PAINT FUNCTION----------//
#Override
public void paintComponent(Graphics g) {
System.out.println("paint");
super.paintComponent(g);
if (wallpaper != null) {
g.drawImage(wallpaper, 0, 0, this);
}
}
//-------------CONSTRUCTOR-------------//
public MenuScreen() {
// Please handle your exceptions better
try {
wallpaper = ImageIO.read(getClass().getResource("/Menu.png"));
setPreferredSize(new Dimension(wallpaper.getWidth(), wallpaper.getHeight()));
} catch (IOException ex) {
ex.printStackTrace();
}
setLayout(new GridBagLayout());
Cursor cusor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR);
options.setCursor(cusor);
startGame.setCursor(cusor);
Font font = UIManager.getFont("Label.font").deriveFont(Font.BOLD, 48);
options.setFont(font);
startGame.setFont(font);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
this.add(options, gbc);
gbc.gridy++;
this.add(startGame, gbc);
startGame.addMouseListener(this);
options.addMouseListener(this);
}
public void mouseClicked(MouseEvent e) {
if (e.getSource() == (startGame)) {
fireActionPerformed("startGame");
}
if (e.getSource() == (options)) {
fireActionPerformed("gameOptions");
}
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void addActionListener(ActionListener listener) {
listenerList.add(ActionListener.class, listener);
}
public void removeActionListener(ActionListener listener) {
listenerList.remove(ActionListener.class, listener);
}
protected void fireActionPerformed(String cmd) {
ActionListener[] listeners = listenerList.getListeners(ActionListener.class);
if (listeners != null && listeners.length > 0) {
ActionEvent evt = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, cmd);
for (ActionListener listener : listeners) {
listener.actionPerformed(evt);
}
}
}
}
Menu Screen...
And when you click start...the game screen...
Now this is an EXAMPLE. Please try and take the time to understand what it going on in the code before you march ahead and implement it. I used by own images, you'll need to get your own..
There are several ways to stop your JPanel from "appearing" depending on exactly what you want to accomplish. One was it to to call setOpaque(false);. I'm not entirely sure how this affects custom painting, though.
Another posibility is
Container parent = getParent().remove(this);
parent.validate();
A third posibility is to add a flag in your class which is set when you click on a JLabel (or better yet a JButton -- see comments below). Then in your paintComponent() method you can check the flag and draw accordingly.
Note:
You are incorrectly using a JLabel and mouse events to respond to user input. Typically in a Swing application, we use JButtons and ActionListeners to accomplish what you are trying to do here. One advantage of this is that you only have to implement one method called onActionPerformed() and don't need to worry about adding all the mouse event handlers that you don't want to even respond to.