2

I am trying to make a program that converts Norwegian Krones into Swedish krones, when pressing my button. I started working with programs inside of Windows yesterday and am a complete beginner.

The problem is that I simply don't understand how I can connect the textbox and the button. I understand that something has to happen inside Knappelytter but I am not sure what.

Here is a picture of my program: http://gyazo.com/f3b0817bf6ae73985a098e5f97c9caf2)

package tilsvensk;
import java.awt.*;
import java.awt.event.*; 
import javax.swing.*; 

class Vindu extends JFrame{
    int norskekr2 = 0; 
    int svenskekr2 = 0; 

    public Vindu(String tittel){
    setTitle(tittel); 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    setLayout(new FlowLayout()); 

    JButton knapp = new JButton("Regn om"); 
    add(knapp); 
    JLabel kr = new JLabel("Norske Kr");
    add(kr); 
    JTextField norskekr = new JTextField(5);
    add(norskekr);  
    JLabel skr = new JLabel("Svenske Kr");
    add(skr); 
    JTextField svenskekr = new JTextField(5); 
    svenskekr.setEnabled(false);
    add(svenskekr); 
    Knappelytter knappelytteren = new Knappelytter(); 
    knapp.addActionListener(knappelytteren);
    norskekr.addActionListener(knappelytteren);

    pack(); 
    }
}
class Knappelytter implements ActionListener{
public void actionPerformed (ActionEvent hendelse){

    //What happens right here? 


}


}
public class TilSvensk {
    public static void main(String[] args) {
        Vindu start = new Vindu("Regn om- Program"); 
        start.setVisible(true); 
    }

}

//NED EDITED CODE HERE

package tilsvensk;
import java.awt.*;
import java.awt.event.*; 
import javax.swing.*; 

class Vindu extends JFrame{
    int norskekr2 = 0; 
    int svenskekr2 = 0; 
    private JTextField norskekr = new JTextField(5);
    private JLabel kr = new JLabel("Norske Kr");
    private JButton knapp = new JButton("Regn om"); 
    private JLabel skr = new JLabel("Svenske Kr");
    private JTextField svenskekr = new JTextField(5); 

    public Vindu(String tittel){
    setTitle(tittel); 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    setLayout(new FlowLayout()); 

    add(knapp); 
    add(kr); 
    add(norskekr);  
    add(skr); 
    svenskekr.setEnabled(false);
    add(svenskekr); 
    Knappelytter knappelytteren = new Knappelytter(); 
    knapp.addActionListener(knappelytteren);


    pack(); 
    }

    class Knappelytter implements ActionListener{
public void actionPerformed (ActionEvent hendelse){
 String text = norskekr.getText(); 
 double tall = Double.parseDouble(text);
 double nyttall = tall*0.80;
 String total2 = String.valueOf(nyttall);
    svenskekr.setText(total2);
}


}

}

public class TilSvensk {
    public static void main(String[] args) {
        Vindu start = new Vindu("Regn om- Program"); 
        start.setVisible(true); 
    }

}
David Lund
  • 235
  • 1
  • 6
  • Create method actionPerformed inside Vindu class and make text fields global variable, So that you can access them. – वरुण Jul 07 '15 at 16:28
  • 1
    "The problem is that I simply don't understand how I can connect the textbox and the button" The action listener should just listen for someone pressing the button, within it is where you write some code to get the text from inside the text box and do the conversion. – SpaceCowboy Jul 07 '15 at 16:28
  • So the actionlistener doesn't listen for when someone is for example writing in the textbox? Does it only listen for buttons? I have to make my textfields global, and only the button should be listened for, and then output to the other text which is also global. How can i be sure my textfields are global? Do I have to put the actionlistener class inside the other class, or is there another way? – David Lund Jul 07 '15 at 16:33
  • Yes, that is right, use anonymous class as @Jack advices – maskacovnik Jul 07 '15 at 16:34
  • @maskacovnik Using an anonymous class for an `ActionListener` has been frowned upon since Java 8. Check out my answer – Vince Jul 07 '15 at 16:58
  • Can you provide the source of you meaning about anonymous classes (I want to learn this news too)?, Lambdas are short expression of anonymous classes, so it can cause problems too @VinceEmigh – maskacovnik Jul 07 '15 at 17:05
  • @maskacovnik They are not "syntactic sugar" for anonymous classes. You can tell by the lack of a $.class file that anonymous classes generate. A lambda expression uses a [Method Handle](http://docs.oracle.com/javase/8/docs/api/java/lang/invoke/MethodHandle.html) rather than defining a new class and instantiating it. If you view the bytecode, you'll notice that it's very different. I suggest watching [Brain Goetz's "Lambdas, A Peek Under the Hood"](https://youtu.be/MLksirK9nnE). – Vince Jul 07 '15 at 17:09
  • Your edited code is working, What is the issue now? – वरुण Jul 08 '15 at 08:35

3 Answers3

3

Pass the fields to the listener:

class Knappelytter implements ActionListener {
    private JTextField field;

    public Knappelytter(JTextField field) {
        this.field = field;
    }

    public void actionPerformed(ActionEvent e) {
        String text = field.getText();
    }
}

Wen you create the listener, pass the field to it:

JTextField field = new JTextField(10);
Knappelytter listener = new Knappelytter(field);

field.addActionListener(listener);

Or, if using Java 8+, you could just use a lambda expression instead of creating a new class for your listener:

field.addActionListener(event -> {
    String text = field.getText();
});
Vince
  • 14,470
  • 7
  • 39
  • 84
  • for using lambdas +1 @VinceEmigh – maskacovnik Jul 07 '15 at 17:02
  • My knowledge is still not to the point where I understand this exact code, because I started with this yesterday. I manged to do it with my simple knowledge. I will put an edit on my thing so you can comment. I am sure this is a much better way but I am not that good yet. – David Lund Jul 07 '15 at 17:17
  • If you are using an IDE that supports Java 8 (like Eclipse Luna), you don't need the class that implements the `ActionListener` as you have in your code; just use the final example I gave (lambda). I renamed `MyListener` to better represent your code. What do you not understand about the code in my answer? – Vince Jul 07 '15 at 17:21
  • I can just tell you my lack of knowledge since I just started with this yesterday. 1. I am not sure what "implements" does yet. I understand what extends does but I don't understand why it's important or why I even need it here - Couldn't I just import lots of stuff and be happy? According to you guys I can only use ActionListener when I have to press something which clears up something, thanks. And I am not entirely sure about when something is accessible to something and when it is not. Is the code that I have made good enough? Also in my code I need to get rid of the numbers after the the . – David Lund Jul 07 '15 at 17:31
  • Do I need a new class for each action listener? So if I have two buttons, and want them to do different things, I need 2 different action listener classes. – David Lund Jul 07 '15 at 17:34
  • And btw, I am using netbeans. – David Lund Jul 07 '15 at 17:35
  • @Vince Emigh , and If you have any videoes that are helpful for me, for my level I would be very happy to see them. I can only read in my book, and my book doesn't give me an answer for everything I wonder about. – David Lund Jul 07 '15 at 17:50
  • @DavidLund You should really look into the basics of object orientaton. Ripping code without studying the syntax of that code will only make the process of learning more difficuly. Oracle has a plethora of [tutorials](https://docs.oracle.com/javase/tutorial/) on their site, more specifically, the [concepts of object orientation](https://docs.oracle.com/javase/tutorial/java/concepts/index.html). They also have Swing tutorials. You don't need a class for each listener if you were to use a lambda. Otherwise, you would. – Vince Jul 07 '15 at 20:13
  • Yes, I know, but almost everything I code, I do understand. I know what classes are, methods, objects, extends means that you take the methods from the superclass, so your other classes can you use them. Apparantly setTitle, and setSize, is a method of Jframe. It's just that I haven't done much of it yet. I just need to keep practicing and ask when I don't understand. – David Lund Jul 07 '15 at 20:24
  • @DavidLund *implements* is similar to *extends*. It allows the implementing class to be used as that type (anything that implements `ActionListener` IS an `ActionListener` and instances of that class can be used where ever an `ActionListener` is requested). Rather than implementing classes (we extend classes), we implement interfaces. These contain methods that anything implementing must declare. They are sometimes referred to as "contracts", as in "the methods you should be able to call from this type". – Vince Jul 07 '15 at 20:29
  • @DavidLund So you apparently know some aspect of OOP (creating objects and what classes are for), but there's apparently more that you must study. Interfaces/implementing is a big aspect of Java, especially when it comes to "*programming to an interface*" – Vince Jul 07 '15 at 20:30
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/82646/discussion-between-vince-emigh-and-david-lund). – Vince Jul 07 '15 at 20:31
0

There you will pick the text from field, make integer, multiply by constant and put to second textfield like this:

double constant; //exchange rate
if(norskekr.getText().isEmpty()){ //converting svenske->norske
     String textfield = svenskekr.getText();
     double number=0;
     try{
         number = Double.parseDouble(textfield);
     }catch(NumberFormatException e){
         System.err.println("NaN");
         e.printStackTrace();
     }
     double result = number * constant;
     norskekr.setText(result+"");
}else if(svenskekr.getText.isEmpty()){ //converting norske->svenske
     String textfield = norskekr.getText();
     double number=0;
     try{
         number = Double.parseDouble(textfield);
     }catch(NumberFormatException e){
         System.err.println("NaN");
         e.printStackTrace();
     }
     double result = number / constant; //reverse exchange rate
     svenskekr.setText(result+"");
}

Not tested

maskacovnik
  • 3,080
  • 5
  • 20
  • 26
0

You're using the ActionListener interface in an unusual way. Generally, it's used as an anonymous class. Using such a class changes your code to:

Knappelytter knappelytteren = new Knappelytter(); 
knapp.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent event) { 
        // what do we do here ?
    }
});

From here, you can add code that will access the text box's value. There's a catch, however. Variables that are outside of this anonymous class must be final. As such, you'll have to change norskekr's declaration to final JTextField norskekr = new JTextField(5);. This question may be of interest to you.

From there, you'll need to get the value of the text box (norskekr.getText()), parse it to some sort of numeric type. Whether that's int or double will depend on what you want your program to do. Then, apply the conversion rate and set the value of svenskekr with svenskekr.setText().

Community
  • 1
  • 1
Jack
  • 396
  • 2
  • 18
  • 1
    I really don't understand what is so unusual about the way I did, because I did as my book I am learning from did it. It's probably just beginner stuff, and stuff I will convert from away from later. If I could continue with my way since it is the only way I know, should I put my Action Listener into the other class? Is that how my actionlistener can get the information about my textfield and my button? – David Lund Jul 07 '15 at 16:49
  • He isn't using it in an unusual way. An anonymous classes for this has been frowned upon since Java 8 – Vince Jul 07 '15 at 16:52
  • Perhaps unusual is the wrong word. It's more complicated than necessary, and it complicates the program, that's all. – Jack Jul 07 '15 at 18:56
  • @David—you're right. The ActionListener should go in the class with the rest of the UI code. @Vince is right, really. ActionListeners have lost much of their use since the introduction of lambdas with Java 8. – Jack Jul 07 '15 at 18:58
  • The problem is that I have a book that uses ActionListeners. I don't think I will be able to learn Java lambdas without a book that uses it. Is lambdas much easier? – David Lund Jul 07 '15 at 19:04
  • In my opinion, it's not all that important to use the latest advances in Java just yet. For now, I would say you should do whatever your book tells you to. Once you're familiar with Java, you won't have any trouble picking up more recent additions, like lambdas. – Jack Jul 07 '15 at 19:06