import java . awt . * ;
import javax . swing . * ;
public class JFramedemo extends JFrame {
private Box box ;
private Container container ;
private JTextField text ;
private JPanel panel1 , panel2 ;
private String S1 [ ] = { "Backspace" , "CE" , "C" } ; //將計算器上顯示的內容存在數組裏面
private String S2 [ ] = { "1" , "2" , "3" , "+" , "sqrt" , "4", "5" , "6" , "-" , "%" , "7" , "8" , "9" , "*" , "1/x" , "0" ,"+/-" , "." , "/" , "=" } ;
public JFramedemo ( ) {
this . setTitle ( "計算器顯示界面" ) ;
this . setBounds ( 300 , 300 , 500 , 500 ) ;
container = getContentPane ( ) ;
container . setLayout ( new FlowLayout ( ) ) ; //將內容窗格設置成流式佈局
text = new JTextField ( 15 ) ;
box = Box . createVerticalBox ( ) ;
panel1 = new JPanel ( new GridLayout ( 1 , 3 , 20 , 0 )) ;
//panel1.setLayout(new GridLayout(1,3,10,0));
panel2 = new JPanel ( ) ;
panel2 . setLayout ( new GridLayout ( 4 , 5 , 10 , 10 ) );
for ( int i = 0 ; i < 3 ; i + + ) //將數組S1的內容加到panel1的Button按鈕上
{
panel1 . add ( new JButton ( S1 [ i ] ) ) ;
}
for ( int j = 0 ; j < 20 ; j + + ) //將數組S2的內容加到panel2的Button按鈕上
{
panel2 . add ( new JButton ( S2 [ j ] ) ) ;
}
box . add ( text ) ;
box . add ( Box . createVerticalStrut ( 15 ) ) ;
box . add ( panel1 ) ;
box . add ( Box . createVerticalStrut ( 25 ) ) ;
box . add ( panel2 ) ;
container . add ( box ) ;
pack ( ) ; //調整窗口的大小,使其適應組件的大小和佈局
setVisible ( true ) ;
this . setDefaultCloseOperation ( EXIT_ON_CLOSE ) ;
}
public static void main ( String [ ] args ) {
new JFramedemo ( ) ;
}
}
java
心得:數組
1在編寫計算器的過程當中要注意包的使用佈局
2注意add方法的使用this