0

why doesn't the action performed method read the text field "text"?

Hi I am new to using Java GUI (Swing). The Action listener is not identifying the textField named text. Help! package Jframe1; import javax.swing.*; import javax.swing.JButton; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Main extends JFrame implements ActionListener { public static void main(String[] args) { new Main().setVisible (true); } public Main (){ setTitle("Golf Scorer"); setSize(600, 400); setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE); JButton startButton = new JButton ("Start"); startButton.setVisible (true); startButton.setSize (100,100); startButton.setLocation(250, 20); startButton.addActionListener(this); add(startButton); startButton.setActionCommand ("Start"); final JTextField text = new JTextField (); add(text); text.setVisible (true); text.setBounds(250, 100, 100, 100); } @Override public void actionPerformed ( ActionEvent e ) { String name = e.getActionCommand (); if (name.equals ("Start")){ text.setText("Welcome"); } } }

11th Apr 2020, 2:50 PM
Stephen
2 odpowiedzi
+ 1
thanks fir your help
12th Apr 2020, 4:36 PM
Stephen
0
Final means you can't change the value of the variable anymore. It is like a constant. Here is my solution: startButton and text are instance variables so I can use them in the whole class. https://code.sololearn.com/cNYwakrGdYfg/?ref=app
12th Apr 2020, 10:20 AM
Denise Roßberg
Denise Roßberg - avatar