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.
Related
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.
I am currently making a GUI that prints a textarea. In this textarea I am required to receive the "weights" for the ID of the variable.
I have created multiple labels showing from ID1: - ID8: & their textfields, and use if statements instead but the with the amount of if and else if.
if (id.size = 1){
id1.setvisible(true);
weight1TField.setvisible(true);
}else if (id.size = 2){
id1.setvisible(true);
weight1TField.setvisible(true);
id2.setvisible(true);
weight2TField.setvisible(true);
}
else if (if.size = 3){
id1.setvisible(true);
weight1TField.setvisible(true);
id2.setvisible(true);
weight2TField.setvisible(true);
id3.setvisible(true);
weight3TField.setvisible(true);
}
So on... untill ID8.
The values are added to the array from a jtable in another Jframe when user has selected the rows(maximum 8 rows).
List<String> ID = new ArrayList<>();
I want to create text fields to allow the user to input their weights and jlabels showing the ID beside the textfield e.g ID: TextField. Image is shown below
ID[i] is replaced with the value in the array if there is one while the rest is hidden if there is no value. How can i create the Jlabels and JTexFields without doing the following below.
ID1.setText(ID[0]);
ID2.setText(ID[1]);
ID3.setText(ID[2]);
ID4.setText(ID[3]);
ID5.setText(ID[4]);
ID6.setText(ID[5]);
ID7.setText(ID[6]);
ID8.setText(ID[7]);
What about instead of using fields (I am not sure you are using fields, but the only thing i can do without more code is guess) to store the components into arrays? I have done an example with JLabels, you can do the same with textfields.
private static int idsCount = 6; //The number of ids. Let's say 6
private JLabel[] labels = new JLabel[8]; // Keep the array as a field. (8 = max capacity)
private void initIDLabels {
for (int i = 0; i < labels.length; i++) {
labels[i] = new JLabel();
// add this font to all labels.
labels[i].setFont(new Font("Tahoma", Font.BOLD, 12));
}
changeLabelsVisibility();
}
private void changeLabelsVisibility() {
// Hide all labels.
for (JLabel label : labels) {
label.setVisible(false);
}
// Show all labels that supposed to be visible
for (int i = 0; i < idsCount; i++) {
labels[i].setVisible(true);
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
Hello guys I started a personal project to where I would basically make a meal planner based of how many calories a person wants to consume per day for myself. I know it maybe a tough challenge for me since I'm a beginner, but I can do it! I will leave the backend later, but for now I wanted to work on the UI and I'm having trouble with this piece of code. I want to make a list of panels to be held in a panel, based on how many number of meals they want is how many panels will appear. any insight on this will be much appreciated.
package mealplanner;
import javax.swing.*;
/**
* Created by Usman on 6/8/2017.
*/
public class MealPlannerPanel extends JPanel {
JPanel[] panel;
int mealsPerDay, caloriesPerDay;
public MealPlannerPanel(){
mealsPerDay = Integer.parseInt(JOptionPane.showInputDialog("How many meals would you like per day?",null));
caloriesPerDay = Integer.parseInt(JOptionPane.showInputDialog("What is your daily calorie aim?",null));
panel = new JPanel[mealsPerDay];
for(int i = 0; i < panel.length; i++){
add(panel[i]);
}
}
public static void main(String[] args){
MealPlannerPanel planner = new MealPlannerPanel();
JFrame frame = new JFrame("Meal Planner");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(planner);
frame.pack();
frame.setVisible(true);
}
}
panel = new JPanel[mealsPerDay];
That statement just creates an array that is able to hold the given number of panels.
It does not actually create the panel (so when you index into the array you will get a null object).
So you need something like:
for(int i = 0; i < panel.length; i++){
JPanel onePanel = new JPanel();
panel[i] = onePanel;
add(panel[i]);
}
Also, be more descriptive with you variable names. "panel" implies a single component. Given it is meant to represent an array the least you can do is call it "panels" so we know there is more than one.
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();
I have a problem regarding loops. I need to access 10 labels which have names like label1, label2, label3 .... etc. I need to know whether I can access those labels by going through a loop in java?
How about using List or an array
List<JLabel> labels = new ArrayList<JLabel>();
labels.get(index);
Change those labels to be an array, and access it using an index.
For example:
JLabel[] labels = new JLabel[10];
for (int i = 0; i < labels.length; ++i) {
labels[i] = new JLabel("Label " + i);
}
for (int i = 0; i < labels.length; ++i) {
// access each label.
}
Put your labels in to LinkList or array
Then you can access those array or linkList on a loop
If you cannot change the labels names / put them into an array you can make an array of references to the labels and fill it at the beginning of your program with the list of your labels.
'Access to labels' is kinda vague. Are you referring to different instances of java.awt.label? If so you can simply loop over them when they're in a list with a for-each statement.
If you are talking about Java labels, you can use a switch statement instead. If you are talking about objects such as a JLabel, use an array or ArrayList.