Java按钮监听
这是所有的代码packagehellowworld;importjava.util.Scanner;importjavax.swing.JFrame;importjava...
这是所有的代码package hellowworld;import java.util.Scanner;import javax.swing.JFrame;import java.awt.Button;import java.awt.Label;import java.awt.TextField;import java.awt.Frame;import java.awt.Panel;import java.awt.Color;import java.awt.*;public class 圆的面积{ public static void main(String args[]){ /*Scanner sc = new Scanner(System.in); double pi=3.14,s; double r; r=sc.nextDouble(); s=pi*r*r; System.out.println("s等于"+s);*/ Frame f = new Frame("圆的面积"); Panel p = new Panel(); TextField t = new TextField(); Button b = new Button("确定"); Label a = new Label("请在此输入半径"); f.add(a); f.add(t); f.add(b); f.add(p); f.setVisible(true); p.setBackground(Color.black); a.setBackground(Color.yellow); t.setBackground(Color.white); b.setBackground(Color.cyan); f.setSize(300,300); a.setBounds(105,45,90,25); t.setBounds(100,80,100,25); b.setBounds(111,120,80,40); f.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent e){ System.exit(0);}}); } }如何在点击确定按钮时在面板上显示圆的面积,求神人完整解答
(前面我把包和类也复制了) 展开
(前面我把包和类也复制了) 展开
1个回答
推荐于2016-01-09
展开全部
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.math.BigDecimal;
import java.util.Scanner;
import javax.swing.JFrame;
import java.awt.Button;
import java.awt.Label;
import java.awt.TextField;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.Color;
import java.awt.*;
public class PanelTest{
public static void main(String args[]) {
/*Scanner sc = new Scanner(System.in); double pi=3.14,s; double r; r=sc.nextDouble(); s=pi*r*r; System.out.println("s等于"+s);*/
EventQueue.invokeLater(new Runnable() {
public void run() {
CricleFrame frame = new CricleFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class CricleFrame extends JFrame{
Panel p = new Panel();
TextField t = new TextField();
Button b = new Button("确定");
Label a = new Label("请在此输入半径");
TextField result = new TextField();
public CricleFrame(){
add(a);
add(t);
add(b);
add(result);
add(p);
setVisible(true);
p.setBackground(Color.black);
a.setBackground(Color.yellow);
t.setBackground(Color.white);
result.setBackground(Color.white);
b.setBackground(Color.cyan);
setSize(300, 300);
setTitle("圆的面积");
a.setBounds(105, 45, 90, 25);
t.setBounds(100, 80, 100, 25);
result.setBounds(100, 180, 100, 25);
b.setBounds(111, 120, 80, 40);
b.addActionListener(new ActionListener() { //按钮点击事件监听
public void actionPerformed(ActionEvent event) {
Double r=0.0;
try{
r = Double.parseDouble(t.getText());
}catch (Exception e){
System.out.println(e.getMessage());
}
BigDecimal tmp = new BigDecimal(r * r * Math.PI);
Double area = tmp.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue(); //保留2位小数
result.setText(""+area);
}
});
}
}
在你的基础上改了一下,界面什么的没有改
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询