java - When trying to register a Swing button with an event handler why do I get an error? -


i trying create simple java swing application allow me convert kilometers miles. when registering button event handler error. error lies within textfield identifier. there red squiggly line highlighted underneath , not know why error. here code. appreciated.

import javax.swing.*; import java.awt.event.*;  public class graphics     {     public static void main(string[] args)         {     // create window     jframe window = new jframe();     window.settitle("distance converter");     window.setsize(550, 450);     window.setdefaultcloseoperation(jframe.exit_on_close);     window.setvisible(true);      // create panel     jpanel panel = new jpanel();      // create components     jlabel message = new jlabel("enter distance in kilometers");     jtextfield textfield = new jtextfield(10);     jbutton button = new jbutton("calculate");      // add components panel     panel.add(message);     panel.add(textfield);     panel.add(button);      // add panel window     window.add(panel); }  // add action listener button mybuttonlistener listener = new mybuttonlistener(); button.@addactionlistener(listener);   // register event listener calculate button private class mybuttonlistener implements actionlistener {     public void actionperformed(actionevent e)     {         final double converstion = 0.6214;         string input; // hold user's input         double miles; // hold number of miles          // text entered user text field         input = textfield.gettext();         // textfield underlined red: there error here.         // not understand why there error here.          // convert input miles         miles = double.parsedouble(input) * converstion;          // display result.          joptionpane.showmessagedialog(null, input + " kilometers " + miles + " miles.");      } } } 

you can't write statements (method calls, variable assignments et.c) outside of method or static initialiser. call button.addlistener() should done within method, such main method.

public static void main(string[] args) {     ...     // add action listener button     mybuttonlistener listener = new mybuttonlistener();     button.addactionlistener(listener);     ... } 

also, @ symbol shouldn't occur before method name in method call. in future, should post error , read it, since give clue problem is.


Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

python 3.x - PyQt5 - Signal : pyqtSignal no method connect -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)