[英]Numeric Keypad more efficient way
有沒有更有效的方法來添加按鈕R,0和E? 是否有可能以某種方式將它們添加到陣列中?
public Keypad() {
setTitle("Keypad");
setSize(220, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(new GridLayout(4, 3, 2, 2));
JButton[] buttonArray = new JButton[10];
for (int i = 1; i < buttonArray.length; i++) {
buttonArray[i] = new JButton(String.valueOf(i));
add(buttonArray[i]);
buttonArray[i].addActionListener(this);
}
add(buttonR);
add(button0);
add(buttonE);
setVisible(true);
setResizable(false);
}
您無法獲得比現在更高的效率。 您可能會稍微重組一下代碼,以在單個方法中將ActionListener的添加和按鈕的添加移動到層次結構中。 而且, JButton[]
沒用,因此刪除它,您將在內存中保存一些字節(但實際上沒有什么大不了的):
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Keypad extends JFrame implements ActionListener {
private JButton buttonR = new JButton("R");
private JButton button0 = new JButton("0");
private JButton buttonE = new JButton("E");
public Keypad() {
setTitle("Keypad");
setSize(220, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(new GridLayout(4, 3, 2, 2));
for (int i = 1; i < 10; i++) {
addButton(new JButton(String.valueOf(i)));
}
addButton(buttonR);
addButton(button0);
addButton(buttonE);
setResizable(false);
setVisible(true);
}
private void addButton(JButton button) {
button.addActionListener(this);
add(button);
}
@Override
public void actionPerformed(ActionEvent e) {
}
}
“有可能以某種方式將它們添加到陣列中嗎?”
是的,如果您要這樣做,就可以這樣做
JButton[] buttonArray = new JButton[10];
for (int i = 1; i < buttonArray.length+3; i++) {
if(i<buttonArray.length){
buttonArray[i] = new JButton(String.valueOf(i));
add(buttonArray[i]);
buttonArray[i].addActionListener(this);
}
if(i==buttonArray.length+1){add(buttonR);}
if(i==buttonArray.length+2){add(button0);}
if(i==buttonArray.length+3){add(buttonE);}
}
這可以滿足您的要求,但是AFAIK沒有更快的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.