Repainting elements in a panel

Twinkie

Banned
Messages
1,389
Reaction score
12
Points
0
How can I repaint elements in a panel? I was told all modifications to an element have to be done before being added to a panel. How can you repaint an element after it has been added to panel, then added to a window? Example code bellow.

Code:
package keylogger;

import javax.swing.*;
import java.awt.*;

public class Main {

    static JLabel text;
    static JFrame window;

    public static void main(String[] args) {
        window = new JFrame("Keylogger");
        window.setSize(400, 100);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setLayout(new FlowLayout(FlowLayout.CENTER));
        text = new JLabel();
        window.add(new JScrollPane(text));
        window.addKeyListener(new Writter());
        window.setVisible(true);
    }

}
Code:
package keylogger;

import java.awt.event.*;

public class Writter extends KeyAdapter {

    public void keyTyped(KeyEvent event) {
        Main.text.setText(Main.text.getText() + event.getKeyChar());
        Main.window.repaint();
    }

}
Outcome: The window appears without errors but the text typed does not appear in the window.

It is acknowledged that this is not the most efficient way to do this, I am just practicing. Apparently it was worth it :)
 
Last edited:

Gouri

Community Paragon
Community Support
Messages
4,565
Reaction score
245
Points
63
Hi Twinkie,

I checked the code. It is ok To know what exactly happening
set some default text to the JLabel

text = new JLabel("Hello");

In the Writter
change this to observe the change.

Main.text.setText("" + event.getKeyChar());

To see the changes i done this. Actually the size of the label is not changing so when you append the text, it is creating scroll bars So i am just adding the typed key to label
 
Last edited:

Twinkie

Banned
Messages
1,389
Reaction score
12
Points
0
How can I make it work the way it way intended, which was to changes size and scroll when it reached the end of the window?

I think it has something to do with the revalidate() method of the JScrollPane although I am not sure how to work it...
 
Last edited:

Gouri

Community Paragon
Community Support
Messages
4,565
Reaction score
245
Points
63
Hi Twinkie,

Just add the label don't create the scroll pane in Main class
window.add(text);
 

Twinkie

Banned
Messages
1,389
Reaction score
12
Points
0
Yes, but then the label can grow to a size beyond the window. When that happens, I would like it to have scroll bars. Overcomplicated, I know, but the point is for me to know how to do it.
 
Top