好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

java实现面板之间切换功能

本文实例为大家分享了java实现面板之间切换的具体代码,供大家参考,具体内容如下

如图:

关键技术:事件监听,设置显示面板,重新刷新验证。

?

1

2

setContentPane(jp2); //设置显示的新面板

revalidate(); //重新验证

完整代码如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JPanel;

public class ceshi2 extends JFrame{

    JButton b1;

    JButton b2;

    JButton b3;

    JButton b4;

public ceshi2() {

    setBounds( 200 , 150 , 500 , 300 ); //设置窗体大小,位置。

    JPanel jp1= new JPanel(); //设置两个面板

    JPanel jp2= new JPanel();

    b1= new JButton( "下一步" );

    b2= new JButton( "路人甲" ); //按钮2和4,标签1和2显示成果

    b3= new JButton( "上一步" );

    b4= new JButton( "路人乙" );

    JLabel l1= new JLabel( "这是第一个面板" );

    JLabel l2= new JLabel( "这是第二个面板" );

    b1.setBounds( 20 , 20 , 100 , 40 );

    b2.setBounds( 20 , 120 , 100 , 40 );

    b3.setBounds( 20 , 20 , 100 , 40 );

    b4.setBounds( 20 , 120 , 100 , 40 );

    l1.setBounds( 100 , 300 , 200 , 50 );

    l2.setBounds( 100 , 300 , 200 , 50 );

    jp1.add(b1); //添加到面板1中

    jp1.add(b2);

    jp1.add(l1);

    jp2.add(l2); //添加到面板2中

    jp2.add(b3);

    jp2.add(b4);

    add(jp1); //首先显示的是面板1

    b1.addActionListener( new ActionListener() { //添加监听

        

        @Override

        public void actionPerformed(ActionEvent e) {

            // TODO Auto-generated method stub            

            setContentPane(jp2); //设置显示的新面板

            revalidate(); //重新验证

            

        }

    });

    b3.addActionListener( new ActionListener() {

        public void actionPerformed(ActionEvent e) {

            // TODO Auto-generated method stub            

            setContentPane(jp1);

            revalidate();

        }

    });

    setVisible( true );

    setLayout( null );

    setDefaultCloseOperation(EXIT_ON_CLOSE);

}

public static void main(String[] args) {

    new ceshi2();

}

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

原文链接:https://blog.csdn.net/weixin_52473454/article/details/120293208

查看更多关于java实现面板之间切换功能的详细内容...

  阅读:19次