JavaSE学习 第十三章 Swing基础

1.重量级组件和轻量级组件

重量级组件是因操作系统而异的,是对本地操作系统的组件的一个封装

轻量级组件是利用Java绘图技术在重量级组件上绘图而成的

Swing与AWT的关系

相关基本概念

Java基础类库(Java Foundation Classes,JFC)

重量组件(Heavy-Weight Components)

轻量组件(Light-Weight Components)

可视化组件(Visual Component)

Swing组件根父类JComponent

java.lang.Object

                |

               +----java.awt.Component

                                   |

                                  +----java.awt.Container

                                                       |

                                                      +----javax.swing.JComponent

 

2.组件介绍

①JFrame

它与Frame最大的区别:它不是单独的一个组件,它是一个容器,可以用来装很多的组件

Container c=jf.getContentPane();

jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 

JFrame继承并扩充了java.awt.Frame类,JFrame实现了javax.swing.WindowConstants接口,

该接口中定义了用于控制窗口关闭操作的整型常量,包括:

DO_NOTHING_ON_CLOSE

HIDE_ON_CLOSE

DISPOSE_ON_CLOSE

EXIT_ON_CLOSE

 

代码:

import java.awt.Container;
import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class TestJFrame{
    public static void main(String[] args){
        JFrame jf = new JFrame("My Test");
        Container c = jf.getContentPane();
        c.setLayout(new FlowLayout(FlowLayout.LEFT,20,20));
        JLabel greet = new JLabel("Hello,World !");
        JLabel bye = new JLabel(" Bye,World ! ");
        bye.setBackground(Color.BLUE);
        bye.setOpaque(true);
        c.add(greet);
        c.add(bye);
        c.setBackground(Color.GREEN);
        jf.setSize(200,100);
        jf.setLocation(400,200);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.setVisible(true);
    }
}

 

②标准对话框

标准对话框(javax.swing.JOptionPane)用于实现程序与用户的便捷交互,其作用包括:

向用户发出错误通知

警告/确认用户操作

接收用户输入简单信息

列举简单选择项供用户选取

 

代码:

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

public class TestJOptionPane implements ActionListener{
    private JFrame jf = new JFrame("标准对话框测试");
    
    public static void main(String[] args){
        new TestJOptionPane().createUI();
    }
    public void createUI(){
        JToolBar jtb = new JToolBar();
        
        String[] s = {"错误","退出确认1","退出确认2","警告","输入","选择"};
        int size = s.length;
        JButton[] button = new JButton[size]; 
        for(int i=0;i<size;i++){
            button[i] = new JButton(s[i]);    
            button[i].addActionListener(this);
            jtb.add(button[i]);    
        }
        jf.add(jtb,"North");
        jf.setSize(350,150);
        jf.setLocation(400,200);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.setVisible(true);
    }
    public void actionPerformed(ActionEvent e){
        String s = e.getActionCommand();
        if(s.equals("错误")){
            JOptionPane.showMessageDialog(null, "要显示的错误信息---",
            "错误提示", JOptionPane.ERROR_MESSAGE);    
        }else if(s.equals("退出确认1")){
            int result = JOptionPane.showConfirmDialog(null, 
                "您真的要退出程序吗?", "请确认", JOptionPane.YES_NO_OPTION);        
            if(result == JOptionPane.OK_OPTION){
                System.exit(0);    
            }
        }else if(s.equals("退出确认2")){
            int result = JOptionPane.showConfirmDialog(null, 
                "退出前是否保存程序?");        
            if(result == JOptionPane.YES_OPTION){
                System.out.println("保存程序---");
                System.exit(0);    
            }else if(result == JOptionPane.NO_OPTION){
                System.exit(0);    
            }
        }else if(s.equals("警告")){
            Object[] options = { "继续", "撤消" };
            int result = JOptionPane.showOptionDialog(null, 
                "本操作可能导致数据丢失", "Warning", JOptionPane.DEFAULT_OPTION, 
                JOptionPane.WARNING_MESSAGE,null, options, options[0]);
            if(result == 0){
                System.out.println("继续操作---");
            }
        }else if(s.equals("输入")){
            String name = JOptionPane.showInputDialog("请输入您的姓名:");
            if(name != null){    
                System.out.println("姓名:" + name);
            }    
        }else if(s.equals("选择")){
            Object[] possibleValues = { "体育", "政治", "经济","文化" };
            Object selectedValue = JOptionPane.showInputDialog(null, 
                "Choose one", "Input",JOptionPane.INFORMATION_MESSAGE, null,
                possibleValues, possibleValues[0]);
            String result = (String)selectedValue;
            if(result != null){
                System.out.println("你选择的是:" + result);
            }
        }        
    }
}

 

 

③JTable 和 JTree

javax.swing.JTable 用于以传统的表格形式来显示数据:

表头:标题行,给出每一列(字段)的名称。

表体:由多行多列、规则矩阵形式的单元格组成,真正的数据信息则显示在每个单元格中。

javax.swing.JTree则是以“树”状结构分层次显示数据信息。

 

代码:

TableExample.java

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

public class TableExample{
    public static void main(String args[]){        
        JFrame myFrame = new JFrame("Table Example");
        Object data[][] ={
            {1,"张三","男","18","010.82607080"},
            {2,"李四","女","24","021.68720890"},
            {3,"王五","男","43","0459.4990893"},
            {4,"赵六","男","32","010.67887098"},
            {5,"任七","女","15","010.84682089"},
            {6,"吴八","男","76","010.63540177"},
        };
        String columnNames[] ={"编号","姓名","性别","年龄","电话"};
        JTable table = new JTable(data,columnNames);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        //JScrollPane pane = new JScrollPane(table);
        JScrollPane pane = new JScrollPane();
        pane.setViewportView(table);
        
        myFrame.add("Center",pane);
        myFrame.setSize(350,150);
        myFrame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);}
        });
        myFrame.setVisible(true);
    }
}

TreeExample.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
public class TreeExample {
    public static void main(String args[]){
        JFrame myFrame = new JFrame("Tree Example");
        DefaultMutableTreeNode rootNode = createNodes();
        JTree tree = new JTree(rootNode);
        tree.setRootVisible(true);
        JScrollPane pane = new JScrollPane();
        pane.setViewportView(tree);
        myFrame.add("Center",pane);
        myFrame.setSize(400,250);
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myFrame.setVisible(true);
    }
    
    public static DefaultMutableTreeNode createNodes(){
        DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Java Stuff");
        DefaultMutableTreeNode resources = new DefaultMutableTreeNode("Resources");
        DefaultMutableTreeNode tools = new DefaultMutableTreeNode("Tools");
        rootNode.add(resources);
        rootNode.add(tools);
        
        DefaultMutableTreeNode webSites =new DefaultMutableTreeNode("Web Sites");
        DefaultMutableTreeNode books = new DefaultMutableTreeNode("Books");
        resources.add(webSites);
        resources.add(books);
        
        DefaultMutableTreeNode magazines = new DefaultMutableTreeNode("Magazines");
        magazines.add(new DefaultMutableTreeNode ("Javology"));
        magazines.add(new DefaultMutableTreeNode ("JavaWorld"));
        
        webSites.add(new DefaultMutableTreeNode ("JavaSoft"));
        webSites.add(new DefaultMutableTreeNode ("Gamelan"));
        webSites.add(magazines);
        
        books.add(new DefaultMutableTreeNode("Special Edition Using Java 1.2"));        
        tools.add(new DefaultMutableTreeNode ("JBuilder"));
        tools.add(new DefaultMutableTreeNode ("Visual J++"));
        tools.add(new DefaultMutableTreeNode ("Visual Age for Java"));
        tools.add(new DefaultMutableTreeNode ("Apptivity"));
        
        return rootNode;
    }
}

3.特殊组件:定时器

javax.swing.Timer提供了定时器功能——用于在指定的时间延迟之后触发ActionEvent事件,以执行所需的处理逻辑。

相关方法:

setRepeats()

setInitialDelay()

stop()

restart()

 

以上四个方法的作用分别是:

是否循环触发

设置首次延迟的时间

停止当前的计时器

计时器重新启动

 

代码:

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.swing.Timer;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;

public class TestTimer{
    public static void main(String[] args){
        JFrame jf = new JFrame("Clock");
        JButton pause = new JButton("Pause");
        JLabel clock = new JLabel("Clock");
        clock.setBackground(Color.GREEN);
        clock.setOpaque(true);
        clock.setHorizontalAlignment(JLabel.CENTER);
        jf.add(clock,"Center");
        jf.add(pause,"North");
        jf.setSize(140,80);
        jf.setLocation(500,300);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.setVisible(true);
        
        MyListener m1 = new MyListener(clock);
        Timer t1 = new Timer(1000,m1);
        t1.setInitialDelay(0);
        t1.start();
        MyListener2 m2 = new MyListener2(t1,pause,clock);
        pause.addActionListener(m2);        
    }    
}

class MyListener  implements ActionListener{
    private JLabel clock;
    public MyListener(JLabel clock){
        this.clock = clock;    
    }    
    public void actionPerformed(ActionEvent e){
        Calendar c = new GregorianCalendar();
        String time = c.get(Calendar.YEAR) + "-" +
                      (c.get(Calendar.MONTH) + 1) + "-" +
                      c.get(Calendar.DATE)  + "  " ;
        int h = c.get(Calendar.HOUR_OF_DAY);
        int m = c.get(Calendar.MINUTE);
        int s = c.get(Calendar.SECOND);
        String ph = h<10 ? "0":"";
        String pm = m<10 ? "0":"";
        String ps = s<10 ? "0":"";        
        time += ph + h + ":" + pm + m + ":" + ps + s; 
        clock.setText(time);
        clock.repaint();
    }    
}

class MyListener2 implements ActionListener{
    private Timer timer;
    private JButton button;
    private JLabel clock;
    private boolean running= true;
    
    public MyListener2(Timer timer,JButton button,JLabel clock){
        this.timer = timer;    
        this.button = button;
        this.clock = clock;
    }    
    public void actionPerformed(ActionEvent e){
        if(running){
            timer.stop();
            button.setText("Replay");
            clock.setBackground(Color.RED);
        }else{
            timer.restart();    
            button.setText("Pause");
            clock.setBackground(Color.green);
        }
        running = !running;
    }    
}

你可能感兴趣的:(JavaSE)