简体   繁体   中英

JPanel can't be added to JLayeredPane outside the JFrame's constructor

I want to add a JPanel to a JLayeredPane when the user clicks enter, but the JPanel is not showing up. If i add the JPanel to the JLayeredPane in the JFrame's constructor, everything is working correctly.

What do i have to do, that the JPanel is showing up, when the user clicks 'enter'?

Here's the code:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.KeyStroke;

public class Test extends javax.swing.JFrame {

    public static void main(String[] args) {
        Test test = new Test();
        test.setSize(800, 500);
        test.setVisible(true);
    }

    public Test() {
        setLayout(new BorderLayout());

        //LayeredPane on JFrame
        JLayeredPane jlp = new JLayeredPane();
        jlp.setLayout(new BorderLayout());
        this.add(jlp, BorderLayout.CENTER);

        //Adds a JPanel to the North
        JPanel jPNorth = new JPanel();
        jPNorth.setBackground(Color.RED);
        jlp.add(jPNorth, BorderLayout.NORTH, JLayeredPane.DEFAULT_LAYER);

        //Adds Enter Keybinding
        InputMap key_input_map = jlp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
        ActionMap key_action_map = jlp.getActionMap();

        key_input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false), "add_jpanel");

        key_action_map.put("add_jpanel", new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {

                JPanel jPSouth = new JPanel();
                jPSouth.setBackground(Color.YELLOW);
                jlp.add(jPSouth, BorderLayout.SOUTH, JLayeredPane.DEFAULT_LAYER);

                System.out.println("enter");
            }
        });
    }
}

Thanks, Jumagoro

You did everything correct, the solution is very simple. When you dynamically add swing Component s to each other, you must to use component.repaint(); and component.revalidate(); to redraw the elements. Add the two commands after everything is added. So your actionPerformed method should be changed to the following:

public void actionPerformed(ActionEvent e) {
    JPanel jPSouth = new JPanel();
    jPSouth.setBackground(Color.YELLOW);
    jlp.add(jPSouth, BorderLayout.SOUTH, JLayeredPane.DEFAULT_LAYER);
    //Need these to here!
    jlp.repaint();
    jlp.revalidate();
    System.out.println("enter");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM