且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

动态添加的JPanels没有出现在Swing中

更新时间:2023-12-05 22:28:22

如果将组件添加到容器中,则需要告诉容器的布局管理器布置它们包含的所有组件通过调用 revalidate(),然后有时在容器上调用 repaint(); 。所以,像... ...

If you add a component to a container you need to tell the container's layout managers to layout all the components they contain by calling revalidate() and then by sometimes calling repaint(); on the container. So, something like...

JPanel contentPane = (JPanel)displayFrames.get(f).getContentPane();
contentPane.add(new EnterPINPanel(), BorderLayout.CENTER);
contentPane.revalidate();
contentPane.repaint();

话虽如此,您的应用程序设计看起来有点不同。你真的使用JFrames的ArrayList吗?大多数真实世界的应用程序不使用一堆单独的窗口,而是在一个主窗口中交换显示,你可以通过使用一个JFrame和通过CardLayout交换视图来使用Swing做类似的事情。

Having said this, your application design looks a bit different. Do you really use an ArrayList of JFrames? Most real-world applications don't use a bunch of separate windows but rather swap displays in one main window, and you can do a similar thing with Swing by using just one JFrame and swap views via a CardLayout.

编辑2

如果您尝试怎么办:

Edit 2
What if you try:

  int f = showFrame(frame, controller);
  JPanel contentPane = (JPanel)displayFrames.get(f).getContentPane();
  contentPane.removeAll();
  contentPane.setLayout(new BorderLayout()); // just to be sure
  contentPane.add(headerPanel, BorderLayout.PAGE_START);
  contentPane.add(new EnterPINPanel(), BorderLayout.CENTER);
  contentPane.add(footerPanel, BorderLayout.PAGE_END);
  contentPane.revalidate(); // *** note that it's **re**validate
  contentPane.repaint();
  displayFrames.get(f).setVisible(true);

再次,如果这没有帮助,那么你应该创建并发布简短,自包含,正确(可编译),示例或SSCCE

Again, if this doesn't help, then you should create and post a "Short, Self Contained, Correct (Compilable), Example" or SSCCE