0

I have been having trouble with creating ActionListeners that don't break my entire program. I want an image of a rock to show up when the user presses the rock button.

Here is the code I have in my Panel class (excluding imports & class header):

public MainPanel(controller controller) {
    super();
    this.controller = controller;
    this.layout = new SpringLayout();
    this.menuPanel = new JPanel(new GridLayout(0, 1));
    this.scissorsImage = new ImageIcon();
    this.scissorsImageLabel = new JLabel("");
    this.paperImage = new ImageIcon();
    this.paperImageLabel = new JLabel("");

    
    rockImage = new ImageIcon (getClass().getResource(""));
    rockImageLabel = new JLabel(rockImage);
    add(rockImageLabel);
    
    setupListeners(null);
    setupPanel();
    setupLayout();
    
}

public void showRock() {
    String path = "/rps/view/images/";
    String defaultName = "Rock";
    String extension = ".png";
    
    try {
        rockImage = new ImageIcon(getClass().getResource(path + extension));
    }
    catch(NullPointerException missingFile){
        rockImage = new ImageIcon(getClass().getResource(path + defaultName + extension));
    }
    
    rockImageLabel.setIcon(rockImage);
}

public void setupPanel() {
    this.setLayout(layout);
    this.add(menuPanel);
    this.rock = new JButton("Rock");
    layout.putConstraint(SpringLayout.NORTH, rock, 1, SpringLayout.SOUTH, paperImageLabel);
    layout.putConstraint(SpringLayout.SOUTH, rock, -175, SpringLayout.SOUTH, this);
    this.paper = new JButton("Paper");
    this.scissors = new JButton("Scissors");
    this.add(paperImageLabel);
    this.add(scissorsImageLabel);
    this.add(rockImageLabel);
    this.setBackground(new java.awt.Color(255, 248, 186));
    
    
}



public void setupListeners(ActionEvent e) {
    
}
Todu
  • 1
  • Easiest way is to create a panel with all your buttons and a JLabel with an empty Icon. Then when you click on the button you just set the Icon of the JLabel with your new image. Check out the section from the Swing tutorial on [How to Use Combo Boxes](https://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html). One of the examples shows how to change the image of the selected animal. Your code would be very similar. – camickr Aug 08 '22 at 17:45
  • Usually, if you want to make something appear and disappear, you want to place the component in a [CardLayout](https://docs.oracle.com/en/java/javase/18/docs/api/java.desktop/java/awt/CardLayout.html). Side note: Never, ever catch NullPointerException—NullPointerException is designed to expose programmer mistakes and should never be caught. Use `if (resource != null)` instead. – VGR Aug 09 '22 at 13:44

0 Answers0