用gui界面编写一个两个数相加的java程序~求问怎么写,那个类主要测试应该在哪里?
package com.guard.test;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextPane;
public class Cal extends JFrame{//建Cal类继承JFrame
public Cal(){//cal构造方法
init();
}
public void init(){//初始化方法
this.setTitle("this is a test");
this.setBounds(100, 200, 200,200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setContentPane(new Panel());
setVisible(true);
}
class Panel extends JPanel{//Cal内部类panel继承JPanel
JTextPane text,text2;
JLabel label;
public Panel(){
setLayout(null);
final int BEGIN=20;
text=new JTextPane();
text.setBounds(50, BEGIN, 80, 20);
add(text);
JLabel labelj=new JLabel();
labelj.setBounds(50, BEGIN+20, 60, 30);
labelj.setText("+");
text2=new JTextPane();
text2.setBounds(50, BEGIN+50, 80, 20);
label=new JLabel("");
label.setBounds(50,BEGIN+100,80,30);
JButton button=new JButton();
button.setBounds(50, BEGIN+70, 50, 30);
button.setText("=");
add(button);
add(label);
add(text2);
add(labelj);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String str=text.getText();
String str2=text2.getText();
double a=Double.parseDouble(str);
double b=Double.parseDouble(str2);
double c=a+b;
label.setText(String.valueOf(c));
}
});
}
}
public static void main(String[] args){
new Cal();
}
}
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String str=text.getText();
String str2=text2.getText();
double a=Double.parseDouble(str);
double b=Double.parseDouble(str2);
double c=a+b;
label.setText(String.valueOf(c));
}
});
文中的这段就是实现加法并显示结果的功能。
广告 您可能关注的内容 |