Reputation: 3
I'm a beginner to programming as a whole and I was wondering instead of typing what's given below, if there's a way you can assign these variable names into a String[] or making it to where I'm not typing the same code over and over again just with different variables?
JButton one = new JButton("1");
one.addActionListener(new Numbers());
add(one);
JButton two = new JButton("2");
two.addActionListener(new Numbers());
add(two);
JButton three = new JButton("3");
three.addActionListener(new Numbers());
add(three);
Thanks!
Upvotes: 0
Views: 73
Reputation: 73558
No, but you could assign your JButtons
to an array.
JButton[] buttons = new JButton[3];
for(int i = 0;i < 3; i++) {
buttons[i] = new JButton(String.valueOf(i));
buttons[i].addActionListener(new Numbers());
add(buttons[i]);
}
if you don't need to access the jbutton references later on, you don't even need the array.
for(int i = 0;i < 3; i++) {
JButton jb = new JButton(String.valueOf(i));
jb.addActionListener(new Numbers());
add(jb);
}
Upvotes: 7