简体   繁体   中英

How to change an Icon when JButton is Pressed

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!");

        }

    }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM