导航:首页 > 编程语言 > javaswing计算器

javaswing计算器

发布时间:2022-05-05 12:18:39

⑴ 怎样用java中的swing编写一个计算器

貌似挺简单的,就用swing会写窗口就行了。
几个类:JFrame,JPanel,JLabel,JButton.....
我只记得这些了,逻辑并不复杂。但是要写一个完整的计算器还是需要点功底的,比如科学计算器。

⑵ java swing 计算器代码纠错

兄弟 别怪我太坦白,你这个程序写的真的很一般,我从来没见过计算器里面还有用JButton来显示数据的
还有你的calculator传进来的lastCommand全部都是数字;和那些什么+ - / 什么的比较时没有一个会符合条件进入计算的
所以你的加减乘除什么的都不会运算数据当然都没有变化的啊

⑶ JAVA用Swing怎么做计算器

进行除法运算 附上代码

<table border="0" style="border-collapse:collapse; line-height:40px;" >

<tr>

<td>第一个数:</td>

<td><input type="text" id="first"/></td>

</tr>

<tr>

<td>第二个数:</td>

<td><input type="text" id="twice"/></td>

</tr>

<tr>

<td colspan="2" >

&nbsp;

<button onclick="add()">+</button>

&nbsp;

<button onclick="subtract()">-</button>

&nbsp;

<button onclick="ride()">*</button>

&nbsp;

<button onclick="devide()">/</button>

</td>

⑷ Java 用swing实现简单计算器

importjava.awt.*;
importjava.awt.event.*;

importjavax.swing.*;publicclassCalculator
{
publicstaticvoidmain(Stringargs[])
{
newMainFrame("Calculator").setVisible(true);
}
}

classMainFrameextendsJFrame
{
/**
*
*/
=-8354514836554448949L;

MainFrame(Stringwinname)
{
super(winname);
CalPanelcp=newCalPanel();
this.add(cp);
this.pack();
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

}

classCalPanelextendsJPanel
{
/**
*
*/
=5927981350284503795L;
JLabeldisplay=null;
JPanelpanel=null;
CalculatorNumnum=null;
CalculatorOpop=null;
doubleresult;
Stringcommand;
booleanstart;

publicCalPanel()
{
result=0;
command="=";
start=true;
display=newJLabel();
panel=newJPanel();
num=newCalculatorNum();
op=newCalculatorOp();
display.setText("0");
display.setFont(newFont("TimesNewRoman",Font.BOLD,30));
display.setHorizontalAlignment(SwingConstants.RIGHT);
this.setLayout(newBorderLayout());
add(display,BorderLayout.NORTH);
panel.setLayout(newGridLayout(4,4));
addButton("7",num);
addButton("8",num);
addButton("9",num);
addButton("+",op);
addButton("4",num);
addButton("5",num);
addButton("6",num);
addButton("-",op);
addButton("1",num);
addButton("2",num);
addButton("3",num);
addButton("*",op);
addButton("0",num);
addButton(".",num);
addButton("=",op);
addButton("/",op);
add(panel,BorderLayout.CENTER);
}

privatevoidaddButton(Stringname,ActionListeneral)
{
JButtonjb=newJButton(name);
jb.addActionListener(al);
jb.setFont(newFont("TimesNewRoman",Font.BOLD,40));
panel.add(jb);
}


{
publicvoidactionPerformed(ActionEvente)
{
Stringin=e.getActionCommand();
if(start)
{
display.setText("");
start=false;
}
display.setText(display.getText()+in);
}

}


{
publicvoidactionPerformed(ActionEvente)
{
Stringco=e.getActionCommand();
if(start)
{
if(co=="-")
{
display.setText(co);
start=false;
}
else
{
command=co;
start=true;
}
}
else
{
Calc(Double.parseDouble(display.getText()));
command=co;
start=true;
}
}

privatevoidCalc(doubled)
{
switch(command)
{
case"+":
result+=d;
break;
case"-":
result-=d;
break;
case"*":
result*=d;
break;
case"/":
result/=d;
break;
case"=":
result=d;
break;
default:
break;
}
display.setText(result+"");
}

}
}

⑸ JAVA_用Swing做一个计算器



importjava.awt.*;
importjava.awt.event.*;
importjavax.swing.*;

{

=1L;
privateJTextFieldtxtResult;
privateJButtonbtnZero,btnOne,btnTwo,btnThree,btnFour,btnFive,
btnSix,btnSeven,btnEight,btnNine,btnPlus,btnMinus,btnTimes,
btnDivided,btnEqual,btnPoint,btnC,btnCE,btnSqrt,btnPlusMinus;
intz;
doublex,y;
StringBufferstr;

publicCalculator(){
super("计算器");
this.setSize(311,231);
this.setLocation(300,300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

this.setLayout(newGridLayout(1,1));//网格布局
JPanelpanel=newJPanel(newGridLayout(6,1));//面板网格布局6行1列
this.add(panel);

txtResult=newJTextField("0");
ColorBackColor=newColor(255,255,255);
ColorForeColor=newColor(0,0,0);
txtResult.setBackground(BackColor);
txtResult.setForeground(ForeColor);

panel.add(txtResult);
txtResult.setHorizontalAlignment(JTextField.RIGHT);
txtResult.setEnabled(false);
//text.setEnabled(true);

JPanelpanel_1=newJPanel(newGridLayout(1,4));
panel.add(panel_1);

btnSqrt=newJButton("sqrt");
panel_1.add(btnSqrt);
btnSqrt.addActionListener(this);
btnPlusMinus=newJButton("+/-");
panel_1.add(btnPlusMinus);
btnPlusMinus.addActionListener(this);
btnCE=newJButton("CE");
panel_1.add(btnCE);
btnCE.addActionListener(this);
btnC=newJButton("C");
panel_1.add(btnC);
btnC.addActionListener(this);

JPanelpanel_2=newJPanel(newGridLayout(1,4));
panel.add(panel_2);

btnSeven=newJButton("7");
panel_2.add(btnSeven);
btnSeven.addActionListener(this);
btnEight=newJButton("8");
panel_2.add(btnEight);
btnEight.addActionListener(this);
btnNine=newJButton("9");
panel_2.add(btnNine);
btnNine.addActionListener(this);
btnDivided=newJButton("/");
panel_2.add(btnDivided);
btnDivided.addActionListener(this);

JPanelpanel_3=newJPanel(newGridLayout(1,4));
panel.add(panel_3);

btnFour=newJButton("4");
panel_3.add(btnFour);
btnFour.addActionListener(this);
btnFive=newJButton("5");
panel_3.add(btnFive);
btnFive.addActionListener(this);
btnSix=newJButton("6");
panel_3.add(btnSix);
btnSix.addActionListener(this);
btnTimes=newJButton("*");
panel_3.add(btnTimes);
btnTimes.addActionListener(this);

JPanelpanel_4=newJPanel(newGridLayout(1,4));
panel.add(panel_4);

btnOne=newJButton("1");
panel_4.add(btnOne);
btnOne.addActionListener(this);
btnTwo=newJButton("2");
panel_4.add(btnTwo);
btnTwo.addActionListener(this);
btnThree=newJButton("3");
panel_4.add(btnThree);
btnThree.addActionListener(this);
btnMinus=newJButton("-");
panel_4.add(btnMinus);
btnMinus.addActionListener(this);

JPanelpanel_5=newJPanel(newGridLayout(1,4));
panel.add(panel_5);

btnZero=newJButton("0");
panel_5.add(btnZero);
btnZero.addActionListener(this);
btnPoint=newJButton(".");
panel_5.add(btnPoint);
btnPoint.addActionListener(this);
btnEqual=newJButton("=");
panel_5.add(btnEqual);
btnEqual.addActionListener(this);
btnPlus=newJButton("+");
panel_5.add(btnPlus);
btnPlus.addActionListener(this);

str=newStringBuffer();

this.setVisible(true);

}

publicvoidwindowClosing(WindowEventa){
System.exit(0);
}

publicvoidactionPerformed(ActionEvente){

try{
if(e.getSource()==btnC){
txtResult.setText("0");
str.setLength(0);
}elseif(e.getSource()==btnCE){
txtResult.setText("0.");
str.setLength(0);
}elseif(e.getSource()==btnPlusMinus){
x=Double.parseDouble(txtResult.getText().trim());
txtResult.setText(""+(-x));
}

elseif(e.getSource()==btnPlus){
x=Double.parseDouble(txtResult.getText().trim());
str.setLength(0);
y=0d;
z=1;
}elseif(e.getSource()==btnMinus){
x=Double.parseDouble(txtResult.getText().trim());
str.setLength(0);
y=0d;
z=2;
}elseif(e.getSource()==btnTimes){
x=Double.parseDouble(txtResult.getText().trim());
str.setLength(0);
y=0d;
z=3;
}elseif(e.getSource()==btnDivided){
x=Double.parseDouble(txtResult.getText().trim());
str.setLength(0);
y=0d;
z=4;
}elseif(e.getSource()==btnEqual){
str.setLength(0);
switch(z){
case1:
txtResult.setText(""+(x+y));
break;
case2:
txtResult.setText(""+(x-y));
break;
case3:
txtResult.setText(""+(x*y));
break;
case4:
txtResult.setText(""+(x/y));
break;
}
}

elseif(e.getSource()==btnPoint){
if(txtResult.getText().trim().indexOf('.')!=-1)//判断字符串中是否已经包含了小数点
{

}else//如果没数点有小
{
if(txtResult.getText().trim().equals("0"))//如果初时显示为0
{
str.setLength(0);
txtResult.setText((str.append("0"
+e.getActionCommand())).toString());
}elseif(txtResult.getText().trim().equals(""))//如果初时显示为空则不做任何操作
{
}else{
txtResult.setText(str.append(e.getActionCommand())
.toString());
}
}

y=0d;
}

elseif(e.getSource()==btnSqrt)//求平方根
{
x=Double.parseDouble(txtResult.getText().trim());
txtResult.setText("数字格式异常");
if(x<0)
txtResult.setText("负数没有平方根");
else
txtResult.setText(""+Math.sqrt(x));
str.setLength(0);
y=0d;
}

elseif(e.getSource()==btnZero)//如果选择的是"0"这个数字键
{
if(txtResult.getText().trim().equals("0"))//如果显示屏显示的为零不做操作
{
}else{
txtResult.setText(str.append(e.getActionCommand())
.toString());
y=Double.parseDouble(txtResult.getText().trim());
}
}

else//其他的数字键
{
txtResult.setText(str.append(e.getActionCommand()).toString());
y=Double.parseDouble(txtResult.getText().trim());
}
}catch(NumberFormatExceptionae){
txtResult.setText("数字格式异常");
}catch(){
txtResult.setText("字符串索引越界");
}

}

publicstaticvoidmain(Stringarg[]){
try{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}catch(Exceptione){
e.printStackTrace();
}
newCalculator();
}

}

⑹ java swing 计算器 代码纠错 3+3还是=3.

private class CommandAction implements ActionListener {

public void actionPerformed(ActionEvent event) {
String command = display.getActionCommand();
.......
}
}
改成
private class CommandAction implements ActionListener {

public void actionPerformed(ActionEvent event) {
//should have been event instead of display
String command = event.getActionCommand();
.......
}
}

⑺ 要求使用Swing,编程一个计算器,需要具备计算器的基本功能,要求出现组合框

有一个简单的,起步的时候做的,简单点,看看能用吧!

package com.java.concource;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;

@SuppressWarnings("serial")
public class TestCalculator extends JFrame implements ActionListener{
private JButton[] jb = new JButton[19];
private JPanel jp0 = null;
private JTextField tf = null;
private StringBuffer sb = null;
private StringBuffer sB = null;
private MyStack numberStack = null;
private MyStack operStack = null;
private LinkedList<String> ll = null;
private LinkedList<String> numberList = null;
private LinkedList<String> operList = null;
private float str = 0;

public TestCalculator() {
super("计算器");
jp0 = new JPanel();
jp0.setLayout(new GridLayout(5,3,10,10));

sb = new StringBuffer("");
sB = new StringBuffer("");

for(int i=0;i<10;i++){
jb[i] = new JButton(String.valueOf(i));
}
jb[10] = new JButton("+");
jb[11] = new JButton("-");
jb[12] = new JButton("*");
jb[13] = new JButton("/");
jb[14] = new JButton("=");
jb[15] = new JButton(".");
jb[16] = new JButton("C");
jb[17] = new JButton("Del");
jb[18] = new JButton("Esc");

this.setLayout(new BorderLayout());

for(JButton o : jb){
o.addActionListener(this);
jp0.add(o);
}
this.add(jp0,BorderLayout.CENTER);

tf = new JTextField();
tf.setBackground(Color.PINK);
tf.setText("");
tf.setEditable(false);
this.add(tf,BorderLayout.SOUTH);

this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});

this.setSize(300, 300);
this.setVisible(true);
this.validate();
}

public void actionPerformed(ActionEvent e){
if(sb.toString().indexOf("Error")!=-1){
sb = new StringBuffer("");
tf.setText(sb.toString());
}

if(sb.toString().indexOf("=")!=-1){
sb = new StringBuffer("");
sb.append(String.valueOf(str));

tf.setText(sb.toString());
}

if(e.getSource()==jb[17]){
if(sb.toString()==null)
tf.setText("");
sb.deleteCharAt(sb.length()-1);
tf.setText(sb.toString());
}
else if(e.getSource()==jb[18]){
System.exit(0);
}
else if(e.getSource()==jb[16]){
sb = new StringBuffer("");
tf.setText("");

numberList = null;
}
else if(e.getSource()!=jb[14]){
JButton j = (JButton)e.getSource();
String str = j.getText();
sb.append(str);
tf.setText(sb.toString());
}
else{
char[] op = {'+','-','*','/','.'};
for(char c : op){
if(sb.toString().startsWith(String.valueOf(c)) || sb.toString().endsWith(String.valueOf(c))){
sb.append(" " + "Error:格式错误!");
tf.setText(sb.toString());
return;
}
}
String[] st = {"+-","-+","+*","*+","+/","/+","-*","*-","-/","/-","*/","/*","++","--","**","//","..",".+",".*",".-","./","+.","-.","*.","/."};
for(String o : st){
if(sb.toString().indexOf(o)!=-1){
sb.append(" " + "Error:格式错误!");
tf.setText(sb.toString());
return;
}
}

numberStack = new MyStack();
operStack = new MyStack();
ll = new LinkedList<String>();

sb.append("=");
char[] number = {'0','1','2','3','4','5','6','7','8','9','.'};
char[] oper = {'+','-','*','/','='};
char[] c = sb.toString().toCharArray();
@SuppressWarnings("unused")
boolean flag = false;

for(int i=0;i<c.length;i++){
int index = numberStack.size();

for(char o : number){
if(c[i]==o){
sB.append(String.valueOf(o));
break;
}
}
if(numberStack.size()>index)
continue;

for(char o : oper){
if(c[i]==o){
flag = true;
ll.addLast(sB.toString());
sB = new StringBuffer("");
ll.addLast(String.valueOf(o));
break;
}
}
}

while(ll.size()!=0){
String str = ll.removeFirst();
if(str.equals("+") || str.equals("-") || str.equals("*") || str.equals("/")){
if(str.equals("+")){
operStack.push(str);
}
else if(str.equals("-")){
operStack.push(str);
}
else if(str.equals("*")){
double var0 = Double.valueOf(ll.removeFirst());
double var1 = Double.valueOf(numberStack.pop());
double var = var0*var1;
numberStack.push(String.valueOf(var));
}
else if(str.equals("/")){
double var0 = Double.valueOf(ll.removeFirst());
double var1 = Double.valueOf(numberStack.pop());
double var = var1/var0;
numberStack.push(String.valueOf(var));
}
}
else{
numberStack.push(str);
}
}

numberList = numberStack.getString();
operList = operStack.getString();

while(operList.size()!=0){
double var0 = Double.valueOf(numberList.removeFirst());
double var1 = Double.valueOf(numberList.removeFirst());
double var = 0;
String opera = operList.removeFirst();

if(opera.equals("+")){
var = var0+var1;
}
else{
var = var0-var1;
}
numberList.addFirst(String.valueOf(var));
}

str = new Double(numberList.removeFirst()).floatValue();
sb.append(str);
tf.setText(sb.toString());
operList = null;
numberList = null;
numberStack = null;
operStack = null;
ll = null;
return;
}
}

public static void main(String[] args) {
new TestCalculator();
}
}

用的是JDK1.6

⑻ 请高手做一个java编程题,做一个计算器(要求可以计算),用swing做,要求有JFrame、JButton。要原创哦!

importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjavax.swing.JButton;
importjavax.swing.JFrame;
importjavax.swing.JPanel;
importjavax.swing.JTextField;
importjavax.swing.SwingConstants;
importjavax.swing.border.EmptyBorder;
@SuppressWarnings("serial")
/*加减乘除计算小程序,哥们绝对原创,给你了。浪费我半个小时,有啥问题在问,继续看电影*/
publicclassJiSuextendsJFrame{
privateintli=0;
privateStrings1="",s2="",s3="";//s2+s3得到最后结果
privateJPanelcp1;
privateJTextFieldt1;//文本框
privateJButtonbr[][]=newJButton[4][4];//二维数组建立按钮
privatechartext[][]={{'1','2','3','/'},{'4','5','6','*'},{'7','8','9','-'},{'0','=','.','+'}};//二维数组为按钮赋值和做+-×÷运算判断的字符值
privatebooleanip=false;
//main执行
publicstaticvoidmain(String[]args){
JiSuframe=newJiSu();
frame.setTitle("计算器");
frame.setVisible(true);
}
publicJiSu(){

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100,100,305,243);
cp1=newJPanel();
cp1.setBorder(newEmptyBorder(5,5,5,5));
setContentPane(cp1);
cp1.setLayout(null);
//文本框
t1=newJTextField("");
t1.setHorizontalAlignment(SwingConstants.RIGHT);
t1.setBounds(38,20,168,21);
cp1.add(t1);
t1.setColumns(10);
//清空
JButtonbt=newJButton("C");
bt.addActionListener(newActionListener(){
publicvoidactionPerformed(ActionEventarg0){
t1.setText("");
s1=s2=s3="";
}
});
bt.setBounds(213,19,46,23);
cp1.add(bt);
//4X4事件按钮
intx,y=65;//坐标
for(inti=0;i<br.length;i++){
x=35;
for(intj=0;j<br[i].length;j++){
br[i][j]=newJButton(text[i][j]+"");
br[i][j].setBounds(x,y,45,23);
br[i][j].addActionListener(newM());
cp1.add(br[i][j]);
x=x+60;
}
y=y+33;
}
}//文本框添加数字并判断
privatevoidset(inti,intj){

if(t1.getText().equals("")&&getText(i,j)=='.'){
s1="0";
}
s1=s1+getText(i,j);
t1.setText(s1);
}
//[][]的麻烦,直接传递参数获取值
privatechargetText(inti,intj){
returntext[i][j];
}
//事件监听器
{

@Override
publicvoidactionPerformed(ActionEvente){
//循环按钮二维数组得到事件监听
for(inti=0;i<br.length;i++){
for(intj=0;j<br[i].length;j++){
s1=t1.getText();
if(e.getSource().equals(br[i][j])){
if(ip){t1.setText("");s1="";ip=false;}
//switch语句判断
switch(getText(i,j)){
case'+':
count();
li=1;
s3=t1.getText();t1.setText("");
break;
case'-':
li=2;
s3=t1.getText();t1.setText("");
break;
case'*':
li=3;
s3=t1.getText();t1.setText("");
break;
case'/':
li=4;
s3=t1.getText();t1.setText("");
break;
case'=':
s2=t1.getText();
count();
break;
case'.':
if(!t1.getText().contains(".")){
set(i,j);
}
break;
default:
set(i,j);
break;
}//swich结束

}//if事件选择结束
}

}

}
//最终计算方法
privatevoidcount(){
doublei=0,j=0;

if(s3.equals("")){
i=0;
}
elseif(s2.equals("")){
j=0;

}else{
i=Double.parseDouble(s3);//字符串转换成double类型
j=Double.parseDouble(s2);
}
if(li==1)
i=i+j;t1.setText(i+"");
if(li==2)
i=i-j;t1.setText(i+"");
if(li==3)
i=i*j;t1.setText(i+"");
if(li==4)
i=i/j;t1.setText(i+"");
ip=true;//当ip=true传入事件中,当点击任意按钮,开始新的计算
}//计算结尾

}//监听类块结尾}//程序结尾

⑼ java swing 计算器 键盘 表达式求值

目标:初始化窗体
代码:如下
----------------
public class View extends JFrame{

public View(){
this.setTitle("计算器");//设置标题
this.setResizable(false);//不可改变大小
this.setLocationRelativeTo(null);//居中显示
this.setSize(228, 324);//窗体大小,可以使用FastStone Capture的屏幕尺量一下win计算器的大小
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//默认关闭操作
}

public static void main(String[] args) {
new View().setVisible(true);
}
}

目标:设置菜单
代码:如下
----------------
/**
* 创建初始化菜单方法(别忘记在构造函数里调用)
*/
private void initMenu(){
jmb = new JMenuBar();//创建菜单条
jm_view = new JMenu("查看(V)");//查看菜单
jm_view.setMnemonic('V');//设置热键
jm_edit = new JMenu("编辑(E)");//编辑菜单
jm_edit.setMnemonic('E');
jm_help = new JMenu("帮助(H)");//帮助菜单
jm_help.setMnemonic('H');

jmb.add(jm_view);
jmb.add(jm_edit);
jmb.add(jm_help);

this.setJMenuBar(jmb);//将菜单条加入窗体中
}

目标:仿结果显示框
代码:如下
----------------
/**
* 创建内容区域初始化方法
*/
private void initContent(){
//整个窗口区域
JPanel jp = new JPanel();
jp.setLayout(null);//设置空布局以便绝对定位
//显示框区域
JPanel jptmp = new JPanel(){
//获取背景图片,使用截图工具从win计算器显示框中截取2像素宽度作为背景
Image bg = new ImageIcon("imgs/bg.png").getImage();
/**
* 填充结果显示区域的背景
*/
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
//x轴平铺满面板
for(int i = 0;i<this.getWidth();i+=bg.getWidth(this)){
g.drawImage(bg, i, 0, this);//绘制背景图片
}
}
};

//设置显示框上方小字体
Font font_lab = new Font("arial", Font.BOLD, 22);
jla_input = new JLabel();
jla_input.setText("0");
//设置字体右对齐
jla_input.setHorizontalAlignment(JLabel.RIGHT);
jla_input.setFont(font_lab);
//设置显示框中计算结果的字体
font_lab = new Font("arial", Font.BOLD, 10);
jla_show = new JLabel();
jla_show.setText("sqrt");
//设置字体右对齐
jla_show.setHorizontalAlignment(JLabel.RIGHT);
jla_show.setFont(font_lab);

//设置显示框区域的位置的大小
jptmp.setBounds(14, 15, 190, 50);
jptmp.setLayout(new BorderLayout());
jptmp.add(jla_show,BorderLayout.NORTH);
jptmp.add(jla_input,BorderLayout.CENTER);
//设置边框
jptmp.setBorder(BorderFactory.createLineBorder(new Color(142,156,173)));
jp.add(jptmp);
this.setLayout(new BorderLayout());
this.add(jp,BorderLayout.CENTER);
}

目标:绘制其他按钮
代码:如下
----------------
①设置字符枚举类
public enum Operator{
//用于swith判断,待用
mC,mR,mS,mAdd,mSubtract,//mc,mr,ms,m+,m-
clBack,clError,clClear,operNegation,operSqrt,//<-,ce,c,-/+,开平方
n7,n8,n9,operDivide,operPer,// /,%,
n4,n5,n6,operMultiply,operReciproc,//*,倒数
n1,n2,n3,operSubtract,operEqu,//-,=
n0,operDot,operAdd;//+
//用于显示
public static final String [] labs = new String[]{
"MC","MR","MS","M+","M-",
"←","CE","C","±","√",
"7","8","9","/","%",
"4","5","6","*","1/x",
"1","2","3","-","=",
"0",".","+"
};
}
②添加按钮
jptmp = new JPanel();
jptmp.setBounds(14, 72, 196,194);
jptmp.setLayout(null);
Font font_but = new Font("arial", Font.BOLD, 10);//创建按钮字体
for (int i = 0; i < jb_oper.length; i++) {
jb_oper[i] = new JButton(Operator.labs[i]);//设置按钮文字
jb_oper[i].setForeground(new Color(30,57,91));//设置字体颜色
jb_oper[i].setActionCommand(Operator.values()[i].toString());//设置按钮标示
jb_oper[i].setFont(font_but);//设置按钮字体
jb_oper[i].setBounds(i%5*(33+6), i/5*(24+6), 33, 24);//统一33宽,24高,间距6,每5个换一行
jb_oper[i].setBorder(new LineBorder(new Color(135,151,170), 1));//设置按钮边框
jb_oper[i].addActionListener(this);//添加监听器
jptmp.add(jb_oper[i]);
}
jb_oper[24].setBounds(24%5*(33+6), 24/5*(24+6), 33, 24*2+6);//调整等号按钮位置
jb_oper[25].setBounds(25%5*(33+6), 25/5*(24+6), 33*2+6, 24);//调整0按钮的位置
jb_oper[26].setBounds(27%5*(33+6), 26/5*(24+6), 33, 24);//调整.按钮的位置
jb_oper[27].setBounds(28%5*(33+6), 27/5*(24+6), 33, 24);//调整较好按钮的位置
jp.add(jptmp);

完整代码
-----
package com.lfd.view;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;

import com.lfd.common.Operator;

public class View extends JFrame implements ActionListener{
private JMenuBar jmb;
private JMenu jm_view,jm_edit,jm_help;
private JLabel jla_input,jla_show;
private JButton[] jb_oper = new JButton[28];

public View(){
initMenu();
initContent();
this.setTitle("计算器");//设置标题
this.setResizable(false);//不可改变大小
this.setLocationRelativeTo(null);//居中显示
this.setSize(228, 324);//窗体大小,可以使用FastStone Capture的屏幕尺量一下win计算器的大小
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//默认关闭操作
}

/**
* 初始化菜单方法
*/
private void initMenu(){
jmb = new JMenuBar();//创建菜单条
jm_view = new JMenu("查看(V)");//查看菜单
jm_view.setMnemonic('V');//设置热键
jm_edit = new JMenu("编辑(E)");//编辑菜单
jm_edit.setMnemonic('E');
jm_help = new JMenu("帮助(H)");//帮助菜单
jm_help.setMnemonic('H');

jmb.add(jm_view);
jmb.add(jm_edit);
jmb.add(jm_help);

this.setJMenuBar(jmb);//将菜单条加入窗体中
}

/**
* 创建内容区域初始化方法
*/
private void initContent(){
//整个窗口区域
JPanel jp = new JPanel();
jp.setLayout(null);
//显示框区域
JPanel jptmp = new JPanel(){
//获取背景图片,使用截图工具从win计算器显示框中截取2像素宽度作为背景
Image bg = new ImageIcon("imgs/bg.png").getImage();
/**
* 填充结果显示区域的背景
*/
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
//x轴平铺满面板
for(int i = 0;i<this.getWidth();i+=bg.getWidth(this)){
g.drawImage(bg, i, 0, this);//绘制背景图片
}
}
};

//设置显示框上方小字体
Font font_lab = new Font("arial", Font.BOLD, 22);
jla_input = new JLabel();
jla_input.setText("0");
//设置字体右对齐
jla_input.setHorizontalAlignment(JLabel.RIGHT);
jla_input.setFont(font_lab);
//设置显示框中计算结果的字体
font_lab = new Font("arial", Font.BOLD, 10);
jla_show = new JLabel();
jla_show.setText("sqrt");
//设置字体右对齐
jla_show.setHorizontalAlignment(JLabel.RIGHT);
jla_show.setFont(font_lab);

//设置显示框区域的位置的大小
jptmp.setBounds(14, 15, 190, 50);
jptmp.setLayout(new BorderLayout());
jptmp.add(jla_show,BorderLayout.NORTH);
jptmp.add(jla_input,BorderLayout.CENTER);
//设置边框
jptmp.setBorder(BorderFactory.createLineBorder(new Color(142,156,173)));
jp.add(jptmp);

jptmp = new JPanel();
jptmp.setBounds(14, 72, 196,194);
jptmp.setLayout(null);
Font font_but = new Font("arial", Font.BOLD, 10);//创建按钮字体
for (int i = 0; i < jb_oper.length; i++) {
jb_oper[i] = new JButton(Operator.labs[i]);//设置按钮文字
jb_oper[i].setForeground(new Color(30,57,91));//设置字体颜色
jb_oper[i].setActionCommand(Operator.values()[i].toString());//设置按钮标示
jb_oper[i].setFont(font_but);//设置按钮字体
jb_oper[i].setBounds(i%5*(33+6), i/5*(24+6), 33, 24);//统一33宽,24高,间距6,每5个换一行
jb_oper[i].setBorder(new LineBorder(new Color(135,151,170), 1));//设置按钮边框
jb_oper[i].addActionListener(this);//添加监听器
jptmp.add(jb_oper[i]);
}
jb_oper[24].setBounds(24%5*(33+6), 24/5*(24+6), 33, 24*2+6);//调整等号按钮位置
jb_oper[25].setBounds(25%5*(33+6), 25/5*(24+6), 33*2+6, 24);//调整0按钮的位置
jb_oper[26].setBounds(27%5*(33+6), 26/5*(24+6), 33, 24);//调整.按钮的位置
jb_oper[27].setBounds(28%5*(33+6), 27/5*(24+6), 33, 24);//调整较好按钮的位置
jp.add(jptmp);

this.setLayout(new BorderLayout());
this.add(jp,BorderLayout.CENTER);
}

public static void main(String[] args) {
new View().setVisible(true);
}

@Override
public void actionPerformed(ActionEvent e) {
//TODO 实现逻辑操作
JButton jb = (JButton) e.getSource();
String commond = jb.getActionCommand();
}
}
-----
package com.lfd.common;
public enum Operator{
mC,mR,mS,mAdd,mSubtract,//mc,mr,ms,m+,m-
clBack,clError,clClear,operNegation,operSqrt,//<-,ce,c,-/+,开平方
n7,n8,n9,operDivide,operPer,// /,%,
n4,n5,n6,operMultiply,operReciproc,//*,倒数
n1,n2,n3,operSubtract,operEqu,//-,=
n0,operDot,operAdd;//+
public static final String [] labs = new String[]{
"MC","MR","MS","M+","M-",
"←","CE","C","±","√",
"7","8","9","/","%",
"4","5","6","*","1/x",
"1","2","3","-","=",
"0",".","+"
};
}

⑽ 怎么用java,Swing实现windows标准计算器

布局结合组件完成计算器页面显示!~下面的例子实现了界面,你可以实现ActionListener接口,为对应按钮添加事件,实现计算器的计算功能!~

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.math.BigDecimal;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Calculator {
JFrame f = new JFrame("计算器");
Container c = f.getContentPane();
// 菜单栏
JMenuBar menubar = new JMenuBar();
JMenu menu1 = new JMenu("查看");
JMenu menu2 = new JMenu("编辑");
JMenu menu3 = new JMenu("帮助");
JMenuItem item1 = new JMenuItem("标准型");
JMenuItem item2 = new JMenuItem("复制");
JMenuItem item3 = new JMenuItem("粘贴");
JMenuItem item4 = new JMenuItem("关于计算机");
// 显示器面板
JPanel panel1 = new JPanel();
JTextField label = new JTextField(25);
// 按钮面板
JPanel panel2 = new JPanel();
private GridBagLayout gb = new GridBagLayout();
private GridBagConstraints gbc = new GridBagConstraints();
// 按钮内容
String[] cal = {"MC", "MR", "MS", "M+", "M-", "←", "CE", " C ", " ± ", "√", " 7 ", " 8 ", " 9 ", " / ", "%", " 4 ",
" 5 ", " 6 ", " * ", "1/x", " 1 ", " 2 ", " 3 ", "-", "=", "0", ".", "+", };
private JButton[] bs = new JButton[28];
// 建立两个BigDecimal为了精准运算
BigDecimal a = new BigDecimal("0");
BigDecimal b = new BigDecimal("0");

public void init() {
//为JFrame设置容器
c = f.getContentPane();
//设置JFrame布局方式
c.setLayout(new BorderLayout());
// 初始化界面
label.setEditable(false);
label.setText("0");
label.setHorizontalAlignment(JTextField.RIGHT);
panel1.add(label);
panel2.setLayout(gb);

gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(2, 2, 2, 2);
gbc.gridx = 0;
gbc.gridy = 0;
for (int i = 0; i < bs.length; i++) {
bs[i] = new JButton(cal[i]);
int x = 1;
String actionCommand = bs[i].getActionCommand().trim();
if("0".equals(actionCommand)) {
gbc.gridwidth = 2;
x = 2;
} else if("=".equals(actionCommand)) {
gbc.gridheight = 2;
}
gb.setConstraints(bs[i], gbc);
panel2.add(bs[i]);
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.gridx += x;
if((i+1)%5 == 0) {
gbc.gridx = 0;
gbc.gridy += 1;
}
}

menu1.add(item1);
menu2.add(item2);
menu2.add(item3);
menu3.add(item4);
menubar.add(menu1);
menubar.add(menu2);
menubar.add(menu3);

c.add(panel1, BorderLayout.NORTH);
c.add(panel2, BorderLayout.CENTER);

f.setJMenuBar(menubar);
f.pack();
f.setResizable(false);
f.setLocation(400, 350);
f.setVisible(true);

//关闭窗口时,停止程序
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] arg) {
new Calculator().init();
}

}

阅读全文

与javaswing计算器相关的资料

热点内容
python操作zookeeper 浏览:705
苹果手机dcim文件夹显示不出来 浏览:430
如何压缩文件夹联想电脑 浏览:583
程序员的学习之旅 浏览:440
apkdb反编译 浏览:922
雪花算法为什么要二进制 浏览:825
在文档中打开命令行工具 浏览:608
android图标尺寸规范 浏览:369
python实用工具 浏览:208
流量计pdf 浏览:936
科东加密认证价格 浏览:532
dos命令读文件 浏览:996
成为程序员需要什么学历 浏览:672
pdf农药 浏览:228
canal加密 浏览:497
日本安卓系统和中国有什么区别 浏览:137
linux命令行修改文件 浏览:838
从编译和解释的角度看 浏览:649
徐志摩pdf 浏览:651
夏天解压球视频 浏览:304