Java基础题目
描述:定义一个矩形类(Rect) , 类中有长(length) 、宽(wide)成员,求该矩形的周长、面积并输出的方法,在类中定义构造函数初识化长、宽成员;定义测试类(TestRect),在该类中定义矩形类对象,通过该对象调用求周长和面积的方法。
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()+""); } } }