My program is intended to display 2 panels initially with different images from file Z_pic1.png and Z_pic2.png.WHEN ANY KEY IS PRESSED the displays on the panels should interchange swap. It is not displaying 2 images, but just the image from Z_pic2,png. Any key press has no effect. Wanna find what’s wrong.
My code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Z_LayeredPaneExample1_2 extends JFrame {
private JPanel[] panels;
private JLabel[] imageLabels;
public Z_LayeredPaneExample1_2() {
setTitle("Panel Swapper");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800, 600);
setLocationRelativeTo(null);
// Create the panel array
panels = new JPanel[2];
imageLabels = new JLabel[2];
// Load the images
ImageIcon image1 = new ImageIcon("Z_pic1.png");
ImageIcon image2 = new ImageIcon("Z_pic2.png");
// Create the panels and add them to the frame
createPanels(image1, image2);
// Add a key listener to swap the images when a key is pressed
addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
swapPanels();
}
@Override
public void keyReleased(KeyEvent e) {
}
});
setVisible(true);
}
private void createPanels(ImageIcon image1, ImageIcon image2) {
// Create the panels and set their layout and background color
for (int i = 0; i < panels.length; i++) {
panels[i] = new JPanel();
panels[i].setLayout(new BorderLayout());
panels[i].setBackground(Color.WHITE);
// Add the image to the panel
imageLabels[i] = new JLabel(i == 0 ? image1 : image2);
panels[i].add(imageLabels[i], BorderLayout.CENTER);
// Add the panel to the frame
add(panels[i], BorderLayout.WEST);
}
}
private void swapPanels() {
// Swap the images in the panels
ImageIcon temp = (ImageIcon) imageLabels[0].getIcon();
imageLabels[0].setIcon(imageLabels[1].getIcon());
imageLabels[1].setIcon(temp);
}
public static void main(String[] args) {
new Z_LayeredPaneExample1_2();
}
}