2011-03-18

第五堂課

今天一開始,先從老師的部落格

程式設計工藝大師(Master of Computer Programming)    

複製程式碼↓



儲存成java檔之後,轉成class檔
執行,就會跑出一個沒有功能的button↓



可以下載這個檔案

另存並執行,會出現下列的圖↓





修改第一個儲存的程式碼
如果要使用Jbutton記得要加上 import javax.swing.*; 套件

在public class ButtonText後加上extends JFrame implements ActionListener 

並在public static void main(String[] args) 後的{  }裡打上
ButtonText test = new ButtonText();  

在ButtonText(){  }裡面打
JButton mybutton1 = new JButton("Submit"); 
JButton mybutton2 = new JButton("Submit"); 

mybutton1.addActionListener(this); 

getContentPane().add(mybutton1); 
 getContentPane().add(mybutton2); 


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
setLayout(new FlowLayout());
setSize(200,100);
setVisible(true);

在最後面的地方加上
public void actionPerformed(ActionEvent e) {
int rn ;   //rn是random的意思
rn=(int)(Math.random()*49);
Systme.out.println(rn);
}


就可以產生出一個0~48之內的隨機整數↓






今天的作業呢!就是創造出一個跟樂透一樣,
可以按一個鍵就一次跑出七個數字的程式碼呦!


參考     大小樂透use Math.random - Java作業- Yahoo!奇摩部落格


作業的程式碼


import java.awt.*; 
import java.awt.event.*;
import javax.swing.*;
public class ButtonText extends JFrame implements ActionListener  { 
 public static void main(String[] args) {
ButtonText test = new ButtonText();    
  }

ButtonText()
{
    
JButton mybutton1 = new JButton("Submit"); 
JButton mybutton2 = new JButton("Submit"); 

mybutton1.addActionListener(this); 
//Container contentPane = frame.getContentPane();

//contentPane.add(mybutton1);  
//contentPane.add(mybutton2);  
 getContentPane().add(mybutton1); 
 getContentPane().add(mybutton2); 

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
setLayout(new FlowLayout());
setSize(200,100);
setVisible(true);
/* 

        System.exit(0);

 frame.addWindowListener(new WindowAdapter(){
      public void windowClosing(WindowEvent e){
*/
}
public void actionPerformed(ActionEvent e) { 
int rn1,rn2,rn3,rn4,rn5,rn6,rn7;
rn1=(int)(Math.random()*49)+1;    //記得要加1喔
rn2=(int)(Math.random()*49)+1;
rn3=(int)(Math.random()*49)+1;
rn4=(int)(Math.random()*49)+1;
rn5=(int)(Math.random()*49)+1;
rn6=(int)(Math.random()*49)+1;
rn7=(int)(Math.random()*49)+1;

System.out.println(rn1);
System.out.println(rn2);
System.out.println(rn3);
System.out.println(rn4);
System.out.println(rn5);
System.out.println(rn6);
System.out.println(rn7);

}

}


結果↓





沒有留言:

張貼留言