【java】实现最简单的分页布局

2/10/2017来源:ASP.NET技巧人气:964

实现如图分页布局

package javaTest;

import java.awt.CardLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class JavaTest {
	
	public static void main(String args[]){
	
	//一个界面只能有一个JFrame	
    JFrame JF = new JFrame();
    JF.setLayout(new GridLayout(1,2));
	
    //JFrame里可以包含若干个JPanel
    JPanel JP1 = new JPanel();
    JP1.setLayout(new GridLayout(3,1));
    JPanel JP2 = new JPanel();
    JP2.setLayout(new CardLayout());
    
    JPanel JP2_1 = new JPanel();
    JPanel JP2_2 = new JPanel();
    JPanel JP2_3 = new JPanel();
    /*......*/
    
    //更改字体大小
    final Font font = new Font(Font.DIALOG,Font.PLAIN,72);
    
    
    Label label1=new Label("Label1");
    Label label2=new Label("Label2");
    Label label3=new Label("Label3");
    label1.setFont(font);
    label2.setFont(font);
    label3.setFont(font);
    
    JP2_1.add(label1);
    JP2_2.add(label2);
    JP2_3.add(label3);
    
    //创建按钮及监听器
    JButton JB1 = new JButton("Button1");
    JB1.addActionListener(new ActionListener() {
	  public void actionPerformed(ActionEvent e) {
		  JP2_1.setVisible(true);
		  JP2_2.setVisible(false);
		  JP2_3.setVisible(false);
	  }});    
    JButton JB2 = new JButton("Button2");
    JB2.addActionListener(new ActionListener() {
	  public void actionPerformed(ActionEvent e) {
		  JP2_1.setVisible(false);
		  JP2_2.setVisible(true);
		  JP2_3.setVisible(false);
	  }});    
    JButton JB3 = new JButton("Button3");
    JB3.addActionListener(new ActionListener() {
	  public void actionPerformed(ActionEvent e) {
		  JP2_1.setVisible(false);
		  JP2_2.setVisible(false);
		  JP2_3.setVisible(true);
	  }});   
    /*......*/

    JP1.add(JB1);
    JP1.add(JB2);
    JP1.add(JB3);

    JP2.add(JP2_1);
    JP2.add(JP2_2);
    JP2.add(JP2_3);
    
    //JF设置
    JF.add(JP1);
    JF.add(JP2);
    JF.setSize(600,400);
    JF.setVisible(true);
	}

}