java如何添加循环_java – 使用for循环时向JButton添加操作

我正在尝试动态添加按钮(JButtons),它每次都会更改名称.我用for循环做它并没有真正的问题.但是当添加一个动作监听器或识别哪个按钮被按下时,那就是当事情不能很好地工作时.

MyFrame.java

import javax.swing.*;

import java.awt.event.*;

import java.awt.GridLayout;

public class MyFrame extends JFrame implements ActionListener

{

private JPanel panel;

private static JButton[] buttons = new JButton[18];

// set all static calculate JButtons

private static JButton equalsBtn, addBtn, subBtn, multiBtn, divBtn, clearBtn, plusMinusBtn, decimalBtn;

// set all static number JBtuttons

private static JButton zeroBtn, oneBtn, twoBtn, threeBtn, fourBtn, fiveBtn, sixBtn, sevenBtn, eightBtn, nineBtn;

private static JTextField resultField;

// numOne is the first row of figures en the second numSecond is the second row

private static double numOne, numSecond, result;

private static double plusMinus;

private static int addClick = 0, subClick = 0, multiClick = 0, divClick = 0;

private static int clearField;

public MyFrame() {

// configure the JFrame

super("Rekennen maar!");

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setResizable(false);

setSize(230, 370);

setLocationRelativeTo(null);

// confugure the JPanel

panel = new JPanel();

panel.setSize(230, 370);

panel.setLayout(new GridLayout(5, 0));

// array string whit all the button names

String a_btnNames[] = {"clearBtn", "plusMinusBtn", "divBtn", "multiBtn", "sevenBtn", "eightBtn", "nineBtn", "subBtn", "fourBtn", "fiveBtn", "sixBtn", "addBtn", "oneBtn", "twoBtn", "threeBtn", "equalsBtn", "zeroBtn", "decimalBtn"};

// array String whit all button characters

String a_btnCharts[] = {"C", "+/-", "/", "*", "7", "8", "9", "-", "4", "5", "6", "+", "1", "2", "3", "=", "0", "."};

for(int i = 0; i < buttons.length; i++)

{

// make new button name

buttons[i] = new JButton(a_btnNames[i]);

// add button to panel

panel.add(new JButton(a_btnCharts[i]));

//System.out.println(buttons[i]);

}

// add panel when he's filled

add(panel);

setVisible(true);

}

public void actionPerformed(ActionEvent e) {

// press the button

if ( e.getSource() == ...... ) {

System.out.println("123");

}

}

}

Main.java

public class Main {

public static void main(String[] arg) {

MyFrame mf = new MyFrame();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值