How do I make an image appear when you press a button in JPanel w/ SpringLayout?

25 Views Asked by At

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) {
    
}
0

There are 0 best solutions below