Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

Java JButton数组初始化后还是空?

import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.server.Operation;
import java.text.Normalizer.Form;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;


public class Calc extends JFrame implements ActionListener
{
    JTextField text;
    JButton[] myBtns = new JButton[16];    
    String[] btnName = {"7","8","9","+","4","5","6","-","1","2","3","*","C","0","=","/"};
    public Calc()
    {
        super("计算器界面练习");
        this.setBounds(200, 0, 635,600);
        Container content = this.getContentPane();
        FlowLayout flow = new FlowLayout();
        flow.setAlignment(FlowLayout.LEFT);
        content.setLayout(flow);
        
        text = new JTextField("0123");
        text.setPreferredSize(new Dimension(600, 100));
        text.setEditable(false);
        text.setHorizontalAlignment(JTextField.RIGHT);
        text.setFont(new Font("宋体",Font.PLAIN , 80));
        content.add(text);
        
        int index = 0;
        for (JButton btn : myBtns)
        {
            btn = new JButton(btnName[index]);
            btn.setPreferredSize(new Dimension(145,100));
            btn.setFont(new Font("Times New Roman",Font.BOLD,80));
            btn.addActionListener(this);
            content.add(btn);
            index++;
        }

        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    

    @Override
    public void actionPerformed(ActionEvent e)
    {
        ArrayList<String> array = new ArrayList<String>();
        
        System.out.println(myBtns[0]);//为什么是Null
        array.add(e.getActionCommand());
        System.out.println(e.getSource());
        text.setText(text.getText()+e.getActionCommand());
    }

}

运行结果如下图,按钮都显示出来了,为什么输出是Null?
图片描述
图片描述


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Java foreach语句中的btn只是遍历myBtns的备份(传值),并不是引用。引用相当于对原始数据做操作,赋值相当于对原始数据的副本做操作。
所以要在foreach中加一句myBtns[index] = btn;

for (JButton btn : myBtns)
        {
            btn = new JButton(btnName[index]);
            myBtns[index] = btn;
            btn.setPreferredSize(new Dimension(145,100));
            btn.setFont(new Font("Times New Roman",Font.BOLD,80));
            btn.addActionListener(this);
            content.add(btn);
            index++;
        }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...