Search code examples
javaswinginitializationjpaneljcomponent

How to change/edit a JPanel object at startup/init


I want to change a JPanel-object in an applet at startup/init. I can't figure out how to do this. I've made a simple example of my problem in which I clear the JPanel. It does not work when it is called by the init() method but it works when I press the button. What can I do to change the JPanel at startup/init?

import javax.swing.JApplet;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class TestStartUpApplet extends JApplet {

    JPanel panel;   

    @Override
    public void init() {
        System.out.println("Init");
        erasePanel();
    }

    private void erasePanel() {
        Graphics g = panel.getGraphics();
        g.clearRect(0, 0, 117, 48);
    }

    public TestStartUpApplet() {
        getContentPane().setLayout(null);

        panel = new JPanel();
        panel.setBackground(Color.RED);
        panel.setBounds(35, 36, 117, 48);
        getContentPane().add(panel);

        JButton btnTest = new JButton("Test");
        btnTest.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                erasePanel();
            }
        });
        btnTest.setBounds(35, 108, 117, 25);
        getContentPane().add(btnTest);

    }
}

Solution

  • question

    1. no idea why do you want to clear empty JPanel without any custom painting

    2. what's wrong with JPanel with red Background

    3. you clear JApplet before became visible on the screen

    4. doesn't works correctly, because doesn't works anything

    suggestions