《Java程式設計》第14周實驗作業:GUI編程初步

來源:互聯網
上載者:User

標籤:

【目的】
1. 掌握圖形化WindowBuilder的使用方式。
2. 理解Java中事件機制。
 
【目標】
1. 掌握Eclipse中安裝WindowBuilder的方法。
2. 瞭解Java中事件機制。
3. 瞭解GUI中重用控制項。
   4. 完成一個GUI作業,作業要求如下。
(1)功能:有一個按鈕(JButton)和一個標籤(JLabel),當點擊 按鈕後,能夠顯示下一張圖片。點擊圖片下載,獲得圖片樣本。
import java.awt.EventQueue;import java.awt.Image;import javax.imageio.ImageIO;import javax.swing.ImageIcon;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.border.EmptyBorder;import javax.swing.JButton;import javax.swing.JLabel;import java.awt.Color;import java.awt.event.ActionListener;import java.awt.event.ActionEvent;import java.io.File;import java.io.IOException;public class ImgDemo extends JFrame {private JPanel contentPane;private int idImg = 1;/** * Launch the application. */public static void main(String[] args) {EventQueue.invokeLater(new Runnable() {public void run() {try {ImgDemo frame = new ImgDemo();frame.setVisible(true);} catch (Exception e) {e.printStackTrace();}}});}/** * Create the frame. */public ImgDemo() {setTitle("\u56FE\u7247\u663E\u793A");setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setBounds(100, 100, 576, 604);contentPane = new JPanel();contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));setContentPane(contentPane);contentPane.setLayout(null);final JLabel lblNewLabel = new JLabel("New label");lblNewLabel.setBackground(Color.YELLOW);lblNewLabel.setForeground(Color.PINK);lblNewLabel.setBounds(58, 86, 600, 500);contentPane.add(lblNewLabel);JButton btnNewButton = new JButton("\u663E\u793A\u4E0B\u4E00\u5F20\u56FE\u7247");btnNewButton.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {ImageIcon icon;try {// 擷取圖片的路徑String strImgFile = "E:/demoPhoto/";// 得到圖片的完整路徑strImgFile = strImgFile + String.valueOf(idImg) + ".jpg";// 讀取圖片icon = new ImageIcon(ImageIO.read(new File(strImgFile)));// 從圖表中擷取到圖片Image image = icon.getImage(); // 縮放映像Image smallImage = image.getScaledInstance(400,400,Image.SCALE_FAST);//把Image檔案轉化為ImageIconicon = new ImageIcon(smallImage);lblNewLabel.setIcon(icon);// 為下一張圖片做準備,一共9張圖片,顯示完第9張後,重新顯示第一張idImg = idImg+1;if(idImg==10)idImg = 1;} catch (IOException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}}});btnNewButton.setBounds(194, 37, 153, 28);contentPane.add(btnNewButton);}}

《Java程式設計》第14周實驗作業:GUI編程初步

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.