Java摇摆;如何切换面板的可见性?

时间:2011-04-08 19:44:09

标签: java swing toggle visibility jpanel

我将此代码导航到panel1和panel2 用按钮。

(button1和button2)但是当我运行我的代码时,框架保持为空。

有人可以解释一下我做错了什么以及如何实现

以这种方式在panel1和panel2之间切换?首先从panel1开始

代码:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JFrame;

public class togglepanel {

    public static void main(String[] args) {

        final JFrame frame = new JFrame();
        final JPanel panel1 = new JPanel();
        final JPanel panel2 = new JPanel();
        JButton button1 = new JButton("previous frame!");
        JButton button2 = new JButton("next frame");

        frame.setLocationRelativeTo(null);
        frame.setResizable(true);
        frame.setVisible(true);
        frame.setSize(600, 400);
        frame.add(panel1);
        frame.add(panel2);

        panel1.add(button2);
        panel1.setVisible(true);

        panel2.add(button1);
        panel2.setVisible(false);

        button1.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {

                panel1.setVisible(true);
                panel2.setVisible(false);

            }
        });


        button2.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {

                panel1.setVisible(false);
                panel2.setVisible(true);
            }
        });
    }
}

提前致谢

2 个答案:

答案 0 :(得分:4)

使用布局管理器。

frame.setLayout(new FlowLayout());

答案 1 :(得分:4)

另一种有用的方法,我认为更好的方法是使用CardLayout并将两个JPanel添加到使用此CardLayout的容器中。然后,您可以通过调用CardLayout方法轻松交换视图。

如,

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class TogglePanel {
   public static void main(String[] args) {
      final CardLayout cardlayout = new CardLayout();
      final JFrame frame = new JFrame();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      final Container contentPane = frame.getContentPane();
      contentPane.setLayout(cardlayout);

      final JPanel panel1 = new JPanel();
      final JPanel panel2 = new JPanel();
      JButton button1 = new JButton("previous frame!");
      JButton button2 = new JButton("next frame");
      contentPane.setPreferredSize(new Dimension(600, 400));
      contentPane.add(panel1, "Panel 1");
      contentPane.add(panel2, "Panel 2");
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setResizable(true);
      frame.setVisible(true);

      panel1.add(button2);
      panel2.add(button1);

      ActionListener btnListener = new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            cardlayout.next(contentPane);
         }
      };

      button1.addActionListener(btnListener);
      button2.addActionListener(btnListener);

   }
}