Swing 介绍

写在之前

以下是《Java8编程入门官方教程》中的一些知识,如有错误,烦请指正。涉及的程序如需下载请移步http://down1.tupwk.com.cn/qhwkdownpage/978-7-302-38738-1.zip

概念:Swing定义了一个类和接口的集合,支持丰富的可视化组件集,这些控件共同构建功能强大且易用的图形界面。

组件和容器

组件:是指独立的可视化控件;

容器可以包含一组组件。容器也是组件。

// A simple Swing program. 
 
import javax.swing.*; 
  
class SwingDemo { 
 
  SwingDemo() { 
 
    // Create a new JFrame container. 容器
    JFrame jfrm = new JFrame("A Simple Swing Application"); 
 
    // Give the frame an initial size. 
    jfrm.setSize(275, 100); 
 
    // Terminate the program when the user closes the application. 
    jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
 
    // Create a text-based label. 
    JLabel jlab = new JLabel(" Swing defines the modern Java GUI."); 
 
    // Add the label to the content pane. 
    jfrm.add(jlab); 
 
    // Display the frame. 
    jfrm.setVisible(true); 
  } 
 
  public static void main(String args[]) { 
    // Create the frame on the event dispatching thread. 
    SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
        new SwingDemo(); 
      } 
    }); 
  } 
}

JButton

listing 2
// Demonstrate a push button and handle action events. 
 
import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 
  
class ButtonDemo implements ActionListener { 
 
  JLabel jlab;  
 
  ButtonDemo() { 
 
    // Create a new JFrame container. 
    JFrame jfrm = new JFrame("A Button Example"); 
 
    // Specify FlowLayout for the layout manager. 
    jfrm.setLayout(new FlowLayout()); 
 
    // Give the frame an initial size. 
    jfrm.setSize(220, 90); 
 
    // Terminate the program when the user closes the application. 
    jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
 
    // Make two buttons. 
    JButton jbtnUp = new JButton("Up"); 
    JButton jbtnDown = new JButton("Down"); 
 
    // Add action listeners. 
    jbtnUp.addActionListener(this); 
    jbtnDown.addActionListener(this); 
 
    // Add the buttons to the content pane. 
    jfrm.add(jbtnUp);  
    jfrm.add(jbtnDown);  
 
    // Create a label. 
    jlab = new JLabel("Press a button."); 
 
    // Add the label to the frame. 
    jfrm.add(jlab); 
 
    // Display the frame. 
    jfrm.setVisible(true); 
  } 
 
  // Handle button events. 
  public void actionPerformed(ActionEvent ae) { 
    if(ae.getActionCommand().equals("Up"))  
      jlab.setText("You pressed Up."); 
    else 
      jlab.setText("You pressed down. "); 
  } 
 
  public static void main(String args[]) { 
    // Create the frame on the event dispatching thread. 
    SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
        new ButtonDemo(); 
      } 
    }); 
  } 
}

JTextField

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 
  
class TFDemo implements ActionListener { 
 
  JTextField jtf; 
  JButton jbtnRev; 
  JLabel jlabPrompt, jlabContents;  
 
  TFDemo() { 
 
    // Create a new JFrame container. 
    JFrame jfrm = new JFrame("Use a Text Field"); 
 
    // Specify FlowLayout for the layout manager. 
    jfrm.setLayout(new FlowLayout()); 
 
    // Give the frame an initial size. 
    jfrm.setSize(240, 120); 
 
    // Terminate the program when the user closes the application. 
    jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
 
    // Create a text field. 
    jtf = new JTextField(10); 
 
    // Set the action commands for the text field. 
    jtf.setActionCommand("myTF"); 
 
    // Create the Reverse button. 
    JButton jbtnRev = new JButton("Reverse"); 
 
    // Add action listeners. 
    jtf.addActionListener(this); 
    jbtnRev.addActionListener(this); 
 
    // Create the labels. 
    jlabPrompt = new JLabel("Enter text: "); 
    jlabContents = new JLabel(""); 
 
    // Add the components to the content pane. 
    jfrm.add(jlabPrompt); 
    jfrm.add(jtf);  
    jfrm.add(jbtnRev);  
    jfrm.add(jlabContents); 
 
    // Display the frame. 
    jfrm.setVisible(true); 
  } 
 
  // Handle action events. 
  public void actionPerformed(ActionEvent ae) { 
   
    if(ae.getActionCommand().equals("Reverse")) { 
      // The Reverse button was pressed.  
      String orgStr = jtf.getText(); 
      String resStr = ""; 
 
      // Reverse the string in the text field. 
      for(int i=orgStr.length()-1; i >=0; i--) 
        resStr += orgStr.charAt(i); 
 
      // Store the reversed string in the text field. 
      jtf.setText(resStr);  
    } else 
      // Enter was pressed while focus was in the  
      // text field. 
      jlabContents.setText("You pressed ENTER. Text is: " + 
                           jtf.getText()); 
  } 
 
  public static void main(String args[]) { 
    // Create the frame on the event dispatching thread. 
    SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
        new TFDemo(); 
      } 
    }); 
  } 
}

JCheckBox

import java.awt.*;  
import java.awt.event.*;  
import javax.swing.*;  
   
class CBDemo implements ItemListener {  
  
  JLabel jlabSelected; 
  JLabel jlabChanged; 
  JCheckBox jcbAlpha; 
  JCheckBox jcbBeta; 
  JCheckBox jcbGamma; 
  
  CBDemo() {  
    // Create a new JFrame container.  
    JFrame jfrm = new JFrame("Demonstrate Check Boxes");  
  
    // Specify FlowLayout for the layout manager. 
    jfrm.setLayout(new FlowLayout()); 
  
    // Give the frame an initial size.  
    jfrm.setSize(280, 120);  
  
    // Terminate the program when the user closes the application.  
    jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  
    // Create empty labels. 
    jlabSelected = new JLabel(""); 
    jlabChanged = new JLabel("");  
  
    // Make check boxes. 
    jcbAlpha = new JCheckBox("Alpha");  
    jcbBeta = new JCheckBox("Beta");  
    jcbGamma = new JCheckBox("Gamma");  
 
    // Events generated by the check boxes 
    // are handled in common by the itemStateChanged() 
    // method implemented by CBDemo. 
    jcbAlpha.addItemListener(this); 
    jcbBeta.addItemListener(this); 
    jcbGamma.addItemListener(this); 
  
    // Add checkboxes and labels to the content pane.  
    jfrm.add(jcbAlpha);   
    jfrm.add(jcbBeta);   
    jfrm.add(jcbGamma);   
    jfrm.add(jlabChanged);  
    jfrm.add(jlabSelected);  
  
    // Display the frame.  
    jfrm.setVisible(true);  
  }  
 
  // This is the handler for the check boxes.   
  public void itemStateChanged(ItemEvent ie) { 
    String str = ""; 
 
    // Obtain a reference to the check box that 
    // caused the event. 
    JCheckBox cb = (JCheckBox) ie.getItem(); 
 
    // Report what check box changed. 
    if(cb.isSelected())  
      jlabChanged.setText(cb.getText() + " was just selected."); 
    else 
      jlabChanged.setText(cb.getText() + " was just cleared."); 
 
    // Report all selected boxes. 
    if(jcbAlpha.isSelected()) { 
      str += "Alpha "; 
    }  
    if(jcbBeta.isSelected()) { 
      str += "Beta "; 
    } 
    if(jcbGamma.isSelected()) { 
      str += "Gamma"; 
    } 
 
    jlabSelected.setText("Selected check boxes: " + str); 
  } 
 
  public static void main(String args[]) {  
    // Create the frame on the event dispatching thread.  
    SwingUtilities.invokeLater(new Runnable() {  
      public void run() {  
        new CBDemo();  
      }  
    });  
  }  
}

Jlist

// Demonstrate a simple JList. 
// This program requires JDK 7 or later.
  
import javax.swing.*;  
import javax.swing.event.*; 
import java.awt.*; 
import java.awt.event.*; 
   
class ListDemo implements ListSelectionListener {  
  
  JList<String> jlst; 
  JLabel jlab; 
  JScrollPane jscrlp; 
 
  // Create an array of names. 
  String names[] = { "Sherry", "Jon", "Rachel",  
                     "Sasha", "Josselyn",  "Randy", 
                     "Tom", "Mary", "Ken", 
                     "Andrew", "Matt", "Todd" }; 
 
  ListDemo() {  
    // Create a new JFrame container.  
    JFrame jfrm = new JFrame("JList Demo");  
 
    // Specify a flow Layout. 
    jfrm.setLayout(new FlowLayout());  
 
    // Give the frame an initial size.  
    jfrm.setSize(200, 160);  
  
    // Terminate the program when the user closes the application.  
    jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  
    // Create a JList. 
    jlst = new JList<String>(names); 
 
    // Set the list selection mode to single-selection. 
    jlst.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); 
 
    // Add list to a scroll pane. 
    jscrlp = new JScrollPane(jlst); 
 
    // Set the preferred size of the scroll pane. 
    jscrlp.setPreferredSize(new Dimension(120, 90)); 
 
    // Make a label that displays the selection. 
    jlab = new JLabel("Please choose a name"); 
 
    // Add list selection handler. 
    jlst.addListSelectionListener(this); 
 
    // Add the list and label to the content pane. 
    jfrm.add(jscrlp); 
    jfrm.add(jlab); 
  
    // Display the frame.  
    jfrm.setVisible(true);  
  }  
 
  // Handle list selection events. 
  public void valueChanged(ListSelectionEvent le) {  
    // Get the index of the changed item. 
    int idx = jlst.getSelectedIndex(); 
 
    // Display selection, if item was selected. 
    if(idx != -1) 
      jlab.setText("Current selection: " + names[idx]); 
    else // Othewise, reprompt. 
      jlab.setText("Please choose an name"); 
  }  
 
  public static void main(String args[]) {  
    // Create the frame on the event dispatching thread.  
    SwingUtilities.invokeLater(new Runnable() {  
      public void run() {  
        new ListDemo();  
      }  
    });   
  }  
}

基于Swing的小程序

// Demonstrate a simple JList. 
// This program requires JDK 7 or later.

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

class SwingFC implements ActionListener {

  JTextField jtfFirst;  // holds the first file name
  JTextField jtfSecond; // holds the second file name

  JButton jbtnComp; // button to compare the files

  JLabel jlabFirst, jlabSecond; // displays prompts
  JLabel jlabResult; // displays results and error messages

  SwingFC() {

    // Create a new JFrame container.
    JFrame jfrm = new JFrame("Compare Files");

    // Specify FlowLayout for the layout manager.
    jfrm.setLayout(new FlowLayout());

    // Give the frame an initial size.
    jfrm.setSize(200, 190);

    // Terminate the program when the user closes the application.
    jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // Create the text fields for the file names..
    jtfFirst = new JTextField(14);
    jtfSecond = new JTextField(14);

    // Set the action commands for the text fields.
    jtfFirst.setActionCommand("fileA");
    jtfSecond.setActionCommand("fileB");

    // Create the Compare button.
    JButton jbtnComp = new JButton("Compare");

    // Add action listener for the Compare button.
    jbtnComp.addActionListener(this);

    // Create the labels.
    jlabFirst = new JLabel("First file: ");
    jlabSecond = new JLabel("Second file: ");
    jlabResult = new JLabel("");

    // Add the components to the content pane.
    jfrm.add(jlabFirst);
    jfrm.add(jtfFirst);
    jfrm.add(jlabSecond);
    jfrm.add(jtfSecond);
    jfrm.add(jbtnComp);
    jfrm.add(jlabResult);

    // Display the frame.
    jfrm.setVisible(true);
  }

  // Compare the files when the Compare button is pressed.
  public void actionPerformed(ActionEvent ae) {
    int i=0, j=0;

    // First, confirm that both file names have
    // been entered.
    if(jtfFirst.getText().equals("")) {
      jlabResult.setText("First file name missing.");
      return;
    }
    if(jtfSecond.getText().equals("")) {
      jlabResult.setText("Second file name missing.");
      return;
    }

    // Compare files. Use try-with-resources to manage the files.
    try (FileInputStream f1 = new FileInputStream(jtfFirst.getText());
         FileInputStream f2 = new FileInputStream(jtfSecond.getText()))
    {
      // Check the contents of each file.
      do {
        i = f1.read();
        j = f2.read();
        if(i != j) break;
      } while(i != -1 && j != -1);

      if(i != j)
        jlabResult.setText("Files are not the same.");
      else
        jlabResult.setText("Files compare equal.");
    } catch(IOException exc) {
      jlabResult.setText("File Error");
    }
  }

  public static void main(String args[]) {
    // Create the frame on the event dispatching thread.
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        new SwingFC();
      }
    });
  }
}

使用匿名内部类或者lambda表达式处理事件

匿名内部类是没有名称的内部类,该类的实例只是在需要时即时生成

jbtn.addActionListener(new ActionListener{
  public void actionPerformed(ActionEvent ae){
    // handle action event here
  }
});

通过lambda表达式可以更加简洁

jbtn.addActionListener((ae) -> {
  //handle action event here
}
);

Swing applet

基于Swing的applet扩展了JApplet而不是Applet。JApplet派生自Applet,因此包含后者所有功能,并且支持Swing。类似基于AWT的applet。

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

/*
This HTML can be used to launch the applet:

<applet code="MySwingApplet" width=200 height=80>
</applet>
*/

public class MySwingApplet extends JApplet {
  JButton jbtnUp;
  JButton jbtnDown;

  JLabel jlab;

  // Initialize the applet.
  public void init() {
    try {
      SwingUtilities.invokeAndWait(new Runnable () {
        public void run() {
          makeGUI(); // initialize the GUI
        }
      });
    } catch(Exception exc) {
      System.out.println("Can't create because of "+ exc);
    }
  }

  // This applet does not need to override start(), stop(),
  // or destroy(). 

  // Setup and initialize the GUI. 
  private void makeGUI() {
    // Set the applet to use flow layout.
    setLayout(new FlowLayout());

    // Make two buttons.
    jbtnUp = new JButton("Up");
    jbtnDown = new JButton("Down");

    // Add action listener for Up button..
    jbtnUp.addActionListener(new ActionListener() {     
      public void actionPerformed(ActionEvent ae) { 
        jlab.setText("You pressed Up."); 
      }
    });

    // Add action listener for Down button.
    jbtnDown.addActionListener(new ActionListener() {     
      public void actionPerformed(ActionEvent ae) { 
        jlab.setText("You pressed down."); 
      }     
    });     

    // Add the buttons to the content pane.
    add(jbtnUp);
    add(jbtnDown);

    // Create a text-based label.
    jlab = new JLabel("Press a button.");

    // Add the label to the content pane.
    add(jlab);    
  }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,636评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,890评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,680评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,766评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,665评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,045评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,515评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,182评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,334评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,274评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,319评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,002评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,599评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,675评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,917评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,309评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,885评论 2 341

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,263评论 25 707
  • 面向对象主要针对面向过程。 面向过程的基本单元是函数。 什么是对象:EVERYTHING IS OBJECT(万物...
    sinpi阅读 1,036评论 0 4
  • 1.import static是Java 5增加的功能,就是将Import类中的静态方法,可以作为本类的静态方法来...
    XLsn0w阅读 1,202评论 0 2
  • 方法一:(缺点:麻烦,会让界面会到xp时代) 1. 下载Restorator并输入注册码注册 2. 拖动exe到该...
    小小机器人阅读 726评论 0 1
  • 淡淡忘阅读 47评论 0 0