gpt4 book ai didi

java - java中自动按钮的实现

转载 作者:行者123 更新时间:2023-12-01 10:35:12 25 4
gpt4 key购买 nike

我想要一个 for 循环,它可以实现并逐个添加指定数量的 JButton。我试图实现它,这是我到目前为止的代码:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ArrayForm extends JFrame implements ActionListener
{
JPanel numPanel = new JPanel();
JPanel opPanel = new JPanel();

JTextField textField = new JTextField(25);

JButton [] buttons = new JButton[10];
JButton [] OPbuttons = new JButton[6];

String num="";

String [] operation = {"+","-","*","/","=","C"};

public static void main(String[] args)
{ArrayForm fobject = new ArrayForm();}

public ArrayForm()
{
setLayout(new FlowLayout());
setSize(400,300);
setTitle("Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);

numPanel.setPreferredSize(new Dimension(180,150));
numPanel.setLayout(new FlowLayout());

opPanel.setPreferredSize(new Dimension(200,70));
opPanel.setLayout(new FlowLayout());

for (int i = 0; i<10; i++)
{
//The code in here
}

for (int i = 0; i<6; i++)
{
//The code in here
}

add(textField);
this.textField.setEditable(false);
add(numPanel);
add(opPanel);
setVisible(true);
}

@Override
public void actionPerformed(ActionEvent e)
{

}
}

你能帮我解决 for 循环部分吗?其中第一个是 buttons 数组,第二个是 OPbuttons 数组。

最佳答案

您的for循环部分可能如下:

            for (int i = 0; i<10; i++)
{
buttons[i] = new JButton(""+i);
numPanel.add(buttons[i]);
buttons[i].addActionListener(this);
}

for (int i = 0; i<6; i++)
{
OPbuttons[i] = new JButton(operation[i]);
opPanel.add(OPbuttons[i]);
OPbuttons[i].addActionListener(this);
}

我所理解的是,您正在尝试在两个不同的面板中自动添加计算器的按钮......

注意:不要忘记为您的操作监听器添加代码。

关于java - java中自动按钮的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34793404/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com