一个 JFrame 和两个 JPanel [英] One JFrame and Two JPanels

查看:44
本文介绍了一个 JFrame 和两个 JPanel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Java 新手,我遇到了有关面板的问题.我的程序中有一个 JFrame 和两个 JPanels.

I'm a newbie in Java and I have a problem regarding panels. I have one JFrame and two JPanels in my program.

  • 当我点击button1时,panel1将显示在框架中.
  • 当我点击 button2 时,panel2 将显示在框架中,而 panel1 将消失/隐藏.
  • When I click button1, panel1 will show in the frame.
  • When I click button2, panel2 will show in the frame and panel1 will disappear/hide.

问题是panel1 不能只显示panel2.如何以这种方式显示两个面板?

The problem is that panel1 can't show only panel2. How to show the two panels in this way?

这是我的代码:

public class test{

public static void main(String args[]){

     JButton b1 = new JButton("show p1");
     JButton b2 = new JButton("show p2");
     JLabel l1 = new JLabel("This is p1");
     JLabel l2 = new JLabel("This is p2");

     final JPanel p1 = new JPanel(new FlowLayout());
     p1.add(l1);
     final JPanel p2 = new JPanel(new FlowLayout());
     p2.add(l2);
     JPanel buttonPNL = new JPanel(new FlowLayout());
     buttonPNL.add(b1);
     buttonPNL.add(b2);

     b1.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
                p1.setVisible(true);
                p2.setVisible(false);   
        }
     });

     b2.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                    p1.setVisible(false);
                    p2.setVisible(true);   
            }
      });

     JFrame frm = new JFrame();
     frm.setLayout(new BorderLayout());
     frm.add(p1,BorderLayout.CENTER);
     frm.add(p2,BorderLayout.CENTER);
     frm.add(buttonPNL,BorderLayout.SOUTH);
     frm.setVisible(true);
     frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     frm.setSize(300,300);
 }
}

推荐答案

BorderLayout 每个约束只能处理一个组件,也就是你在 CENTER 中添加 p2 的那一刻,p1 就被忘记了.因此,要么在您的 actionListeners 中执行删除/添加操作,要么使用另一个 LayoutManager,例如 f.i.CardLayout.

BorderLayout can only handle one component per constraint, that is the moment you add p2 in CENTER, p1 is forgotten. So either do a remove/add in your actionListeners or use another LayoutManager, like f.i. CardLayout.

这篇关于一个 JFrame 和两个 JPanel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆