Java KeyListener changes JFrame label value

I have the following code:

package testOpdracht1; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.Date; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.io.InputStream; public class MainMenu extends JFrame implements KeyListener { public MainMenu() { initUI(); } public final void initUI() { JLabel label1 = new JLabel("text1"); add(label1); addKeyListener(this); setTitle("Bla"); setPreferredSize(new Dimension(400,250)); setMinimumSize(getPreferredSize()); setResizable(true); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); } public void keyPressed(KeyEvent e) { } public void keyReleased(KeyEvent e) { } public void keyTyped(KeyEvent e) { } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { MainMenu ex = new MainMenu(); ex.setVisible(true); } }); } } 

I want to change the text in the label when any button is pressed. How can i do this? I know that I can call methods from the JFrame class, since my MainMenu class extends it, but I cannot find a way to refer to the label element to change the value.

Yours faithfully,

Luxo

+4
source share
3 answers

Modify your code to look like this:

 package testOpdracht1; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.Date; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.io.InputStream; public class MainMenu extends JFrame implements KeyListener { final JLabel label1 = new JLabel("text1"); public MainMenu() { initUI(); } public final void initUI() { add(label1); addKeyListener(this); setTitle("Bla"); setPreferredSize(new Dimension(400,250)); setMinimumSize(getPreferredSize()); setResizable(true); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); } public void keyPressed(KeyEvent e) { label1.setText("foo"); } public void keyReleased(KeyEvent e) { } public void keyTyped(KeyEvent e) { } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { MainMenu ex = new MainMenu(); ex.setVisible(true); } }); } } 
+1
source

Declare JLabel as a global variable and create an instance like you in initUI (). Now in your ActionListener methods, when you handle the event, you can change the text of your label there.

+1
source

You must declare your JLabel as a global variable, and then in any of the keyXXX() methods, you can change your text using the setText() method of the setText() class.

0
source

Source: https://habr.com/ru/post/1444644/


All Articles