對象 - 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]);//為什么是Nullarray.add(e.getActionCommand());System.out.println(e.getSource());text.setText(text.getText()+e.getActionCommand()); }}
運行結果如下圖,按鈕都顯示出來了,為什么輸出是Null?
問題解答
回答1: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++;}
相關文章:
1. android - 分享到微信,如何快速轉換成字節數組2. javascript - 能否讓vue-cli的express修改express重啟服務3. node.js - npm一直提示proxy有問題4. 解決Android webview設置cookie和cookie丟失的問題5. angular.js - Beego 與 AngularJS的模板格式沖突,該怎么解決?6. html5 - 有人做過防微信app界面的H5 demo嗎?7. javascript - 有沒有iOS微信中可以在背景播放視頻的方法?8. phpstorm 沒有安裝Emmet怎么還有Emmet的相關功能啊9. 最新版本的微信web開發者工具必須要APPID,會提供測試號,但是像你一樣tabBar配置的話不會顯示首頁與日志,難道我要下載跟你一樣的版本?10. Navicat for mysql 中以json格式儲存的數據存在大量反斜杠,如何去除?
