repaint() method does not paint new frame - java

I have looked at a lot of answers but i still cannot find a solution. I have a JFrame and two JPanels. I want to remove the one panel and replace it with the second when a button is pressed, but the repaint() method does not refresh the frame. Please help.
Here is my code for the frame:
import javax.swing.*;
import java.awt.*;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
public class MainFrame
{
static JFrame mainFrame;
int height = 650;
int width = 1042;
public MainFrame()
{
mainFrame = new JFrame();
mainFrame.setBounds(0, 0, width, height);
mainFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
mainFrame.setResizable(false);
}
public static void main(String[] args)
{
new MainMenu();
mainFrame.setVisible(true);
}
}
This is the code for my MainMenu panel
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import static java.awt.Color.CYAN;
import static java.awt.Color.red;
public class MainMenu extends MainFrame
{
public MainMenu()
{
components();
}
//variable decleration
JPanel menuPanel;
JLabel title;
JButton periodicTable;
private void components()
{
int buttonW = 500;
int buttonH = 50;
//creating panel
menuPanel = new JPanel();
menuPanel.setLayout(null);
menuPanel.setBackground(CYAN);
//creating title label
title = new JLabel("Application Title", SwingConstants.CENTER);
title.setFont(new Font("Calibri Body", 0, 50));
title.setBounds(width / 3 - buttonW / 2, 50, buttonW, buttonH + 10);
//creating periodic table button
periodicTable = new JButton();
periodicTable.setText("Periodic Table");
periodicTable.setBounds(width / 3 - buttonW / 2, 50 + buttonH + 60, buttonW, buttonH);
periodicTable.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
periodicTableActionPerformed(event);
}
});
//adding components to panel
menuPanel.add(title);
menuPanel.add(periodicTable);
//adding panel to MainFrame
mainFrame.add(menuPanel);
}
private void periodicTableActionPerformed(ActionEvent event)
{
mainFrame.remove(menuPanel);
mainFrame.repaint();
new PeriodicTable();
mainFrame.repaint();
}
}
And finally my PeriodicTable panel
import javax.swing.*;
import java.awt.*;
public class PeriodicTable extends MainFrame
{
public PeriodicTable()
{
periodicComponents();
}
JPanel ptPanel;
private void periodicComponents()
{
ptPanel = new JPanel();
ptPanel.setLayout(null);
ptPanel.setBackground(Color.RED);
mainFrame.add(ptPanel);
}
}

I have no idea why you are extending MainFrame. Looks unnecessary to me.
I want to remove the one panel and replace it with the second when a button is pressed
Then use a CardLayout. Read the section from the Swing tutorial on How to Use CardLayout for a working example.
The tutorial will show you how to better structure your code.

Your PeriodicTable extends MainFrame. When creating new PeriodicTable you create with it new MainFrame which has its own instance of JFrame (MainFrame.mainFrame). You need to add that panel to existing mainFrame in MainMenu
I suggest removing changing your PeriodicTable class like this:
import javax.swing.*;
import java.awt.*;
public class PeriodicTable extends JPanel // Not MainFrame, but new custom panel
{
public PeriodicTable()
{
periodicComponents();
}
private void periodicComponents()
{
// You don't need ptPanel anymore, because `this` is JPanel
setLayout(null);
setBackground(Color.RED);
}
}
and change your actionPerformed function to something like this:
private void periodicTableActionPerformed(ActionEvent event)
{
mainFrame.remove(menuPanel); // Remove old panel
mainFrame.add(new PeriodicTable()); // Create and add to existing mainFrame
mainFrame.repaint(); // Just one repaint at the end
// I think it will work even without repaint, because add and remove should schedule repainting as well
}

Related

Utilize a ActionListener object from a separate JFrame class to main class

I am building a GUI program in which specific code takes place when a certain condition is meant (JButton is pressed). I have a seperate class that constructs my Jframe called "MyFrame" .
Essentially I want to know the proper way to use my use a ActionListener/ ActionEvent from my "MyFrame" class in conjunction when a JButton is pressed in which it would correlate properly in the main class.
For example i am able to initiate specific code when a JButton is pressed in my MyFrame class through the actionPerformed provided method by java in my Myframe class, I am just puzzled on how I can make the same thing work through my main class as well.
Any assistance would be appreciated
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Main {
public static void main(String[] args) {
MyFrame mf;
mf= new MyFrame();
Expenses exp ;
BudgetSystem system ;
ActionEvent e ;
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
class MyFrame extends JFrame implements ActionListener {
JFrame myFrame;
JPanel myPanel;
JLabel greetText ;
JButton addReportButton;
JButton exitButton;
ActionListener event ;
BorderLayout layout ;
MyFrame() {
myFrame = new JFrame();
myPanel = new JPanel();
greetText = new JLabel();
addReportButton = new JButton();
exitButton = new JButton();
myPanel.setBorder(null);
myFrame.setPreferredSize(new Dimension(400,300));
greetText.setText("Please choose one of the following options to begin:" );
myPanel.add(greetText);
myFrame.add(myPanel);
addReportButton.setText("Add a budget report");
addReportButton.addActionListener(this);
myPanel.add(addReportButton);
exitButton.setText("Close Program");
exitButton.addActionListener(this);
myPanel.add(exitButton);
myFrame.setVisible(true);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setLocationRelativeTo(null);
myFrame.pack();
}
#Override
public void actionPerformed(ActionEvent e) {
/*
if (e.getSource()==addReportButton)
{
JOptionPane.showMessageDialog(myFrame,"This button Works!");
}
else if (e.getSource()== dummyButton)
{
JOptionPane.showMessageDialog(myFrame,"This is the dummy button ! , you are targeting specific buttons now ! ... YOU ROCK :) ");
}else
JOptionPane.showMessageDialog(myFrame,"This is does not work :( ");
*/
}
}
I tried to make a specific ActionEvent object in main but that did not work properly.
I also tried to use a MyFrame object to access the actionPerformed method in java but that doesnt seem to work either.
If your goal is to add listeners to a JButton from another class, one option is to give the class that holds the JButton a public method that allows this to happen, for instance:
public void addMyButtonListener(ActionListener listener) {
myButton.addActionListener(listener);
}
This would allow any object that holds an instance of the class that holds the JButton to call this method and pass in a listener.
For instance:
import java.awt.Dimension;
import java.awt.event.ActionListener;
import javax.swing.*;
public class AddOutsideActionListener {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
SomeGUI mainPanel = new SomeGUI();
mainPanel.addMyButtonListener(e -> {
String message = "Message from the main method";
String title = "Message";
int type = JOptionPane.PLAIN_MESSAGE;
JOptionPane.showMessageDialog(mainPanel, message, title, type);
});
JFrame frame = new JFrame("Some GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}
class SomeGUI extends JPanel {
public static final int PREF_W = 600;
public static final int PREF_H = 400;
private JButton myButton = new JButton("My Button");
public SomeGUI() {
add(myButton);
setPreferredSize(new Dimension(PREF_W, PREF_H));
}
public void addMyButtonListener(ActionListener listener) {
myButton.addActionListener(listener);
}
}

When button clicked, replace entire window content with an image

SOLVED
So I have an issue where when I click the button, I want an image to replace the entire content of the window. But it's only replacing, what I believe to be, a part of a panel. Should I not use panels in this instance? I found some code online which didn't use panels which worked, but maybe there is a scenario where I can remove the panel and just cover the entire frame with my image when the button is clicked?
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class SatNav extends JFrame {
private JFrame frame;
private JPanel panel;
private JLabel satelliteLabel;
private JLabel aboutLabel;
private JButton satellite;
private JButton about;
public SatNav() {
frame = new JFrame("Work Package 5");
frame.setVisible(true);
frame.setSize(300, 380);
about = new JButton("About");
add(about);
event abo = new event();
about.addActionListener(abo);
panel = new JPanel();
frame.add(panel);
panel.add(about);
setLocationRelativeTo(null); //This is for centering the frame to your screen.
setDefaultCloseOperation(EXIT_ON_CLOSE); //This for closing your application after you closing the window.
}
public class event implements ActionListener {
public void actionPerformed(ActionEvent abo) {
ImagePanel imagePanel = new ImagePanel();
//JFrames methods
panel.add(imagePanel, BorderLayout.CENTER);
revalidate();
repaint();
about.setVisible(false);
//satellite.setVisible(false);
}
}
public class ImagePanel extends JPanel {
private BufferedImage image;
public ImagePanel() {
try {
image = ImageIO.read(new File("about.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
setBorder(BorderFactory.createLineBorder(Color.black, 2));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
}
}
public static void main(String[] args) {
new SatNav();
}
}
Your problem is that you're treating the panel JPanel as if it has a BorderLayout when it doesn't. Rather it has JPanel's default FlowLayout which will size components to their preferred sizes (here [0, 0]) rather than have contained components fill the container. The simple solution: give your panel a BorderLayout:
panel = new JPanel(new BorderLayout());
Now when adding components, the BorderLayout constants will be respected by the container's layout.
Another and possibly better and more durable solution is to use a CardLayout to help you swap components.
For example:
import java.awt.CardLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
public class SatNav2 extends JPanel {
private static final long serialVersionUID = 1L;
// a publicly available example image for demonstration purposes:
public static final String SAT_PATH = "https://upload.wikimedia.org"
+ "/wikipedia/commons/1/18/AEHF_1.jpg";
private static final String INTRO_PANEL = "intro panel";
private static final String IMAGE_LABEL = "image label";
// our layout
private CardLayout cardLayout = new CardLayout();
// JLabel to display the image
private JLabel imgLabel = new JLabel();
public SatNav2(Image img) {
// put image into JLabel
imgLabel.setIcon(new ImageIcon(img));
// JPanel to hold JButton
JPanel introPanel = new JPanel();
// add button that does the swapping
introPanel.add(new JButton(new ShowImageAction("Show Image")));
// set the CardLayout and add the components. Order of adding
// is important since the first one is displayed
setLayout(cardLayout);
// add components w/ String constants
add(introPanel, INTRO_PANEL);
add(imgLabel, IMAGE_LABEL);
}
private class ShowImageAction extends AbstractAction {
public ShowImageAction(String text) {
super(text);
}
#Override
public void actionPerformed(ActionEvent e) {
// tell card layout to show next component
cardLayout.next(SatNav2.this);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
try {
createAndShowGui();
} catch (IOException e) {
e.printStackTrace();
}
});
}
private static void createAndShowGui() throws IOException {
// get the image
URL imgUrl = new URL(SAT_PATH);
Image img = ImageIO.read(imgUrl);
// pass image into our new JPanel
SatNav2 mainPanel = new SatNav2(img);
JFrame frame = new JFrame("Satellite");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}

How to switch JPanels in a JFrame from within the panel?

So, I'm trying to make a basic functional menu for a simple game. I tried to do this by creating 2 JPanels, one for the actual game, and another for my menu.
What I'm trying to do is have a button on my Menu panel that when pressed, switches the JPanel being displayed in the parent JFrame from that of the menu to that of the actual game.
Here is my code:
class Menu extends JPanel
{
public Menu()
{
JButton startButton = new JButton("Start!");
startButton.addActionListener(new Listener());
add(startButton);
}
private class Listener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Container container = getParent();
Container previous = container;
System.out.println(getParent());
while (container != null)
{
previous = container;
container = container.getParent();
}
previous.setContentPane(new GamePanel());
}
}
}
As you can see, I created a Listener for my start button. Inside the listener, I used a while loop to get to the JFrame, via the getParent() method. The program is getting the JFrame object, however it's not letting me call the setContentPane method...
Does anyone know how to get this to work, or a better way to switch back and forth between a menu and game?
Like so :
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class CardLayoutDemo extends JFrame {
public final String YELLOW_PAGE = "yellow page";
public final String RED_PAGE = "red page";
private final CardLayout cLayout;
private final JPanel mainPane;
boolean isRedPaneVisible;
public CardLayoutDemo(){
setTitle("Card Layout Demo");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
mainPane = new JPanel();
mainPane.setPreferredSize(new Dimension(250,150));
cLayout = new CardLayout();
mainPane.setLayout(cLayout);
JPanel yellowPane = new JPanel();
yellowPane.setBackground(Color.YELLOW);
JPanel redPane = new JPanel();
redPane.setBackground(Color.RED);
mainPane.add(YELLOW_PAGE, yellowPane);
mainPane.add(RED_PAGE, redPane);
showRedPane();
JButton button = new JButton("Switch Panes");
button.addActionListener(e -> switchPanes() );
setLayout(new BorderLayout());
add(mainPane,BorderLayout.CENTER);
add(button,BorderLayout.SOUTH);
pack();
setVisible(true);
}
void switchPanes() {
if (isRedPaneVisible) {showYelloPane();}
else { showRedPane();}
}
void showRedPane() {
cLayout.show(mainPane, RED_PAGE);
isRedPaneVisible = true;
}
void showYelloPane() {
cLayout.show(mainPane, YELLOW_PAGE);
isRedPaneVisible = false;
}
public static void main(String[] args) {
new CardLayoutDemo();
}
}

Update JLabel text

I'm working on a simple GUI. On Button press i want to increase/decrease a variable and update the corresponding JLabel.
class JFrameSetUp
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JFrameSetUp extends JFrame implements ActionListener {
private int RecHeight = 0;
private int RecWidth = 0;
//Here Buttons
JButton HeightIncrease = new JButton("+");
JButton HeightDecrease = new JButton("-");
JLabel height = new JLabel(Integer.toString(RecHeight));
JLabel width = new JLabel(Integer.toString(RecWidth));
GridLayout gridLayout = new GridLayout(2, 4);
public JFrameSetUp(){
}
public void addComponentsToPane(final Container pane){
//Create GridPanel and set Layout
JPanel grid = new JPanel();
grid.setLayout(gridLayout);
//Create buttondrawPanel and set Layout
JPanel buttondraw = new JPanel();
buttondraw.setLayout(new GridLayout(2, 0));
//Adding Components to GridPanel
//Adding Layouts to pane
pane.add(grid, BorderLayout.NORTH);
pane.add(new JSeparator(), BorderLayout.CENTER);
pane.add(buttondraw, BorderLayout.SOUTH);
}
#Override
public void actionPerformed(ActionEvent e) {
//Setting up ActionListener to Buttons
if (e.getSource() == this.HeightDecrease) {
RecHeight -= 1;
height.setText(Integer.toString(RecHeight));
} else if (e.getSource() == this.HeightIncrease) {
RecHeight += 1;
height.setText(Integer.toString(RecHeight));
}
}
}
Class with MainMethod
import javax.swing.JFrame;
public class Program {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrameSetUp frame = new JFrameSetUp();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
frame.addComponentsToPane(frame.getContentPane());
//Display the window.
frame.pack();
frame.setVisible(true);
}
}
I'm aware, that's kind a newbish question. I think I'm wrong with my Code Structure. Any help is appreciated.
Thanks in advance.
You never register any ActionListeners to the buttons...
HeightIncrease.addActionListener(this);
HeightDecrease.addActionListener(this);
You also never add the buttons to the GUI
buttondraw.add(HeightIncrease);
buttondraw.add(HeightDecrease);
You also never add the labels to the GUI either...
grid.add(height);
grid.add(width);
I reworked the code, because your example was messing with my mind, hope you don't mind...
It's conceptually the same idea, just done slightly more efficently
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
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 int recHeight = 0;
private int recWidth = 0;
//Here Buttons
JButton heightIncrease = new JButton("+");
JButton heightDecrease = new JButton("-");
JLabel height = new JLabel(Integer.toString(recHeight));
JLabel width = new JLabel(Integer.toString(recWidth));
GridLayout gridLayout = new GridLayout(2, 4);
public TestPane() {
setLayout(new BorderLayout());
//Create GridPanel and set Layout
JPanel grid = new JPanel();
grid.setLayout(gridLayout);
grid.add(height);
grid.add(width);
//Create buttondrawPanel and set Layout
JPanel buttondraw = new JPanel();
buttondraw.setLayout(new GridLayout(2, 0));
heightIncrease.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
recHeight += 1;
height.setText(Integer.toString(recHeight));
}
});
heightDecrease.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
recHeight -= 1;
height.setText(Integer.toString(recHeight));
}
});
buttondraw.add(heightIncrease);
buttondraw.add(heightDecrease);
//Adding Components to GridPanel
//Adding Layouts to pane
add(grid, BorderLayout.NORTH);
add(new JSeparator(), BorderLayout.CENTER);
add(buttondraw, BorderLayout.SOUTH);
}
}
}
I would encourage you to spend some time having a look at How to Use Buttons, Check Boxes, and Radio Buttons and How to Write an Action Listeners for more details
After changing the value call
frame.repaint();
Good to see you learning Java! A few things I should point out.
Firstly, your variable names are good, but they don't follow the Java naming convention. Even though it seems small, it's just good practice to follow.
Of course, your actual problem; the action listener you've implemented is on the JFrame. (See how you extend JFrame and implement ActionListener?) This ActionListener should be on the button. You'll can do this a few ways.
Method 1: By adding it inline with your code
JButton heightButton = new JButton("Increase Height");
heightButton.addActionListener(new ActionListener(){
#Override
public void run(){
//run method here
}
});
Method 2: Create a class which implements ActionListener
class ButtonListener implements ActionListener{
#Override
public void run(){
//actionListener code here
}
}
And then instantiate an object of this type and add it directly to your code.
ActionListner buttonListener = new ButtonListener(); //or ButtonListener buttonListener = new ButtonListener();
JButton heightButton = new JButton("Increase Height");
heightButton.addActionListener(buttonListener);
Of course, as in MadProgrammers answer, don't forget to add the labels and such to your JFrame or JPanel. Good luck learning Java!
I bet that your program just shows nothing, isn't it? That's because in addComponentsToPane method, you didn't add any component but empty JPanels. After the comment //Adding Components to GridPanel, you should:
buttondraw.add(HeightIncrease);
buttondraw.add(HeightDecrease);
grid.add(height);
grid.add(width);
Then, to listen to button event, you should also add :
HeightIncrease.addActionListener(this);
HeightDecrease.addActionListener(this);
"this" is because your frame JFrameSetUp implements ActionListener, so when either bootton is clicked the method actionPerformed is invoked.
As JLabel.setText method will repaint itself and consequently its component hierarchi is repainted as well, you haven't to do anything othr.

When i change JPanel in JFrame i lose focus

As in subject: When i change JPanel in JFrame i lose focus. I have class Game, Action, Button.
I have also class Stage when drawing the game stage.
At first in Game i have Action panel, which contains buttons, after push button NewGame i change panel in Game to Stage, but i cant control ship, which i am flying.
How to fix it or how to do it different?
Action.java
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.io.FileNotFoundException;
import javax.swing.*;
#SuppressWarnings("serial")
public class Action extends JPanel {
public static final int xxx = 800;
public static final int yyy = 600;
private Button buttonPanel;
public Action(Game game) {
setLayout(new FlowLayout());
setPreferredSize(new Dimension(xxx, yyy));
buttonPanel = new Button(game);
add(buttonPanel);
setVisible(true);
}
}
Button.java
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class Button extends JPanel implements ActionListener{
public static final int xxx = 100;
public static final int yyy = 300;
private JButton NewGame;
private JButton Scores;
private JButton Exit;
private Game game;
public Button(Game game) {
NewGame = new JButton("NewGame");
Scores = new JButton("Scores");
Exit = new JButton("Wyjście");
this.game=game;
NewGame.addActionListener(this);
setLayout(new FlowLayout());
setPreferredSize(new Dimension(xxx, yyy));
add(NewGame);
add(Scores);
add(Exit);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if(source == NewGame){
game.setPanel("stage");
}
;
}
}
Game.java
#SuppressWarnings("serial")
public class Game extends JFrame {
private Action menu;
private static Stage stage = new Stage();
public Game() {
super("Lunar Lander");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(Stage.WIDTH,Stage.HEIGHT);
setMinimumSize(new Dimension(400,300));
this.setResizable(true);
//stage = new Stage(0);
menu = new Action(this);
add(menu);
pack();
//setPanel("stage");
setVisible(true);
}
public void setPanel(String panel) {
if (panel=="stage") {
remove(menu);
add(stage);
pack();
} else if (panel=="menu") {
remove(stage);
add(menu);
pack();
}
}
public static void main(String[] args) throws FileNotFoundException {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Game();
}
});
Thread a = new Thread(stage);
a.start();
while (a.isAlive()) {}
Scores scores = new Scores();
scores.changeScores(stage.getPlayer().getName(),stage.getPlayer().getPoints());
}
}
but i cant control ship, which i am flying.
KeyEvents are only passed to the component with focus. When you swap panels the panel no longer has focus.
Don't use a KeyListener. Instead you should be using Key Bindings. Then you can handle the event even if the component doesn't have focus.
See Motion Using the Keyboard for more information and working examples.
Edit:
Don't use "==" for String comparisons. Use the String.equals(...) method.
Variable names should NOT start with an upper case character.

Categories