I am a beginner with java and has got a problem that I just cant solve.
I am trying to add strings to my array, I have tested my array so that work. But my problem is that I have created an actionlistener and trying to get the text from another class and then add it to the array.
My Buttonlistener:
public class ButtonListener extends AddToLibrary implements ActionListener {
public void actionPerformed(ActionEvent e) {
Database dt = new Database();
dt.add(textType, textTitle, textSort, textDesc);
} }
I got a friend who told me that I am creating a new database every time I pushes the button, but how do I do if I just want to "load" it? Can clear that database is the classname for my array.
The more "funny" part of this is that when I run it in eclipse it goes to debugger without showing me anything clear that is wrong, and because of my limited knowledge in java this is too much to me.
My buttonlistener is geting the information from AddToLibrary and it looks like this:
public class AddToLibrary extends JPanel{
public String textTitle;
public String textSort;
public String textDesc;
public String textType;
public AddToLibrary() {
// Förklarande text
JLabel titel = new JLabel("Titel");
JLabel sort = new JLabel("Genre");
JLabel desc = new JLabel("Beskriving");
// Textrutor
JTextField textTitel = new JTextField(null, 20);
textTitel.setToolTipText("ex. Flickan som lekte med elden");
JTextField textSort = new JTextField(null, 10);
textSort.setToolTipText("ex. Skräck, Action");
JTextField textDesc = new JTextField(null, 15);
textDesc.setToolTipText("ex. Stieg Larsson");
// Knappar
JButton addButton = new JButton("Lägg till");
addButton.addActionListener(new ButtonListener()); //Lyssna på knapp
// Combobox
JComboBox comboBox = new JComboBox();
comboBox.addItem("Film");
comboBox.addItem("CD");
comboBox.addItem("Bok");
comboBox.addItem("Annat");
// Lägg till i panelen
add(titel);
add(textTitel);
add(sort);
add(textSort);
add(desc);
add(textDesc);
add(comboBox);
add(addButton);
}
public String getTitelText(JTextField titelText) {
textTitle = "" + titelText.getText();
return textTitle;
}
public String getDescText(JTextField descText) {
textDesc = "" + descText.getText();
return textDesc;
}
public String getSortText(JTextField sortText) {
textSort = "" + sortText.getText();
return textSort;
}
public String getTypeText(JComboBox comboBox) {
return textType = "" + (String) comboBox.getSelectedItem() + ".png";
}
}
But it do not work and I cant understand why it isnt working, so if anyone has some time over to help me I would be pleased.
Thanks!
One fault is here:
public class ButtonListener extends AddToLibrary implements ActionListener {
extending AddToLibrary creates a weird inheritance problem.
The simple solution is to define the ButtonListener inline:
final Database dt = new Database();
addButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dt.add(getTypeText(comboBox), getTitelText(textTitel), getSortText(textSort), getDescText(textDesc));
}
}); // Lyssna på knapp
One important change is to create one instance of Database to which the strings are added (as Amit Kumar already pointed out).
There were a lot of problems with your code, mostly illegal constructions. My advice is to get a good Java tutorial/book and take notice of how they solve the problems. Also if you use Eclipse (or another modern IDE) it will notify you of any illegal constructions and will try to propose solutions.
One last note, the public Strings and the JTextFields have the same name, this creates a problem for the computer as it does not know which one you are referring to (this is called shadowing). Define unique names for each variable within a class so you do not confuse the compiler or yourself.
=====================================
I have done a little work on your code and I arrived at the following. (It may be improved even further, but this is at least a lot better in terms of legality and readability)
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class AddToLibrary extends JPanel {
private static final long serialVersionUID = 1L;
private Database database = new Database();
private JComboBox comboBox = new JComboBox(new String[]{"Film", "CD", "Bok", "Annat"});
private JButton addButton = new JButton("Lägg till");
private JTextField textTitel = new JTextField(null, 20);
private JTextField textSort = new JTextField(null, 10);
private JTextField textDesc = new JTextField(null, 15);
private JLabel titel = new JLabel("Titel");
private JLabel sort = new JLabel("Genre");
private JLabel desc = new JLabel("Beskriving");
public AddToLibrary() {
textTitel.setToolTipText("ex. Flickan som lekte med elden");
textSort.setToolTipText("ex. Skräck, Action");
textDesc.setToolTipText("ex. Stieg Larsson");
addButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
database.add(comboBox.getSelectedItem() + ".png",
textTitel.getText(),
textSort.getText(),
textDesc.getText()
)
}
}); // Lyssna på knapp
// Lägg till i panelen
add(titel);
add(textTitel);
add(sort);
add(textSort);
add(desc);
add(textDesc);
add(comboBox);
add(addButton);
}
}
public class ButtonListener extends AddToLibrary implements ActionListener {
private Database dt = new Database();
public void actionPerformed(ActionEvent e) {
dt.add(textType, textTitle, textSort, textDesc);
}
}
should work. Or better, the database should be created in AddToLibrary and passed to ButtonListener in its constructor. Sorry I do not have the time to check the code for you, but if this does not work, you can notify.
Related
EDIT: resolved
on a side note, how do i pause an audio stream? is there a way, or can i only kill the player?
this school project i am doing, it's a music player, it is in BlueJ.
the requirements were to have a form displayed with a combo box, play buttons,etc.
i managed to get my playlist of audio into the playlist, but trying to change the SelectedIndex is giving me issues.
for example, there are two play buttons.
one is a play button- you play the first song in the playlist.
for this, i need to use the method GetSelectedIndex() to get me the index to play the song. the items in the combo box are in the same order as the files are listed.
the other button is a play random button, once pressed, it will play a random song in the given library. this button works, but when it plays the song, it needs to display which song it is playing in the combobox. using the SetSelectedIndex() method.
both are giving me the java.lang.NullPointerException error.
being int values, i can't seem to figure out how to make the "object" instanced- this is what other answers were saying. (on other questions)
random button constructor: (the other button is very similar to this)
private JButton ranbutton;
ranbutton = new JButton();
ranbutton.setMargin(new Insets(0,0,0,0));
ranbutton.setText("ran");
ranbutton.addActionListener(sl);
ranbutton.setBounds(150,220,35,30);
ShuffleListener sl= new ShuffleListener();
Action Listener of random button:
private class ShuffleListener implements ActionListener
{
public void actionPerformed(ActionEvent t)
{
org.playrandom();
playlist.setSelectedIndex(1); **THIS GIVES ME THE ERROR**
System.out.println("Z");
}
because it gives me a null error at the set selected index, "Z" never gets printed.
the other play button, is defined the same, and the action listener is the same except for the one difference:
int w= playlist.getSelectedIndex();**THIS GIVES ME THE ERROR**
code for the JComboBox "playlist" note: this code works. it is moldable to the number of files in the audio folder. note#2: org is the instance of the organizer class - which controls everything and it works.
public JComboBox playlist;
Integer[] nums;
x= org.getNumberOfTracks();
nums = new Integer[x];
String item[] = new String[x];
for(int i = 0 ; i < x; i++) {
item[i]= ((org.getName(i)));
}
JComboBox playlist = new JComboBox(item);
playlist.setBounds(50,50,250,50);
Now, something interesting, if i put
playlist.setSelectedIndex(4);
in the bottom of the constructor, and run the program, the combo box will be set to index 4 (item 5)
i have messed around a bit, isolating the code when it is called, and using System.Out.println() to see if the code is going through.
but i cannot figure out why it will call in the constructor but not in the ActionListener class.
Here is all of the code, excuse the formatting:
import java.util.ArrayList;
import java.util.Random;
import java.util.Iterator;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Insets;
import java.lang.Integer;
public class GUI extends JFrame
{
private int x;
private int r;
private int p;
private String l;
private int n=0;
private JButton playbutton;
private JButton ranbutton;
private JButton prevbutton;
private JButton skipbutton;
private JButton stopbutton;
private JButton repeatbutton;
private static MusicOrganizer org;
public JComboBox playlist;
public boolean looper=false;
public static void main(String[] args)
{
new GUI();
}
public GUI()
{
org= new MusicOrganizer();
this.setSize(400,300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Awesome Music Player");
this.setLocation(600,300);
JPanel panel= new JPanel();
panel.setLayout(null);
ButtonListener blp = new ButtonListener();
ShuffleListener sl= new ShuffleListener();
StopListener pl= new StopListener();
RepListener rp = new RepListener();
playbutton= new JButton();
playbutton.setMargin(new Insets(0,0,0,0));
playbutton.setText("►");
playbutton.addActionListener(blp);
playbutton.setBounds(35,215,40,40);
repeatbutton= new JButton();
repeatbutton.setMargin(new Insets(0,0,0,0));
repeatbutton.setText("○");
repeatbutton.addActionListener(rp);
repeatbutton.setBounds(190,220,35,30);
skipbutton = new JButton();
skipbutton.setMargin(new Insets(0,0,0,0));
skipbutton.setText(">>|");
skipbutton.setBounds(75,220,30,30);
prevbutton = new JButton();
prevbutton.setMargin(new Insets(0,0,0,0));
prevbutton.setText("|<<");
prevbutton.setBounds(5,220,30,30);
ranbutton = new JButton();
ranbutton.setMargin(new Insets(0,0,0,0));
ranbutton.setText("ran");
ranbutton.addActionListener(sl);
ranbutton.setBounds(150,220,35,30);
stopbutton= new JButton();
stopbutton.setMargin(new Insets(0,0,0,0));
stopbutton.setText("■");
stopbutton.addActionListener(pl);
stopbutton.setBounds(110,220,35,30);
Integer[] nums;
x= org.getNumberOfTracks();
nums = new Integer[x];
String item[] = new String[x];
for(int i = 0 ; i < x; i++)
{
item[i]= ((org.getName(i)));
}
JComboBox playlist = new JComboBox(item);
playlist.setBounds(50,50,250,50);
panel.add(skipbutton);
panel.add(prevbutton);
panel.add(playbutton);
panel.add(ranbutton);
panel.add(playlist);
panel.add(stopbutton);
panel.add(repeatbutton);
this.add(panel);
this.setVisible(true);
//playlist.setSelectedIndex(4);(the code that will work....)
}
public void u()
{
playlist.setSelectedIndex(1);//( temp testing)
}
public void q()
{
n=(int)playlist.getSelectedIndex();//( temp testing)
System.out.println(n);
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (x==1)
{
playbutton.setText("| |");
int w= playlist.getSelectedIndex(); //THIS GIVES ERROR
System.out.println(w);
x=0;
}
else
{
playbutton.setText("►");
x=1;
}
}
}
private class ShuffleListener implements ActionListener
{
public void actionPerformed(ActionEvent t)
{
org.playrandom();
u();//-> method is playlist.setSelectedIndex(1); gives me the error
System.out.println("I");
}
}
private class StopListener implements ActionListener
{
public void actionPerformed(ActionEvent c)
{
org.stopPlaying();
}
}
}
The playlist you set in GUI constructor is a local variable within the constructor, not the field. The field is never initialized. In the statement JComboBox playlist = new JComboBox(item); remove the first JComboBox making it not a declaration of a new variable but a reference. The line should read playlist = new JComboBox(item);
I have this code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class pruebaframe extends JFrame
{
public static String elurl="wut";
JPanel jp = new JPanel();
JLabel jl = new JLabel();
JTextField jt = new JTextField(50);
JButton jb = new JButton("Enter");
public pruebaframe()
{
setTitle("Inserte el URL");
setVisible(true);
setSize(600, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
jp.add(jt);
jp.add(jb);
jb.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String input = jt.getText();
elurl=input;
jl.setText(input);
}
});
jp.add(jl);
add(jp);
}
public static String getElurl() {
return elurl;
}
public static void setElurl(String elurl) {
pruebaframe.elurl = elurl;
}
}
Now i want to use the elurl variable in another class like this:
String url1;
pruebaframe t = new pruebaframe();
url1 = t.getElurl();
so everytime i type something on the Jtextfield url1 changes it values. The thing is its not working. It does not change the value. I know it's a simple problem i just cant find where am i wrong.
Pass peuebaframe object when action performed. Either by using constructor or method of another class. Then you can get updated value of your jTextField.
AnotherClass.java
public class AnotherClass {
private pruebaframe t;
public AnotherClass(pruebaframe t) {
this.t= t;
}
public void print() {
System.out.println("Printing From Another Class: " + t.getElurl());
}
}
And do follwoing.
jb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String input = jt.getText();
elurl = input;
jl.setText(input);
AnotherClass anotherClass = new AnotherClass(pruebaframe.this);
anotherClass.print();
}
});
Output:
Printing From Another Class: <your updated jTextValue>
When you click the button after changing the text in JTextField a new String object is assigned to elurl. If you want url1 to change everytime you should update it too.
Instead of assigning to a variable, call t.getElurl();everytime you need the elurl value. With this you will always get the latest value of elurl
You static variable usages should be
String url1;
url1 = Pruebaframe.elurl;
But I do not recommend to use static variable to pass a parameter because of concurrent issue.
Hi well my code so far does something like this: Click a button, opens a combobox. I want to select an option on the ComboBox and depending on which option is picked i want to open another combobox using getSelectIndex().
Here are parts of my code which are relevant. I know I have to make the other comboboxes not visible or removed but at the moment I'm just trying to make a combobox appear. As you can see i have inserted the actionlistener for the button which works and opens the combobox.however when selecting a string in the combobox no event occurs. However when I run it, no comboboxes appear.
public class Work extends JFrame {
// variables for JPanel
private JPanel buttonPanel;
private JButton timeButton;
public Work()
{
setLayout(new BorderLayout());
buttonPanel = new JPanel();
buttonPanel.setBackground(Color.RED);
buttonPanel.setPreferredSize(new Dimension(400, 500));
add(buttonPanel,BorderLayout.WEST);
timeButton = new JButton("Time");
buttonPanel.add(timeButton);
buttontime clickTime = new buttontime(); // event created when time button is clicked
timeButton.addActionListener(clickTime);
Time timeObject = new Time();
timeObject.SelectTime();
buttontime2 selectDest = new buttontime2();
timeObject.getAirportBox().addActionListener(selectDest);
}
public class buttontime implements ActionListener { //creating actionlistener for clicking on timebutton to bring up a combobox
public void actionPerformed(ActionEvent clickTime) {
Time timeObject = new Time();
timeObject.SelectTime();
add(timeObject.getTimePanel(),BorderLayout.EAST);
timeObject.getTimePanel().setVisible(true);
timeObject.getTimePanel().revalidate() ;
timeObject.getAirportBox().setVisible(true);
}
}
public class buttontime2 implements ActionListener{
public void actionPerformed(ActionEvent selectDest) {
Time timeObject = new Time();
timeObject.SelectTime();
if(timeObject.getAirportBox().getSelectedIndex() == 1) {
timeObject.getEastMidBox().setVisible(true);
}
else if(timeObject.getAirportBox().getSelectedIndex() == 2) {
timeObject.getBirmBox().setVisible(true);
}
else if(timeObject.getAirportBox().getSelectedIndex() == 3) {
timeObject.getMancbox().setVisible(true);
}
else if(timeObject.getAirportBox().getSelectedIndex() == 4) {
timeObject.getHeathBox().setVisible(true);
}
}
}
public static void main (String args[]) {
events mainmenu = new events(); //object is created
mainmenu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainmenu.setSize(800,500);
mainmenu.setVisible(true);
mainmenu.setLayout(new BorderLayout());
mainmenu.setTitle("Learning how to use GUI");
mainmenu.setBackground(Color.BLUE);
mainmenu.setResizable(false);
}
}
my other class TIME
import javax.swing.JOptionPane;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Time
{
private JComboBox timeAirportbox;//comboboxes declared
private JComboBox eastMidbox;
private JComboBox mancBox;
private JComboBox heathBox;
private JComboBox birmBox;
private String[] airport = {"","EM", "Bham", "Manc", "Heath"};//array of airports declared
private String[] destination = {"","NY", "Cali", "FlO", "MIAMI", "Tokyo"};//array of destinations declared
private JPanel timePanel;
public void SelectTime() {
//combobox objects created
timePanel = new JPanel();
timePanel.setBackground(Color.BLUE);
timePanel.setPreferredSize(new Dimension(400, 400));
timeAirportbox = new JComboBox(airport);//array is inserted into the JComboBox
timePanel.add(timeAirportbox);
timeAirportbox.setVisible(false);
eastMidbox = new JComboBox(destination);
timePanel.add(eastMidbox);
eastMidbox.setVisible(false);
mancBox = new JComboBox(destination);
timePanel.add(mancBox);
mancBox.setVisible(false);
heathBox = new JComboBox(destination);
timePanel.add(heathBox);
heathBox.setVisible(false);
birmBox = new JComboBox(destination);
timePanel.add(birmBox);
birmBox.setVisible(false);
}
public JPanel getTimePanel() {
return timePanel;
}
public JComboBox getAirportBox() {
return timeAirportbox;
}
public JComboBox getEastMidBox() {
return eastMidbox;
}
public JComboBox getMancbox() {
return mancBox;
}
public JComboBox getHeathBox() {
return heathBox;
}
public JComboBox getBirmBox() {
return birmBox;
}
}
The Time object that is built in Work constructor is not used:
Time timeObject = new Time();
timeObject.SelectTime();
buttontime2 selectDest = new buttontime2();
timeObject.getAirportBox().addActionListener(selectDest);
As you are only applying the action listener selectedDest to the combobox of that timeObject, which is not used, then the listener will never be called.
You can do two things to make it work:
Move the code that creates the listener and assign it to the combox in the first listener buttontime
Create the Time object only once and store it as a member of your Work instance. As your listener is a non-static inner classes of the Work class, it will be able to use it instead of creating a new Time object.
Edit: I didn't see that in your second listener, you were AGAIN building a new Time object. This object is really a different one than the one you have created earlier, so modifying one will not affect the other. You really should create the Time object once and store it as a member variable of your Work class, and then use this object in your listeners instead of recreating it.
To be clear, do it like this:
public class Work extends JFrame {
// ...
private Time timeObject;
public Work() {
// ...
timeObject = new Time();
timeObject.SelectTime();
buttontime2 selectDest = new buttontime2();
timeObject.getAirportBox().addActionListener(selectDest);
}
public class buttontime implements ActionListener {
public void actionPerformed(ActionEvent clickTime) {
// use timeObject, don't create it and don't call SelectTime()
// example:
add(timeObject.getTimePanel(),BorderLayout.EAST);
// ....
}
}
public class buttontime2 implements ActionListener {
public void actionPerformed(ActionEvent clickTime) {
// use timeObject, don't create it and don't call SelectTime()
}
}
}
Also to note:
You should not extends JFrame, there is no reason to do so. Refactor your code so that your frame is just a member variable of your Work class.
Follow Java standard code conventions, especially use case properly with class names: buttonlistener should be ButtonListener, and method should start with lowercase: SelectTime should be selectTime.
I am using a gui with JTextFields to collect some information and then a JButton that takes that infomration and writes it to a file, sets the gui visibility to false, and then uses Runnable to create an instance of another JFrame from a different class to display a slideshow.
I would like to access some of the information for the JTextFields from the new JFrame slideshow. I have tried creating an object of the previous class with accessor methods, but the values keep coming back null (I know that I have done this correctly).
I'm worried that when the accessor methods go to check what the variables equal the JTextFields appear null to the new JFrame.
Below is the sscce that shows this problem.
package accessmain;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class AccessMain extends JFrame implements ActionListener
{
private static final int FRAMEWIDTH = 800;
private static final int FRAMEHEIGHT = 300;
private JPanel mainPanel;
private PrintWriter outputStream = null;
private JTextField subjectNumberText;
private String subjectNumberString;
public static void main(String[] args)
{
AccessMain gui = new AccessMain();
gui.setVisible(true);
}
public AccessMain()
{
super("Self Paced Slideshow");
setSize(FRAMEWIDTH, FRAMEHEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
//Begin Main Content Panel
mainPanel = new JPanel();
mainPanel.setBorder(new EmptyBorder(0,10,0,10));
mainPanel.setLayout(new GridLayout(7, 2));
mainPanel.setBackground(Color.WHITE);
add(mainPanel, BorderLayout.CENTER);
mainPanel.add(new JLabel("Subject Number: "));
subjectNumberText = new JTextField(30);
mainPanel.add(subjectNumberText);
mainPanel.add(new JLabel(""));
JButton launch = new JButton("Begin Slideshow");
launch.addActionListener(this);
mainPanel.add(launch);
//End Main Content Panel
}
#Override
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand();
if(actionCommand.equals("Begin Slideshow"))
{
subjectNumberString = subjectNumberText.getText();
if(!(subjectNumberString.equals("")))
{
System.out.println(getSubjectNumber());
this.setVisible(false);
writeFile();
outputStream.println("Subject Number:\t" + subjectNumberString);
outputStream.close();
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
AccessClass testClass = new AccessClass();
testClass.setVisible(true);
}
});
}
else
{
//Add warning dialogue here later
}
}
}
private void writeFile()
{
try
{
outputStream = new PrintWriter(new FileOutputStream(subjectNumberString + ".txt", false));
}
catch(FileNotFoundException e)
{
System.out.println("Cannot find file " + subjectNumberString + ".txt or it could not be opened.");
System.exit(0);
}
}
public String getSubjectNumber()
{
return subjectNumberString;
}
}
And then creating a barebones class to show the loss of data:
package accessmain;
import javax.swing.*;
import java.awt.*;
public class AccessClass extends JFrame
{
AccessMain experiment = new AccessMain();
String subjectNumber = experiment.getSubjectNumber();
public AccessClass()
{
System.out.println(subjectNumber);
}
}
Hardcoding the accessor method with "test" like this:
public String getSubjectNumber()
{
return "test";
}
Running this method as below in the new JFrame:
SelfPaceMain experiment = new SelfPaceMain();
private String subjectNumber = experiment.getSubjectNumber();
System.out.println(subjectNumber);
Does cause the system to print "test". So the accessor methods seem to be working. However, trying to access the values from the JTextFields doesn't seem to work.
I would read the information from the file I create, but without being able to pass the subjectNumber (which is used as the name of the file), I can't tell the new class what file to open.
Is there a good way to pass data from JTextFields to other classes?
pass the argument 'AccessMain' or 'JTextField' to the second class:
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
AccessClass testClass = new AccessClass(AccessMain.this); //fixed this
testClass.setVisible(true);
}
});
Then reading the value of 'subjectNumber'(JTextField value) from the 'AccessMain' or 'JTextField' in the second class:
public class AccessClass extends JFrame
{
final AccessMain experiment;
public AccessClass(AccessMain experiment)
{
this.experiment = experiment;
}
public String getSubjectNumber(){
return experiment.getSubjectNumber();
}
}
Also, you should try Observer pattern.
A simple demo of Observalbe and Observer
Observable and Observer Objects
I'm writing a currency converter but I'm having a bit of trouble caculating the exchange rate for each currency. basically I want the user to select a currecy first then enter an amount and press "go" button to calculate the rate. but i'm having trouble with the listeners on JMenuItem and JButton. I've declared two listeners for menuItem and JButton. how do i use the listener on the button to look out for the selection made on the menuIten so that it makes the right currecy calculation?
thanks.
CODE:
private class selectionListener implements ActionListener
{
double EuroToSterling(double euro)
{
double total = Double.parseDouble(amountField.getText());
return total;
}
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("Euros"))
// result = EuroToSterling(10*euro);
currencyMenu.setLabel("Euros");
// answerLabel.setText("this" + EuroToSterling(1.22*2));
if (e.getActionCommand().equals("Japanese Yen"))
currencyMenu.setLabel("Japanese Yen");
}
}
private class GoButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
//please help with this section
The usual approach is that the menu listener changes the state of the application (i.e. calls a method that will save the exchange rate in a field).
Then the calculation code can read this value and use it.
Try this out with the Euros. Should give you a place to get started.
/*
*
* Currency converting
*
*/
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.JComboBox;
import javax.swing.UIManager;
public class CurrencyConverterWin extends JFrame {
private JLabel promptLabel;
private JTextField amountField;
private JButton goButton;
private JPanel inputPanel;
private JPanel answerPanel;
private JLabel answerLabel;
private JLabel selectLabel;
private JComboBox currencyMenuBar;
private JPanel menuPanel;
private double result = 0.0;
private double euro = 1.22257;
private double japYen = 152.073;
private double rusRuble = 42.5389;
private double usd = 1.5577;
public CurrencyConverterWin() {
super();
this.setSize(500, 200);
this.setTitle("Currency Converter Window");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new GridLayout(3, 1));
this.selectLabel = new JLabel("Select a currency to convert to: ", JLabel.RIGHT);
this.answerLabel = new JLabel(" ", JLabel.CENTER);
currencyMenuBar = new JComboBox(new String[]{"Euros","Japanese Yen","Russian Rubles","US Dollars"});
this.menuPanel = new JPanel();
this.menuPanel.add(this.selectLabel);
this.menuPanel.add(this.currencyMenuBar);
this.add(this.menuPanel);
this.promptLabel = new JLabel("(select a currency first) ", JLabel.RIGHT);
this.answerLabel = new JLabel(" ", JLabel.CENTER);
this.amountField = new JTextField("", 8);
this.goButton = new JButton("GO");
goButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonClicked(evt);
}
});
this.inputPanel = new JPanel();
this.inputPanel.add(this.promptLabel);
this.inputPanel.add(this.amountField);
this.inputPanel.add(this.goButton);
this.add(this.inputPanel);
this.answerPanel = new JPanel();
this.answerPanel.add(this.answerLabel);
this.add(this.answerPanel);
}
double EuroToSterling() {
double total = Double.parseDouble(amountField.getText()) * euro;
return total;
}
double JapYenToSterling()
{
double japToSterlingTotal = Double.parseDouble(amountField.getText()) * japYen;
return japToSterlingTotal;
}
//String currencyEntered = yearField.getText();
public void buttonClicked(ActionEvent evt) {
if(currencyMenuBar.getSelectedItem().equals("Euros"))
{
answerLabel.setText(EuroToSterling() + " Euros");
}
if(currencyMenuBar.getSelectedItem().equals("Japanese Yen"))
{
answerLabel.setText(JapYenToSterling() + " Japanese Yen");
}
}
public static void main(String[] args) {
try{UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");}
catch (Exception e){e.printStackTrace();}
CurrencyConverterWin win = new CurrencyConverterWin();
win.setVisible(true);
}
}
I would also suggest you use a JComboBox to store the currencies. You would create an object to store both the currency name and the conversion rate. Then when you need to calculate the converted amount you get the selected item from the combo and use its conversion rate in your calculation. With this approach you can easily expand the number of currencies you support.
Check out: How to use Map element as text of a JComboBox for an example to get you start on using an object in the combo box.
I would personally add in an Enumeration to denote the currency conversion type. eg:
public enum ConversionType {
DOLLARS,
EUROS,
RUBLES
//ETC...
}
Using this, you can keep a state variable in the class:
private ConversionType fromType;
This is what you set in your selection listener.
From there it's a matter of doing the different conversions in your action listener based on the state variable (fromType). Something like this:
if( fromType== EUROS ) {
convertEurosToSterling( value1, value2 );
}
This is sort of a general approach - I hope this helps.