minh
minh

Reputation: 9

Need help on Swing JPanel

I have a very basic question on 'panel'.

I have my same program below, which I want to hit on a submit button on panel 1 and my program would print a hello you hit on a submit button on panel 2.

I do not see the program print hello you hit on a submit button on panel 2 while a hit a submit button on panel 2. But when I touch the frame, then magically the hello you hit on a submit button on panel 2 appear on panel 2.

What is going on ? I don't know the answer so I would like to ask if you know why?

Attached is my code:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;


public class Main {
    private JFrame frame = new JFrame();
    private JLayeredPane lpane = new JLayeredPane();
    private JPanel panelBlue = new JPanel();
    private JPanel panelGreen = new JPanel();
    private JButton btn1 = new JButton ("Button1");

    public Main()
    {
        frame.setPreferredSize(new Dimension(600, 400));
        frame.setLayout(new BorderLayout());
        frame.add(lpane, BorderLayout.CENTER);
        lpane.setBounds(0, 0, 600, 400);
        panelBlue.setBackground(Color.BLUE);
        panelBlue.setBounds(0, 0, 600, 400);
        panelBlue.setOpaque(true);
        panelBlue.add (btn1);

        panelGreen.setBackground(Color.GREEN);
        panelGreen.setBounds(200, 100, 100, 100);
        panelGreen.setOpaque(true);


        btn1.addActionListener(new ActionListener () {

            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                panelGreen.add(new JLabel ("You click button1"));


            }});



        lpane.add(panelBlue, new Integer(0), 0);
        lpane.add(panelGreen, new Integer(1), 0);
        frame.pack();
        frame.setVisible(true);
    }


    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new Main();
    }
}

Upvotes: 0

Views: 37

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347324

Call panelGreen.revaliate() and panelGreen.repaint() after you add the label. Swing layouts are lazy.

@Override
public void actionPerformed(ActionEvent e) {
    panelGreen.add(new JLabel ("You click button1"));
    panelGreen.revaliate();
    panelGreen.repaint();
}});

Calling setOpaque is irrelevant as the components are opaque to start with

Upvotes: 1

Related Questions