對(duì)象 - Java JButton數(shù)組初始化后還是空?
問題描述
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('計(jì)算器界面練習(xí)');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]);//為什么是Nullarray.add(e.getActionCommand());System.out.println(e.getSource());text.setText(text.getText()+e.getActionCommand()); }}
運(yùn)行結(jié)果如下圖,按鈕都顯示出來了,為什么輸出是Null?
問題解答
回答1:Java foreach語句中的btn只是遍歷myBtns的備份(傳值),并不是引用。引用相當(dāng)于對(duì)原始數(shù)據(jù)做操作,賦值相當(dāng)于對(duì)原始數(shù)據(jù)的副本做操作。所以要在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++;}
相關(guān)文章:
1. javascript - 如圖,百度首頁,查看源代碼為什么什么都沒有?2. vue2.0+webpack 如何使用bootstrap?3. PHP類封裝的插入數(shù)據(jù),總是插入不成功,返回false;4. mac連接阿里云docker集群,已經(jīng)卡了2天了,求問?5. node.js - 如何重定向到public下的靜態(tài)html文件6. mysql - 微信小程序如何提高查詢速度?7. 前端 - 我有一個(gè)建站程序,但是多個(gè)文件夾下的HTML模板代碼沒有進(jìn)行縮進(jìn)格式化,請(qǐng)問用什么軟件可以批量格式化一下代碼?8. vue 子組件watch監(jiān)聽不到prop的解決9. 我畢業(yè)以后在工作之余學(xué)了 PHP,都是自學(xué) 現(xiàn)在在找這方面的工作 求前輩指導(dǎo)學(xué)習(xí)方向 工作常用的知識(shí)10. javascript - 關(guān)于jquery的ajax post數(shù)據(jù)的問題
