简体   繁体   中英

How to change icon in JLabel with JButton

I'm making a simple conversion tool to convert dollars to euro's and vice versa.

The whole purpose is just to experiment and learn this cool tool, java.

I have a JLabel at the top with an icon of a euro to indicate the starting currency. I have a button bellow this that I want to use to change that icon to a dollar one.

I am currently plying around with an ActionListener and trying different variations of setIcon/setIconImage (every itteration I can think of seeing that nothing has worked thus far).


public class MoneyConverter extends JFrame implements ActionListener{
     //add label and icon showing base conversion currency
     JLabel startcur = new JLabel("<--- Starting Curency", new ImageIcon("C:\\Users\\Russel\\Desktop\\1euro.gif"), SwingConstants.CENTER);
     JButton euro = new JButton("Swap to Euro");
     JButton dollar = new JButton("Swap to Dollar");

I then set up a

public MoneyConverter(){} 

method and add all my components to a grid layout and add ActionLister's to my convert buttons.

eg

    dollar.addActionListener(this);
    euro.addActionListener(this);

After the usual code (setVisible and the likes that I will omit for your sake as I don't see it interfering with this, please let me know if I should include it all)

public void ActionPerformed (ActionEvent e){
    Object source = e.getSource();
    if (source.equals(euro)){
         startcur.setIcon(new ImageIcon("C:\\Users\\Russel\\Desktop\\1.gif"));
    }
}

This part has been changed many times and is the main reason for this post, how do I change this icon in the JLabel? - I will also be setting the conversion rate in here depending if they choose to start with dollars or euros. (Rate won't be actual rate.)

First, create and store a new ImageIcon

ImageIcon image = new ImageIcon(getClass().getResource("/nameOfImage.jpg"));

Then put this in your Action Listener

label.setIcon(image);
label.setText("");

You have to make sure you have a resource folder set up for your project. You can read how to do that in IntelliJ or Eclipse

You are also declaring the actionPerformed() wrong. I suggest reading up on this You should be doing it like this.

@Override
public void actionPerformed(ActionEvent e)
{

}

Conventionally, in java, method names start with a lower case letter and Classes start with an upper case.

The whole purpose is just to experiment and learn this cool tool, java.

Then I'll show you how to improve this program in a number of ways.

//Don't make your Swing class implement Actionlistener and add it as a
//listener to itself in the constructor before it's fully initialized
public class MoneyConverter extends JFrame {
    //These don't have to be loaded at runtime, so make them into constants
    //Java variables and methods follow thisNamingConvention
    private static final Icon euroIcon = new ImageIcon("C:\\Users\\Russel\\Desktop\\1euro.gif");
    private static final Icon dollarIcon = new ImageIcon("C:\\Users\\Russel\\Desktop\\1dollar.gif");
    //These you probably want to use later so save them as private class variables
    //Make them final so you can access them in the ActionListeners below
    private final JLabel currencyLabel;
    private final JButton euroButton;
    private final JButton dollarButton;

    public MoneyConverter() {
        //These are declared final and are are therefore usually set first in constructor
        this.currencyLabel = new JLabel("<--- Starting Curency", euroIcon, SwingConstants.CENTER);
        this.euroButton = new JButton("Swap to Euro");
        this.dollarButton = new JButton("Swap to Dollar");

        //Write your own separate ActionListener for each button
        euroButton.addActionListener(new ActionListener() {
            @Override
            public void run() {
                currencyLabel.setIcon(euroIcon);
                //These two are required for you to see the effect
                //This should also be the solution to your initial problem
                currencyLabel.revalidate();
                currencyLabel.repaint();
            }
        });
        dollarButton.addActionListener(new ActionListener() {
            @Override
            public void run() {
                currencyLabel.setIcon(dollarIcon);
                currencyLabel.revalidate();
                currencyLabel.repaint();
            }
        });

        //Add your components here using whatever layout manager you want.
    }

    public static void main(String []args){
        //Start new Swing applications like this to prevent it from
        //clogging the rest of the program
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new MoneyConverter();
            }
        });
    }
}

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