Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to disable a JPanel from doing anything in Java
    primarykey
    data
    text
    <p>I have a problem with disabling a JPanel from having any methods called inside of it. I set up a Frame with 2 JPanels controlling the graphics for the Frame. The problem is, if I a new JPanel to the Frame and I also remove the old JPanel that was previously there, the paint method in the old JPanel is still called.</p> <p>Here is the code I used to test this:</p> <p>The Start class:</p> <pre><code> import java.awt.Frame; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; public class Start implements WindowListener, KeyListener{ public static void main(String[] args) { new Start(); } Frame frame = new Frame("Frame"); TestPanel P1 = new TestPanel(); TestPanel P2 = new TestPanel(); static boolean active = true; public Start() { frame.setSize(500,500); frame.setLocationRelativeTo(null); frame.addWindowListener(this); frame.addKeyListener(this); frame.setVisible(true); frame.add(P1); for (Object c : frame.getComponents()){ System.out.println(c.toString()); } } @Override public void keyPressed(KeyEvent e) { if (active){ frame.remove(P1); frame.add(P2); }else{ frame.remove(P2); frame.add(P1); } active = !active; for (Object c : frame.getComponents()){ System.out.println(c.toString()); } } @Override public void windowClosing(WindowEvent e) { System.exit(0); } public void windowOpened(WindowEvent e) {} public void windowClosed(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} public void keyTyped(KeyEvent e) {} public void keyReleased(KeyEvent e) {} } </code></pre> <p>The TestPanel class:</p> <pre><code> import java.awt.Graphics; import javax.swing.JPanel; public class TestPanel extends JPanel{ boolean active = Start.active; @Override public void paint(Graphics g) { System.out.println(active); } } </code></pre> <p>This program always print "true" showing me that only the object P1 is active and that P2 is doing nothing even though its displayed on the screen.</p> <p>So what I'm asking is how to make the P1 object stop getting the paint method called when it's not on the screen and have the P2 object have its paint method called when it's being displayed.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload