问题描述
我们被要求做一个简单的图形用户界面的计算器,我用的getSource()来检测按钮,导致这就是他们教给我们。它的工作原理通过键入第一和第二值,则选择操作,它的工作。但是,我犯了一个错误,因为他们希望我们做的是这些数字也应该是按键,就像一个真正的计算器。所以我如何得到使用的getSource()每个按钮的价值?就像当我preSS键1和2是等于3香港专业教育学院做什么继承人
进口java.awt中的*。
java.awt.event中导入*。公共类SimpleCalculator实现的ActionListener
{
//容器
私人帧F;
私人面板P1,P2,P3,P4; // 组件
私人标签L1,L2,L3;
私人文本字段TF1,TF2,TF3;
私人按钮BADD,bSub,bMul,BDIV,bClear; 公共SimpleCalculator()
{
F =新的帧(我的第一个GUI应用程序); P1 =新面板();
P2 =新面板();
P3 =新面板();
P4 =新面板(); L1 =新标签(第一);
L2 =新标签(二:);
L3 =新标签(结果:); TF1 =文本字段新(15);
TF2 =新的TextField(15);
TF3 =新的TextField(15); BADD =新按钮(+);
bSub =新按钮( - );
bMul =新按钮(*);
BDIV =新按钮(/);
bClear =新按钮(C);
}
公共无效launchFrame()
{
//小组使用默认的布局管理器(FlowLayout中)
p1.add(L1);
p1.add(TF1); p2.add(12);
p2.add(TF2); p3.add(13);
p3.add(TF3); p4.add(BADD);
p4.add(bSub);
p4.add(bMul);
p4.add(BDIV);
p4.add(bClear); //改变框架的布局管理器,
//使用网格布局(4,1)
f.setLayout(新的GridLayout(4,1)); f.add(P1);
f.add(P2);
f.add(P3);
f.add(P4); f.pack();
f.setVisible(真); //注册事件处理程序
bAdd.addActionListener(本);
bSub.addActionListener(本);
bMul.addActionListener(本);
bDiv.addActionListener(本);
bClear.addActionListener(本); f.addWindowListener(新MyCloseButtonHandler());
}
//重写actionPerformed方法
公共无效的actionPerformed(ActionEvent的AE)
{
对象源= ae.getSource();
双NUM1,NUM2,结果= 0.0; 如果(tf1.getText()= NULL和放大器;!&安培;!tf2.getText()= NULL)
{
NUM1 = Double.parseDouble(tf1.getText());
NUM2 = Double.parseDouble(tf2.getText()); 如果(来源== BADD)
结果= NUM1 + NUM2;
否则,如果(来源== bSub)
结果= NUM1 - NUM2;
否则,如果(来源== bMul)
结果= NUM1 * NUM2;
否则,如果(来源== BDIV)
结果= NUM1 / NUM2;
否则,如果(来源== bClear)
{
tf1.setText(0.0);
tf2.setText(0.0);
tf3.setText(0.0);
}
其他{}
// tf3.setText(新双(结果)的ToString());
tf3.setText(+结果);
}
}
私有类MyCloseButtonHandler WindowAdapter的扩展
{
公共无效的windowClosing(WindowEvent我们)
{
System.exit(0);
}
}
公共静态无效的主要(字符串ARGS [])
{
SimpleCalculator SC =新SimpleCalculator();
sc.launchFrame();
}
}
我会倾向于对这些数字每一个按钮,以及为操作数的每个按钮,添加文字是这样的输入/输出的文本字段。
也有一个按钮 =
。当 =
按钮被激活,调用的评估I / O文本字段的内容和结果写回吧。
例如
=
进口java.awt中的*。
java.awt.event中导入*。
进口的javax.swing *。
进口javax.swing.border.EmptyBorder中;
进口的java.util.ArrayList;//在Java 1.6的推出脚本包
进口javax.script.ScriptEngineManager;
进口javax.script.ScriptEngine中;
进口javax.script.ScriptException;类ScriptEngineCalculator实现的ActionListener,的KeyListener { 私人JTextField的IO;
私人的ScriptEngine引擎;
私人的ArrayList<&的JButton GT;控制;
私人JPanel的用户界面; ScriptEngineCalculator(){
initUI();
} 公众最终无效initUI(){
//获得对JS引擎的引用
发动机=新ScriptEngineManager()。
getEngineByExtension(JS); UI =新JPanel(新的BorderLayout(2,2));
控制=新的ArrayList<&的JButton GT;(); JPanel的文本=新JPanel(新网格布局(0,1,3,3));
ui.add(文字,BorderLayout.PAGE_START);
IO =新的JTextField(15);
字体字型= io.getFont();
字体= font.deriveFont(font.getSize()* 1.8F);
io.setFont(字体);
io.setHorizontalAlignment(SwingConstants.TRAILING);
io.setFocusable(假);
text.add(IO); JPanel的按钮=新JPanel(新网格布局(4,4,2,2));
ui.add(按钮,BorderLayout.CENTER);
的String []键值{=
7,8,9,/,
4,5,6,*,
1,2,3, - ,
0,。,C,+
}; 对于(字符串的keyValue:键值){
Add按钮(按钮,的keyValue);
} 一个JButton等于=的新的JButton(=);
configureButton(等于);
ui.add(等于,BorderLayout.LINE_END); ui.setBorder(新EmptyBorder(5,5,5,5));
} 公共JComponent中的getUI(){
返回UI;
} 公共无效Add按钮(容器C,字符串文本){
JButton的B =的新的JButton(文本);
configureButton(二);
c.add(二);
} 公共无效configureButton(JButton的B){
字体F = b.getFont();
b.setFont(f.deriveFont(f.getSize()* 1.5F));
b.addActionListener(本);
b.addKeyListener(本);
Controls.Add被(B);
} 公共无效calculateResult(){
尝试{
对象result = engine.eval(io.getText());
如果(结果== NULL){
io.setText(输出是'空');
}其他{
io.setText(result.toString());
}
}赶上(ScriptException SE){
io.setText(se.getMessage());
}
} @覆盖
公共无效的actionPerformed(ActionEvent的AE){
字符串命令= ae.getActionCommand();
如果(command.equals(C)){
io.setText();
}否则如果(command.equals(=)){
calculateResult();
}其他{
io.setText(io.getText()+命令);
}
} 私人的JButton getButton(字符串文本){
对于(JButton的按钮:控制){
字符串s = button.getText();
如果(text.endsWith(多个)
|| (s.equals(=)
&功放;&安培; (text.equals(等于)|| text.equals(回车)))){ 返回按钮;
}
}
返回null;
} / *启动 - 因为我讨厌老鼠。 * /
@覆盖
公共无效键pressed(KeyEvent的KE){
} @覆盖
公共无效调用keyReleased(KeyEvent的KE){
字符串s = KeyEvent.getKeyText(ke.getKey code());
JButton的B = getButton(S);
如果(B!= NULL){
b.requestFocusInWindow();
b.doClick();
}
} @覆盖
公共无效的keyTyped(KeyEvent的KE){
}
/ * END - 因为我讨厌老鼠。 * / 公共静态无效的主要(字串[] args){
SwingUtilities.invokeLater(Runnable的新(){
@覆盖
公共无效的run(){
ScriptEngineCalculator SC =新ScriptEngineCalculator();
JFrame的F =新的JFrame(Calculet);
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setContentPane(sc.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setLocationByPlatform(真);
f.setVisible(真);
}
});
}
}
We were asked to make a simple GUI calculator, I used getSource() to detect the buttons, cause that's what they taught us. It works by typing the 1st and 2nd value then choosing the operation, it worked. But I made a mistake, because what they want us to do is that the numbers should also be buttons, just like a real calculator. so how do i get the value of each button using getSource()? like when I press button 1 and 2 is equal to 3. heres what ive done
import java.awt.*;
import java.awt.event.*;
public class SimpleCalculator implements ActionListener
{
// containers
private Frame f;
private Panel p1, p2, p3, p4;
// components
private Label l1, l2, l3;
private TextField tf1, tf2, tf3;
private Button bAdd, bSub, bMul, bDiv, bClear;
public SimpleCalculator()
{
f = new Frame("My First GUI App");
p1 = new Panel();
p2 = new Panel();
p3 = new Panel();
p4 = new Panel();
l1 = new Label("First: ");
l2 = new Label("Second: ");
l3 = new Label("Result: ");
tf1 = new TextField(15);
tf2 = new TextField(15);
tf3 = new TextField(15);
bAdd = new Button("+");
bSub = new Button("-");
bMul = new Button("*");
bDiv = new Button("/");
bClear = new Button("C");
}
public void launchFrame()
{
// use default layout manager of the Panel (FlowLayout)
p1.add(l1);
p1.add(tf1);
p2.add(l2);
p2.add(tf2);
p3.add(l3);
p3.add(tf3);
p4.add(bAdd);
p4.add(bSub);
p4.add(bMul);
p4.add(bDiv);
p4.add(bClear);
// change the layout manager of the Frame,
// use GridLayout(4, 1)
f.setLayout(new GridLayout(4, 1));
f.add(p1);
f.add(p2);
f.add(p3);
f.add(p4);
f.pack();
f.setVisible(true);
// register event handlers
bAdd.addActionListener(this);
bSub.addActionListener(this);
bMul.addActionListener(this);
bDiv.addActionListener(this);
bClear.addActionListener(this);
f.addWindowListener(new MyCloseButtonHandler());
}
// override the actionPerformed method
public void actionPerformed(ActionEvent ae)
{
Object source = ae.getSource();
double num1, num2, result = 0.0;
if (tf1.getText() != null && tf2.getText() != null)
{
num1 = Double.parseDouble(tf1.getText());
num2 = Double.parseDouble(tf2.getText());
if (source == bAdd)
result = num1 + num2;
else if (source == bSub)
result = num1 - num2;
else if (source == bMul)
result = num1 * num2;
else if (source == bDiv)
result = num1 / num2;
else if (source == bClear)
{
tf1.setText("0.0");
tf2.setText("0.0");
tf3.setText("0.0");
}
else {}
// tf3.setText(new Double(result).toString());
tf3.setText("" + result);
}
}
private class MyCloseButtonHandler extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
public static void main(String args[])
{
SimpleCalculator sc = new SimpleCalculator();
sc.launchFrame();
}
}
I would tend to have each button for the numbers, as well as each button for operands, add text to a text field that is the 'Input/Output'.
Also have a button =
. When the =
button is activated, call the javax.script.ScriptEngine
to evaluate the content of the I/O text field and write the result back to it.
E.G.
=
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.util.ArrayList;
// script package introduced in Java 1.6
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
class ScriptEngineCalculator implements ActionListener, KeyListener {
private JTextField io;
private ScriptEngine engine;
private ArrayList<JButton> controls;
private JPanel ui;
ScriptEngineCalculator() {
initUI();
}
public final void initUI() {
// obtain a reference to the JS engine
engine = new ScriptEngineManager().
getEngineByExtension("js");
ui = new JPanel(new BorderLayout(2, 2));
controls = new ArrayList<JButton>();
JPanel text = new JPanel(new GridLayout(0, 1, 3, 3));
ui.add(text, BorderLayout.PAGE_START);
io = new JTextField(15);
Font font = io.getFont();
font = font.deriveFont(font.getSize() * 1.8f);
io.setFont(font);
io.setHorizontalAlignment(SwingConstants.TRAILING);
io.setFocusable(false);
text.add(io);
JPanel buttons = new JPanel(new GridLayout(4, 4, 2, 2));
ui.add(buttons, BorderLayout.CENTER);
String[] keyValues = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "C", "+"
};
for (String keyValue : keyValues) {
addButton(buttons, keyValue);
}
JButton equals = new JButton("=");
configureButton(equals);
ui.add(equals, BorderLayout.LINE_END);
ui.setBorder(new EmptyBorder(5, 5, 5, 5));
}
public JComponent getUI() {
return ui;
}
public void addButton(Container c, String text) {
JButton b = new JButton(text);
configureButton(b);
c.add(b);
}
public void configureButton(JButton b) {
Font f = b.getFont();
b.setFont(f.deriveFont(f.getSize() * 1.5f));
b.addActionListener(this);
b.addKeyListener(this);
controls.add(b);
}
public void calculateResult() {
try {
Object result = engine.eval(io.getText());
if (result == null) {
io.setText("Output was 'null'");
} else {
io.setText(result.toString());
}
} catch (ScriptException se) {
io.setText(se.getMessage());
}
}
@Override
public void actionPerformed(ActionEvent ae) {
String command = ae.getActionCommand();
if (command.equals("C")) {
io.setText("");
} else if (command.equals("=")) {
calculateResult();
} else {
io.setText(io.getText() + command);
}
}
private JButton getButton(String text) {
for (JButton button : controls) {
String s = button.getText();
if (text.endsWith(s)
|| (s.equals("=")
&& (text.equals("Equals") || text.equals("Enter")))) {
return button;
}
}
return null;
}
/* START - Because I hate mice. */
@Override
public void keyPressed(KeyEvent ke) {
}
@Override
public void keyReleased(KeyEvent ke) {
String s = KeyEvent.getKeyText(ke.getKeyCode());
JButton b = getButton(s);
if (b != null) {
b.requestFocusInWindow();
b.doClick();
}
}
@Override
public void keyTyped(KeyEvent ke) {
}
/* END - Because I hate mice. */
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
ScriptEngineCalculator sc = new ScriptEngineCalculator();
JFrame f = new JFrame("Calculet");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setContentPane(sc.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setLocationByPlatform(true);
f.setVisible(true);
}
});
}
}
这篇关于如何找到在AWT按钮源(计算器做作业)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!