對(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. docker容器呢SSH為什么連不通呢?2. docker api 開發(fā)的端口怎么獲取?3. docker網(wǎng)絡(luò)端口映射,沒有方便點(diǎn)的操作方法么?4. 關(guān)docker hub上有些鏡像的tag被標(biāo)記““This image has vulnerabilities””5. python - from ..xxxx import xxxx到底是什么意思呢?6. nignx - docker內(nèi)nginx 80端口被占用7. debian - docker依賴的aufs-tools源碼哪里可以找到啊?8. ddos - apache日志很多其它網(wǎng)址,什么情況?9. 請(qǐng)教各位大佬,瀏覽器點(diǎn) 提交實(shí)例為什么沒有反應(yīng)10. angular.js - ng-grid 和tabset一起用時(shí),grid width默認(rèn)特別小
