I am working on a little game, a Java project for IT-classes.
To add/declare(???) Java swing elements I've used this type of writing:
JLabel A = new JLabel();
JLabel B = new JLabel();
//More JLabels...
JButton A = new JButton();
JButton B = new JButton();
//More JButtons...
That the code does not become longer and (more) confusing, I continued with this type of writing:
JLabel A = new JLabel(), B = new JLabel()/*More JLabels...*/;
JButton A = new JButton(), B = new JButton()/*More JButton...*/;
/*Generaly more comments everywhere over the code for my teacher (and me)
*and more for a better overview.
*/
My question is:
Is there a shorter way to add/declare(???) multiple Java swing elements at once?
//like this
JLabel A, B, C, D, E, F = new JLabel();
//or
new JLabel[A, B, C, D, E, F];//PLS don't ask what I'm doing in this line xD
or may is there already a semilar question in Stackoverflow that I've not found?
Edit
This question may already have an answer here: Initializing multiple
variables to the same value in Java 6 answers
Here the Link to the question
Your question has been identified as a possible duplicate of another
question. If the answers there do not address your problem, please
edit to explain in detail the parts of your question that are unique.
Not worked with Jbuttons and JLabels.
If you are using Java 8 you can use :
List<String> labels = ....;
Stream<Button> stream = labels.stream().map(Button::new);
List<Button> buttons = stream.collect(Collectors.toList());
From the book Java se 8 for the really impatient
Then you can use :
JPanel p = new JPanel();
buttons.forEach((t) -> p.add(t));//add your buttons to your panel
It depends, if all your objects are JLabel or the same object type, you could try:
An array of JLabel like:
JLabel[] labels = new JLabel[size of your array];
Then access it after inside a for loop:
for (int i = 0; i < labels.length; i++) {
labels[i] = new JLabel("I'm label: " + i);
}
A List of labels:
ArrayList <JLabel> labelsList = new ArrayList <JLabel>();
Then you could:
for (int i = 0; i < 10; i++) { //I take 10 as an arbitrary number just to do it in a loop, it could be inside a loop or not
labelsList.add(new JLabel("I'm label-list: " + i));
}
And later you could add them like:
pane.add(labels[i]); //Array
pane.add(labelsList.get(i)); //List
The above code should be inside a loop or change i for the explicit index of the element to be added.
If you want to do the same thing (or a similar thing) many times in a program, the answer is to use a loop of some kind. Here, you could declare an array (or List) of JButton elements, and loop over it to initialize its elements:
final int NUM_BUTTONS = 6;
JButton[] buttons = new JButton[NUM_BUTTONS];
for (int i = 0; i < NUM_BUTTONS; i++) {
buttons[i] = new JButton();
}
// refer to A as buttons[0], C as buttons[2], etc
You can make variables equal to each other after declaring them.
String one, two, three;
one = two = three = "";
So, I think you could do
JLabel A,B,C,D,E,F;
A = B = C = D = E = F = new JLabel();
Related
So I have two arrays of JRadioButton[] that I am trying to put into an array of ButtonGroup[]. When I add a single JRadioButton from my array one at a time to a single ButtonGroup, I have no problems. When I use a for-loop to add to an array of ButtonGroup[], there are no syntax errors but I do get a compiler error:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "javax.swing.ButtonGroup.add(javax.swing.AbstractButton)" because "allButtons[x]" is null
I don't mind creating buttonGroups one at a time, but I was just wondering why the first one works and the other doesn't.
The code that works:
//creates radio buttons
JRadioButton[] profButtons = new JRadioButton[profs.length];
JRadioButton[] expButtons = new JRadioButton[profs.length];
for(int i=0; i<profs.length; i++)
{
profButtons[i] = new JRadioButton(profs[i]);
expButtons[i] = new JRadioButton(profs[i]);
}
//makes the radio button groups.
ButtonGroup acrGroup = new ButtonGroup();
acrGroup.add(profButtons[0]);
acrGroup.add(expButtons[0]);
The code that doesn't work:
//creates radio buttons
JRadioButton[] profButtons = new JRadioButton[profs.length];
JRadioButton[] expButtons = new JRadioButton[profs.length];
for(int i=0; i<profs.length; i++)
{
profButtons[i] = new JRadioButton(profs[i]);
expButtons[i] = new JRadioButton(profs[i]);
}
//makes the radio button groups.
ButtonGroup[] allButtons = new ButtonGroup[profs.length];
for(int x=0; x<profs.length; x++)
{
allButtons[x].add(profButtons[x]);
allButtons[x].add(expButtons[x]);
}
profs is a String[] array that I use to label the radio buttons.
In this part of your code, you're creating the array of ButtonGroups, but you never initialize each element, so each of them is null
//makes the radio button groups.
ButtonGroup[] allButtons = new ButtonGroup[profs.length];
for(int x=0; x<profs.length; x++)
{
allButtons[x].add(profButtons[x]);
allButtons[x].add(expButtons[x]);
}
So, inside your for-loop, add this line as the first line
allButtons[x] = new ButtonGroup();
And then, the rest of your code
I'm sure this question has been asked but I cannot find it (on SO or Google) for my life.
How can I most effectively create a reference to multiple objects that I create in a loop?
In this specific case, I am using Swing to add JButtons to a GridLayout.
int numOfButtons = 10;
for (int i = 0; i < numOfButtons; i++){
add(new JButton("" + i));}
If later I want to change the text on the buttons, how would I do so? Say, if I wanted to change button number 8:
buttonEight.setText("DO NOT CLICK!!!);
How would I create a reference to the button with the 8 on it from buttonEight?
The only thing I can think of is creating a bunch of instance variables before the loop. Except... Well. Actually , that wouldn't work (I don't think)
Something that would do this:
JButton button8;
for (int i = 0; i < numOfButtons; i++){
button + i = new JButton(""+ i);
//like, if i = 8 then button + i gets me button8 to reference it or something?
//obviously that doesn't work
}
button8.setText("DO NOT CLICK!!!);
and also I'd be in trouble creating the right number of instance variables if numOfButtons is variable.
How should I do this?
Use an ArrayList:
ArrayList<JButton> list=new ArrayList<>();
int numOfButtons = 10;
for (int i = 0; i < numOfButtons; i++){
JButton jb=new JButton("" + i);
list.add(jb);
add(jb);
}
Later (assuming you want to change the text of 8th button (which is 7 in list)):
list.get(7).setText("...");
The list only create a reference to JButton object. Then any change made to it will reflect on the UI.
Or, if you wanted to set the text of only the eighth button, you could use a conditional to single out that button:
for (int i=0;i<numOfButtons;i++) {
if (i==7) {
add(new JButton("DO NOT CLICK!");
} else {
add(new JButton(""+i);
}
}
which will save memory space in your program than if you use an ArrayList.
This question already has answers here:
Assigning variables with dynamic names in Java
(7 answers)
Closed 6 years ago.
I am trying to continually create JLabels for every name in an ArrayList PantryNames. Here is my current code:
for(int i = 0; i < FoodApp.getPantryNames().size(); i++){
JLabel lblNewLabel = new JLabel((String) FoodApp.getPantryNames().get(i));
contentPane.add(lblNewLabel, BorderLayout.WEST);
}
I want the lblNewLabel to be set to "ingredient" + (i + 1). For example, the first food would be ingredient1 and so on. Additionally, in the contentPane, lblNewLabel would have to be ingredient + (i + 1). Thanks!
That's not how variables work in Java, you can't dynamically set variable names like that. Instead I would use a List<JLabel>.
ArrayList<JLabel> labels = new ArrayList<JLabel>();
for(int i = 0; i < FoodApp.getPantryNames().size(); i++){
JLabel temp = new JLabel((String) FoodApp.getPantryNames().get(i));
labels.add(temp);
contentPane.add(temp, BorderLayout.WEST);
}
Alternatively you could just call contentPane.getComponents() whenever you need the labels again.
I'm relatively new to java and i'm trying to do an assignment for school. In my assignment i'm supposed to make a GUI program that makes a 8 by 8 red and black colored checkerboard. The only problem (so far) that i'm having is initializing a two-dimensional array of JPanels. i'm getting this error when using eclipse:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
This doesn't give an error until i try to run the code. It says the error is occurring in the body of this for loop:
JPanel[][] panel = new JPanel[7][7];
for (int i = 0; i <= panel.length; i++){
panel[i][0] = new JPanel();
panel[i][1] = new JPanel();
panel[i][2] = new JPanel();
panel[i][3] = new JPanel();
panel[i][4] = new JPanel();
panel[i][5] = new JPanel();
panel[i][6] = new JPanel();
panel[i][7] = new JPanel();
}
This does work if i don't use a for loop but i really don't want to put in 64 different statements do do this. I double checked and the panel.length does give the value 7 (which is what i wanted) and did not work even when i physically put in 7. I don't have any syntax error is my code, but i still get the error. Is there some other way i should go about doing this? Thanks in advance. Remember i'm new to this.
"make a GUI program that makes a 8 by 8 red and black colored checkerboard. The only problem (so far) that i'm having is initializing a two-dimensional array of JPanels.".
If all you need to do is make the board, with no other conditions, why not just use a GridLayout
JPanel mainPanel = new JPanel(new GridLayout(8, 8));
for (int i = 0; i < 64; i++){
JPanel panel = new JPanel();
// alternate background colors with a predefined boolean and an if
mainPanel.add(panel);
}
Three things:
A checkboard is 8×8, so you really want panel.length to be 8, no?
A standard for loop uses < for the test, not <=.
If you use two nested loops, you don't need to repeat new JPanel() 8 times.
Result:
JPanel[][] panel = new JPanel[8][8];
for (int i = 0; i < panel.length; i++) {
for (int j = 0; j < panel[i].length; j++) {
panel[i][j] = new JPanel();
}
}
Is there any way to add "n" Jlabels to the frame, where n is specified somewhere in code? Can I make an Array of Jlabels?
Yes you can
JLabel [] labels = new JLabel[n];
for(int i = 0 ; i <labels.length;i++){
labels[i] = new JLabel("sometext");
//.... and other things
}
It's better to use java.util.List instead of array:
List<JLabel> labels = new ArrayList<>();
for(int i = 0 ; i <labels.length;i++){
labels.add(new JLabel("SomeText"));
labels.get(i).setForeground(Color.red);
//.... and other things
}