Java Swing - how to show a panel on top of another panel?

后端 未结 6 1374
野趣味
野趣味 2020-11-30 03:56

I wish to have an internal (non window) dialog to ask for member input. I would like the dialog to be placed centrally on an existing JPanel.

I have looked at layered

6条回答
  •  余生分开走
    2020-11-30 04:18

    You can add an undecorated JDialog like this:

    import java.awt.event.*;
    
    import javax.swing.*;
    
    public class TestSwing {
      public static void main(String[] args) throws Exception {
        JFrame frame = new JFrame("Parent");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800, 600);
        frame.setVisible(true);
    
        final JDialog dialog = new JDialog(frame, "Child", true);    
        dialog.setSize(300, 200);
        dialog.setLocationRelativeTo(frame);
        JButton button = new JButton("Button");
        button.addActionListener(new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            dialog.dispose();
          }
        });
        dialog.add(button);
        dialog.setUndecorated(true);
        dialog.setVisible(true);
      }
    }
    

提交回复
热议问题