如何切换面板的可见性

如何切换面板的可见性

本文介绍了Java摇摆;如何切换面板的可见性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用这些代码通过按钮导航到panel1和panel2

i made this code to navigate trough panel1 and panel2with buttons.

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

(button1 and button2) but when i run my code the frame stays empty.

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

Can somebody explain me what i'm doing wrong and how i can accomplish

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

toggling between panel1 and panel2 in this way? Starting with panel1 first

代码:

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);
            }
        });
    }
}

提前感谢

推荐答案

使用布局管理器。

frame.setLayout(new FlowLayout());

frame.setLayout(new FlowLayout());

这篇关于Java摇摆;如何切换面板的可见性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 05:33