Java上机

import javax.swing.*;
import javax.swing.border.Border;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
public class mytext1 {
    JFrame f;
    JPanel p;
    JButton[] b;
    JTextField  t;
    String title[]= {"7","8","9","/","4","5","6","*","1","2","3","-","0",".","=","+"};
    GridLayout gl;
    public mytext1() {
        f=new JFrame("计算机");
        p=new JPanel();
        b=new JButton[16];
        t=new JTextField(10);
        for(int i=0;i<16;i++) {
            b[i]=new JButton(title[i]);
            p.add(b[i]);
            b[i].setBackground(Color.pink);
        }
        gl=new GridLayout(4,4,5,5);    //为gl创建对象
        p.setLayout(gl);               //将面板的默认流布局改为网格布局
        f.add(t,BorderLayout.NORTH);
        f.add(p,BorderLayout.CENTER);
        f.setSize(400,300);
        f.setVisible(true);
    }
    
    public static void main(String[] args) {
        new mytext1();

    }

}
package daima;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;
public class mytext2 implements ActionListener {
     JFrame f;
     JPanel p1,p2;
     JButton[]  b;
     String title[]= {"红色","绿色","蓝色"};
     public mytext2() {
         f=new JFrame();
         p1=new JPanel();
         p2=new JPanel();
         b=new JButton[3];
         for(int i=0;i<3;i++) {
             b[i]=new JButton(title[i]);
             b[i].addActionListener(this);
             p1.add(b[i]); 
         }
         f.add(p1,BorderLayout.NORTH);
         f.add(p2,BorderLayout.CENTER);
         f.setSize(400,300);
         f.setVisible(true);
     }
     public static void main(String[]args) {
         new mytext2();
     }
    @Override
    public void actionPerformed(ActionEvent e) {
    //    e.getSource()来区分响应哪个按钮
        if(e.getSource()==b[0]) {
            p2.setBackground(Color.red);
    }else if(e.getSource()==b[1]) {
            p2.setBackground(Color.green);      
    }else {
        p2.setBackground(Color.blue);   
    }   
}}

原文地址:https://www.cnblogs.com/lusilin/p/10920165.html