package cuko; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.GridLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; public class 计算机界面 { JFrame f; JButton b[]; JPanel p; GridLayout g; JTextField t; String a[]= { "7" , "8" , "9" , "/" , "4" , "5" , "6" , "*" , "1" , "2" , "3" , "-" , "0" , "." , "=" , "+" }; public 计算机界面() { f= new JFrame( "计算器" ); t= new JTextField(); p= new JPanel(); p.setBackground(Color.GRAY); g= new GridLayout(4,4); p.setLayout(g); b= new JButton[a.length]; for ( int i=0;i<16;i++) {b[i]= new JButton(a[i]); // p.add(a[i]); p.add(b[i]); //把吧b[]加入面板p中 } f.add(t,BorderLayout.NORTH); //设置一个分格的,作用把文本框放在最上面 f.add(p,BorderLayout.CENTER); //把网格布局放在下面,实现计算器的分布 f.setSize(300,280); f.setVisible( true ); p.setLayout(g); f.add(p); } public static void main(String[] args) { new 计算机界面(); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | package cuko; import java.awt.Color; import java.awt. event .ActionEvent; import java.awt. event .ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class 换颜色的窗体 { JFrame jf; JPanel[] jp; JButton[] jb; public 换颜色的窗体() { jf = new JFrame(); jp = new JPanel[2]; for ( int i =0; i<jp.length; i++) { jp[i] = new JPanel(); } jb = new JButton[4]; jb[0] = new JButton( "红色" ); jb[1] = new JButton( "绿色" ); jb[2] = new JButton( "蓝色" ); jb[3] = new JButton( "自定义色" ); for ( int i =0; i<jb.length; i++) { jp[0].add(jb[i]); } jf.add( "North" , jp[0]); jf.add( "Center" , jp[1]); jb[0].addActionListener( new ActionListener(){ // @Override public void actionPerformed(ActionEvent e){ jp[1].setBackground(Color.RED); }}); jb[1].addActionListener( new ActionListener(){ // @Override public void actionPerformed(ActionEvent e){ jp[1].setBackground(Color.GREEN); }}); jb[2].addActionListener( new ActionListener(){ //@Override public void actionPerformed(ActionEvent e){ jp[1].setBackground(Color.BLUE); }});jb[3].addActionListener( new ActionListener(){ //@Override public void actionPerformed(ActionEvent e){ jp[1].setBackground( new Color(0,255,255)); //自定义颜色范围在0到255 }}); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jf.setSize(300, 200); jf.setVisible( true ); } public static void main(String[] args) { new 换颜色的窗体(); } } |