Swing 介紹

寫在之前

以下是《Java8編程入門官方教程》中的一些知識(shí)慈参,如有錯(cuò)誤腥放,煩請(qǐng)指正。涉及的程序如需下載請(qǐng)移步http://down1.tupwk.com.cn/qhwkdownpage/978-7-302-38738-1.zip

概念:Swing定義了一個(gè)類和接口的集合,支持豐富的可視化組件集册烈,這些控件共同構(gòu)建功能強(qiáng)大且易用的圖形界面。

組件和容器

組件:是指獨(dú)立的可視化控件婿禽;

容器可以包含一組組件赏僧。容器也是組件。

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

使用匿名內(nèi)部類或者lambda表達(dá)式處理事件

匿名內(nèi)部類是沒有名稱的內(nèi)部類扭倾,該類的實(shí)例只是在需要時(shí)即時(shí)生成

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

通過(guò)lambda表達(dá)式可以更加簡(jiǎn)潔

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

Swing applet

基于Swing的applet擴(kuò)展了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);    
  }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末恢筝,一起剝皮案震驚了整個(gè)濱河市哀卫,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌撬槽,老刑警劉巖此改,帶你破解...
    沈念sama閱讀 206,723評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異侄柔,居然都是意外死亡共啃,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,485評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門暂题,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)移剪,“玉大人,你說(shuō)我怎么就攤上這事薪者∽菘粒” “怎么了?”我有些...
    開封第一講書人閱讀 152,998評(píng)論 0 344
  • 文/不壞的土叔 我叫張陵言津,是天一觀的道長(zhǎng)攻人。 經(jīng)常有香客問(wèn)我,道長(zhǎng)悬槽,這世上最難降的妖魔是什么怀吻? 我笑而不...
    開封第一講書人閱讀 55,323評(píng)論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮初婆,結(jié)果婚禮上蓬坡,老公的妹妹穿的比我還像新娘猿棉。我一直安慰自己,他們只是感情好渣窜,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,355評(píng)論 5 374
  • 文/花漫 我一把揭開白布铺根。 她就那樣靜靜地躺著,像睡著了一般乔宿。 火紅的嫁衣襯著肌膚如雪位迂。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,079評(píng)論 1 285
  • 那天详瑞,我揣著相機(jī)與錄音掂林,去河邊找鬼。 笑死坝橡,一個(gè)胖子當(dāng)著我的面吹牛泻帮,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播计寇,決...
    沈念sama閱讀 38,389評(píng)論 3 400
  • 文/蒼蘭香墨 我猛地睜開眼锣杂,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了番宁?” 一聲冷哼從身側(cè)響起元莫,我...
    開封第一講書人閱讀 37,019評(píng)論 0 259
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎蝶押,沒想到半個(gè)月后踱蠢,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 43,519評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡棋电,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,971評(píng)論 2 325
  • 正文 我和宋清朗相戀三年茎截,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片赶盔。...
    茶點(diǎn)故事閱讀 38,100評(píng)論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡企锌,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出于未,到底是詐尸還是另有隱情霎俩,我是刑警寧澤,帶...
    沈念sama閱讀 33,738評(píng)論 4 324
  • 正文 年R本政府宣布沉眶,位于F島的核電站,受9級(jí)特大地震影響杉适,放射性物質(zhì)發(fā)生泄漏谎倔。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,293評(píng)論 3 307
  • 文/蒙蒙 一猿推、第九天 我趴在偏房一處隱蔽的房頂上張望片习。 院中可真熱鬧捌肴,春花似錦、人聲如沸藕咏。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,289評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)孽查。三九已至饥悴,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間盲再,已是汗流浹背西设。 一陣腳步聲響...
    開封第一講書人閱讀 31,517評(píng)論 1 262
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留答朋,地道東北人贷揽。 一個(gè)月前我還...
    沈念sama閱讀 45,547評(píng)論 2 354
  • 正文 我出身青樓梦碗,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親洪规。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,834評(píng)論 2 345

推薦閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 171,515評(píng)論 25 707
  • 面向?qū)ο笾饕槍?duì)面向過(guò)程库车。 面向過(guò)程的基本單元是函數(shù)。 什么是對(duì)象:EVERYTHING IS OBJECT(萬(wàn)物...
    sinpi閱讀 1,046評(píng)論 0 4
  • 1.import static是Java 5增加的功能,就是將Import類中的靜態(tài)方法柠衍,可以作為本類的靜態(tài)方法來(lái)...
    XLsn0w閱讀 1,213評(píng)論 0 2
  • 方法一:(缺點(diǎn):麻煩,會(huì)讓界面會(huì)到xp時(shí)代) 1. 下載Restorator并輸入注冊(cè)碼注冊(cè) 2. 拖動(dòng)exe到該...
    小小機(jī)器人閱讀 732評(píng)論 0 1
  • 淡淡忘閱讀 48評(píng)論 0 0