1

Im looking to change an Icon when I click a Jbutton. I have button1 rigged up to an action command that prints "On" or "Off". I would like to have the button change icons from an image of an circle meaning off, to an image of a power button meaning on. I've tried many things but haven't been able to find a solution so Im wondering if there is an easy way to do this or if there isn't an easy way, and ill have to make a more complex way for each button. Any advice is greatly appreciated because Im at a dead end. Fell free to edit large blocks or add things because Im open to all ideas. The code is included below

import java.awt.*; 
import javax.swing.*;
import java.io.*;
import java.awt.event.*;


public class OnandOff{

  public static void main(String[] a){
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.add(new ButtonDemo());
    f.setSize(600,500);
    f.setVisible(true);

  }
}

class ButtonDemo extends JPanel implements ActionListener {
  JTextField jtf;

  public ButtonDemo() {
    try {
      SwingUtilities.invokeAndWait(new Runnable() {
        public void run() {
          makeGUI();
        }
      });
    } catch (Exception exc) {
      System.out.println("Can't create because of " + exc);
    }
  }

  private void makeGUI() {
    setLayout(new FlowLayout());
      //sets up icons
      ImageIcon OnIcon = new ImageIcon("  On.jpg");
      Icon OffIcon = new ImageIcon("Off.jpg");
      ImageIcon BlankIcon = new ImageIcon("Blank.jpg");

    //creates jbuttons with Action command
    ImageIcon button1 = new ImageIcon("Off.jpg");
    JButton jb = new JButton(button1);

    jb.setActionCommand("On");

    jb.addActionListener(this);
    add(jb);

    ImageIcon button2 = new ImageIcon("Off.jpg");
    jb = new JButton(button2);
    add(jb);

    ImageIcon button3 = new ImageIcon("Off.jpg");
    jb = new JButton(button3);
    add(jb);

    ImageIcon button4 = new ImageIcon("Off.jpg");
    jb = new JButton(button4);
    add(jb);




  }

   @Override
    //prints on and off when detecting action comand from a jbutton
    public void actionPerformed(ActionEvent ae) {

        String action = ae.getActionCommand();

        if (action.equals("On")) {

            System.out.println("Yes Button pressed!");
            ImageIcon button1 = new ImageIcon("On.jpg");

            TicTacToe.a = 1;


        }

        else if (action.equals("Off")) {

            System.out.println("No Button pressed!");

        }

    }
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Jay Ytsma
  • 21
  • 2
  • `ImageIcon button1 = new ImageIcon("On.jpg");` The name should reflect the type, so.. `ImageIcon imageIcon1 = new ImageIcon("On.jpg");` – Andrew Thompson Jun 18 '16 at 05:32
  • As an aside, if the singular need is to change icons from 'off' to 'on' I would use a `JToggleButton` (possibly undecorated) and set different icons for the normal and selected states. Job done! Here is [an example (MCVE) of that approach](http://stackoverflow.com/a/7360696/418556). – Andrew Thompson Jun 18 '16 at 05:35

1 Answers1

3

You're forgetting to call setIcon(...) on any button. As the AbstractButton API will tell you (this is the parent class of JButton), it is easy to change the icon of any button by simply calling its setIcon(Icon icon) method and pass in the new Icon. In the future, first go to the API as you'll learn much there, including methods that do exactly what you need.

Other suggestions: don't give your variables names that don't match what they are. For instance you're calling an ImageIcon variable "button1" as if it were a JButton, and that will confuse other coders and your future self. Instead why not call it `onIcon" or "offIcon", a name that makes the code self-commenting.

A major problem with your code, and one reason why as written, you can't make it work -- your JButton objects are assigned to local variables, variables that are only visible within the method that they were declared. If you want your JButton objects to be able to have there icons changed in different methods of the class, they must be declared at the class level, not at the method or constructor or deeper level.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373