2

I'm new to this site and to Java programming and I'd greatly appreciate a bit of help. I'm trying to make a really simple program using SWING where the user clicks a button and a label's text changes from "Hello" to "Bonjour". These are the two errors I'm getting:

java:6: error: Lab4Part1 is not abstract and does not override abstract method actionPerformed(ActionEvent) in ActionListener public class Lab4Part1 extends JFrame implements ActionListener { java:25: error: cannot find symbol label.setText("Bonjour"); 

Any ideas? My code is here:

 import javax.swing.*; import java.awt.*; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class Lab4Part1 extends JFrame implements ActionListener { public Lab4Part1() { super("Lab 4 Part 1"); Container contentPane = getContentPane(); JPanel panel = new JPanel(); contentPane.add(panel); setSize(400, 100); setVisible(true); JLabel label = new JLabel("Hello"); panel.add(label); JButton button = new JButton("Translate to French"); panel.add(button); button.addActionListener(this); } public void handle(ActionEvent event) { label.setText("Bonjour"); } public static void main(String[] args) { Lab4Part1 myFrame = new Lab4Part1(); myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } 
2
  • I've just fixed the first problem, sorry! Dumb mistake on my part, just about how I named my method. However, the second one still stands. The action method can't find the "label" object. Commented Dec 23, 2017 at 17:49
  • edit your question to eliminate the first problem. The second problem is nothing but basic Java, passing references to where needed and knowledge of variable scope (look it up). Commented Dec 23, 2017 at 17:58

1 Answer 1

4

You have to declare the JLabel in the class directly so you can access it from the handle function:

public class Lab4Part1 extends JFrame implements ActionListener { JLabel label; public Lab4Part1() { super("Lab 4 Part 1"); Container contentPane = getContentPane(); JPanel panel = new JPanel(); contentPane.add(panel); setSize(400, 100); setVisible(true); label = new JLabel("Hello"); panel.add(label); JButton button = new JButton("Translate to French"); panel.add(button); button.addActionListener(this); } public void handle(ActionEvent event) { label.setText("Bonjour"); } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.