第七次上机作业

1.设计一个如图所示的界面,不需要提供组件的功能。

代码:

import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.*;
public class counter {
JFrame a;
JPanel b;
GridLayout c ;
JTextField t;
JButton[] b1;
String b2[]={"7","8","9","/","4","5","6","*","1","2","3","-","0",".","=","+"};
public counter() {
a=new JFrame("计算器");
b=new JPanel();
c=new GridLayout(4,4,3,3);
t=new JTextField();
b1=new JButton[b2.length];
a.setVisible(true);
a.setBounds(500, 300, 350, 250);
a.setLayout(new BorderLayout());
a.add(b,BorderLayout.CENTER);
a.add(t,BorderLayout.NORTH);
b.setLayout(c);
for(int i=0;i<b2.length;i++){
b1[i]=new JButton(b2[i]);
b.add(b1[i]);
}
}
public static void main(String[] args) {
new counter();
}
}

运行结果:

2.编写可改变背景颜色的窗口。

代码:

package class7;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class color implements ActionListener{
JFrame a;
JPanel b,p;
JButton b1,b2,b3;
public color() {
a = new JFrame();
b = new JPanel();
p = new JPanel();
b1 = new JButton("红色");
b2 = new JButton("绿色");
b3 = new JButton("蓝色");
b1.addActionListener(this);
b1.setActionCommand("red");
b2.addActionListener(this);
b2.setActionCommand("green");
b3.addActionListener(this);
b3.setActionCommand("blue");
a.setVisible(true);
a.setSize(400, 300);
a.setLayout(new BorderLayout());
a.add(b,BorderLayout.CENTER);
a.add(p,BorderLayout.NORTH);
p.add(b1);
p.add(b2);
p.add(b3);
}
public static void main(String[] args) {
new color();
}
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("red")){
b.setBackground(Color.red);
}else if(e.getActionCommand().equals("green")){
b.setBackground(Color.green);
}else if(e.getActionCommand().equals("blue")){
b.setBackground(Color.blue);
}
}
}

运行结果:

 心得:学习,并不是每天上课跟着老师走,老师说什么,就学什么;在大学,我认为学习更多的是自己查阅资料,主动学习。在本次实训,写改变背景颜色的代码的时候,完全无从下手,但后来通过自己百度查阅,找到了写的方法,在上机课的时候通过问老师又了解到了另一种更为简便的方法,它让我意识到,书本上和老师讲的知识还是太少太少,要想学好这门专业,就必须自己下更多的功夫去实践。毕竟 自己选的专业,哭着也要学好!

原文地址:https://www.cnblogs.com/1121yjj/p/10868584.html