2

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.

e.g.

    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.)

Frakcool
  • 10,915
  • 9
  • 50
  • 89
  • This may help you: http://stackoverflow.com/questions/7966287/dynamically-change-jbutton-icon – PeterMmm Mar 23 '16 at 19:22
  • You could add a `print` statement to the `actionPerformed` method and inside the `condition`, to see whether the method is called and whether the check is correct. Also, is the method really called `ActionPerformed`, with capital A? – tobias_k Mar 23 '16 at 19:23
  • I'll look into concurrency and threads shortly so that I can understand the linked question, this was a side project to apply what I've been doing before blindly moving on and I thought that I must've been overlooking something simple. Thanks for the answer hopefully helps once I've started with threads... – Russel Povey Mar 23 '16 at 19:41
  • You should not create new ImageIcons in the actionPreformed() method. Your constructor should create each icon once and store it. Then in your actionPerformed() method you just call `startcur.setIcon(theCorrectIcon)` – FredK Mar 23 '16 at 19:52
  • *"please let me know if I should include it all"* No. 1) For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). 2) One way to get image(s) for an example is to hot link to images seen in [this Q&A](http://stackoverflow.com/q/19209650/418556). – Andrew Thompson Mar 23 '16 at 22:30
  • Application resources will become embedded resources by the time of deployment, so it is wise to start accessing them as if they were, right now. An [tag:embedded-resource] must be accessed by URL rather than file. See the [info. page for embedded resource](http://stackoverflow.com/tags/embedded-resource/info) for how to form the URL. – Andrew Thompson Mar 23 '16 at 22:31

2 Answers2

1

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.

Community
  • 1
  • 1
Jonah
  • 1,013
  • 15
  • 25
0

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();
            }
        });
    }
}
darksmurf
  • 3,747
  • 6
  • 22
  • 38