编程论坛
注册
登录
编程论坛
→
JAVA论坛
Java基础题目
cjj123
发布于 2020-03-08 15:44, 2860 次点击
描述:定义一个矩形类(Rect) , 类中有长(length) 、宽(wide)成员,求该矩形的周长、面积并输出的方法,在类中定义构造函数初识化长、宽成员;定义测试类(TestRect),在该类中定义矩形类对象,通过该对象调用求周长和面积的方法。
4 回复
#2
林月儿
2020-03-08 15:52
作业贴?
#3
cjj123
2020-03-08 16:11
回复 2楼 林月儿
是滴哦,大学生一枚,这题不会来请教诸位的,如果不给发我可以删了。
#4
林月儿
2020-03-08 18:22
程序代码:
package
com.test.day0308;
import
java.awt.event.KeyAdapter;
import
java.awt.event.KeyEvent;
import
javax.swing.JFrame;
import
javax.swing.JLabel;
import
javax.swing.JTextField;
class
Rect {
int
length;
int
width;
public
Rect(
int
length,
int
width) {
this
.length = length;
this
.width = width;
}
public
int
getLen() {
return
2 * (width + length);
}
public
int
getArea() {
return
length * width;
}
}
public
class
TestRect
extends
KeyAdapter {
private
static
JTextField[] txts =
new
JTextField[4];
private
void
init() {
JFrame jframe =
new
JFrame();
jframe.setBounds(400, 400, 240, 140);
jframe.setVisible(
true
);
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setLayout(
null
);
jframe.setResizable(
false
);
String[] lblStrs = {"宽:", "高:", "周长:", "面积:"};
for
(
int
i = 0; i < lblStrs.length; i++) {
JLabel lbl =
new
JLabel(lblStrs[i]);
lbl.setBounds(20, 20 * (i + 1), 40, 18);
jframe.add(lbl);
txts[i] =
new
JTextField();
jframe.add(txts[i]);
txts[i].setBounds(80, 20 * (i + 1), 100, 20);
if
(i >= 2) {
txts[i].setEditable(
false
);
}
else
{
txts[i].addKeyListener(TestRect.
this
);
}
}
jframe.repaint();
}
public
static
void
main(String[] args) {
new
TestRect().init();
}
@Override
public
void
keyReleased(KeyEvent e) {
int
width = -1;
int
height = -1;
if
(txts[0].getText().matches("[0-9]+")) {
width = Integer.valueOf(txts[0].getText());
}
if
(txts[1].getText().matches("[0-9]+")) {
height = Integer.valueOf(txts[1].getText());
}
txts[2].setText("?");
txts[3].setText("?");
if
(width >= 0 && height >= 0) {
Rect rect =
new
Rect(height, width);
txts[2].setText(rect.getLen()+"");
txts[3].setText(rect.getArea()+"");
}
}
}
#5
cjj123
2020-03-08 19:04
回复 4楼 林月儿
谢谢大佬
1