2011年4月1日 星期五

Object-Oriented Programming Java. The 7th Week of Class Notes.

// app17_8, Button類別
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JButton;

public class app17_8 extends JFrame implements ActionListener
{
   //static Frame frm=new Frame("Button class");
   //static BorderLayout border=new BorderLayout();//環繞排列
   static JButton buttons[]=new JButton[10];
   static JTextField jtf=new JTextField(); 
   static JButton button=new JButton(); 
   public static void main(String args[])
   {

    app17_8  frm=new app17_8();
    button.addActionListener(frm);
    String numbers[]  = {"0", "1", "2", "3", "4", "5", "6", "7", "8"}; 
    GridLayout glt= new GridLayout(3,3);
    
      frm.setSize(200,200);
      //frm.add(btn1);
      frm.setLayout(glt);
      JPanel p = new JPanel(glt); 
       JPanel g = new JPanel(glt); 
      for(int i=0;i<numbers.length;i++) 
     { 
      buttons[i] = new JButton(numbers[i]); // create buttons
      buttons[i] .addActionListener(frm);
      p.add(buttons[i], glt); 
     } 
      g.add(jtf,glt);
      g.add(button,glt);
      frm.add(p);
      frm.add(g);
      frm.setVisible(true);     
      frm.addWindowListener(new java.awt.event.WindowAdapter() { 
public void windowClosing(java.awt.event.WindowEvent e) { 
System.exit(0); 
} 
});
   }
public void actionPerformed(ActionEvent e) 
{ 

String stringValue;
int t1;
stringValue=jtf.getText();

System.out.println(stringValue);
 t1=  Integer.parseInt(stringValue);
if(t1==1)
 buttons[1].setBackground(Color.RED);
else if(t1==2)
buttons[2].setBackground(Color.RED);
else if(t1==3)
buttons[3].setBackground(Color.RED);
else if(t1==4)
buttons[4].setBackground(Color.RED);
else if(t1==5)
buttons[5].setBackground(Color.RED);
else if(t1==6)
buttons[6].setBackground(Color.RED);
else if(t1==7)
buttons[7].setBackground(Color.RED);
else if(t1==8)
buttons[8].setBackground(Color.RED);
else if(t1==0)
buttons[0].setBackground(Color.RED);
}

}

執行結果

沒有留言:

張貼留言