圖形化使用者介面(一)GUI元素之文本域

來源:互聯網
上載者:User

 這是一個展示文本域使用的小程式。
Fahrenheit顯示一個GUI視窗,其中一個文本域,可以鍵入Fahrenheit(華氏)溫度。當按斷行符號鍵時,顯示對應的Celsius(攝

氏)溫度。當按斷行符號鍵時,顯示對應的Celsius(攝氏)溫度。

當按下斷行符號時(且游標在文本域中),文本域產生動作事件。所以需要設定一個監聽器對象來響應動作事件,這與前面的例子是類似的。

 

注意,按鈕和文本域產生同一類的事件——動作事件。所以Fahrenheit程式也可以重新設計:向GUI中添加一個JButton對象,當按下按鈕時,用用這個對象完成溫度的轉換。這種情況下,可用同一個監聽器在同一時刻監聽多個組件。所以監聽器必須添加到文本域及按鈕上,這樣就可以使用兩種輸入方式了。

 

效果

Fahrenheit.java

 

import javax.swing.JFrame;

public class Fahremheit {

     //建立一個溫度轉換GUI
    public static void main(String[] args) {
        JFrame frame = new JFrame("Fahrenheit");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  
        FahrenheitPanel panel = new FahrenheitPanel();
        frame.getContentPane().add(panel);
  
        frame.pack();
       frame.setVisible(true);
   }
}

 

FahrenheitPanel.java

 

import java.awt.Color;
import  .......

 

public class FahrenheitPanel extends JPanel {
    private JLabel inputLabel, outputLabel, resultLabel;
    private JTextField fahrenheit;
 
    public FahrenheitPanel(){
         inputLabel = new JLabel("Enter Fahrenheit temperature: ");
         outputLabel = new JLabel("Temperature in Celsius: ");
         resultLabel = new JLabel("----");
  
         fahrenheit = new JTextField(5);
         fahrenheit.addActionListener(new TempListener());
  
        add(inputLabel);
        add(fahrenheit);
        add(outputLabel);
        add(resultLabel);
  
        setPreferredSize(new Dimension(300,75));
        setBackground(Color.yellow);
  }
 
    //溫度輸入文字框的監聽器
   private class TempListener implements ActionListener{
    //示範轉換,當斷行符號鍵按下的時候
     public void actionPerformed (ActionEvent event){
        int fahrenheitTemp, celsiusTemp;
   
        String text = fahrenheit.getText();
   
        fahrenheitTemp = Integer.parseInt(text);
        celsiusTemp = (fahrenheitTemp - 32) * 5/9;
   
        resultLabel.setText(Integer.toString(celsiusTemp));
    }
  }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.