Programmatically Name Variables in Java for GUI - java

I am creating a GUI in java using gridLayout 6 x elevatorNum. My purpose is to create the number of columns based on the user input "elevatorNum" so that it can automatically be expanded. My problem now is that I want to populate each column with the same 6 JLabel fields and then be able to use these fields to change their values whenever I want to.
I am not able to do this since I will have to create a new set of 6 JLabels for each column but for that I would need to either hardcode each column or automatically expand them using user input. I want to automatically expand them using userInput but I don't know how to name each set of 6 JLabels without hardcoding them.
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setLayout(new GridLayout(7,elevatorNum));
JLabel totalFloors = new JLabel("Total floors: " + floorNum);
JLabel currentFloor = new JLabel("CurrentFloor : N/A");
JLabel destFloor = new JLabel("Destination Floor: N/A");
JLabel doorStatus = new JLabel("Doors Status: N/A");
JLabel motorStatus = new JLabel("Motor Status: N/A");
JLabel passengerStatus = new JLabel("Passenger Status: N/A");
JLabel elevatorStatus = new JLabel("Elevator Direction: N/A");
frame.add(totalFloors);
frame.add(currentFloor);
frame.add(destFloor);
frame.add(doorStatus);
frame.add(motorStatus);
frame.add(passengerStatus);
frame.add(elevatorStatus);
Now i want to create another 6 set of JLabels but I will have to use different name but I don't know the userinput so I cannot hardcode the 6 JLabels. I also want to use each set of JLabels later on to update/edit their values.
I would greatly appreciate your help.

I had a similar experience of populating the layout with buttons and need to change their values anytime I want. I think you don't need to have user input to create labels, try simply create JLabels in a for loop, and track them by adding each of them to a List. you could find exactly that label through its index in array.
for example, create a list to track them:
List<JLabel> labelList = new ArrayList<>();
then create a method to create JLabels:
private JLabel createLabel() {
JLabel newLabel = new JLabel("give_it_an_initial_name");
// maybe do something on each label
return newButton;
}
finally add them to frame:
for(int i = 0; i < 6 * elevatorNum; i++) {
JLabel addLabel = createLabel();
frame.add(addLabel);
labelList.add(addLabel);
}
when you want to change something on label, fetch it from list and edit, no need to give each of them a name.It's a very simple way, might not be very good, but it works.

Related

jpanel cannot make gridlayout with 7 rows and 2 cols

i want to ask if anything goes wrong with my code. i've set my frame with borderlayout . and on the center part, i want to use gridlayout with 7rows and 2 cols inside them.
paneltengah= new JPanel();
paneltengah.setLayout(new GridLayout(7,2));
labelname = new JLabel(lbl_name,SwingConstants.LEFT);
labelusername = new JLabel(lbl_username,SwingConstants.LEFT);
labelpassword = new JLabel(lbl_password,SwingConstants.LEFT);
labelgender = new JLabel(lbl_gender,SwingConstants.LEFT);
labelemail = new JLabel(lbl_email,SwingConstants.LEFT);
labelhobby = new JLabel(lbl_hobby,SwingConstants.LEFT);
labelrole = new JLabel(lbl_role,SwingConstants.LEFT);
textname = new JTextField(20);
textusername = new JTextField(20);
textpassword = new JPasswordField(20);
textemail = new JTextField(20);
comboboxhobby = new JComboBox();
comboboxrole = new JComboBox();
radiobuttonmale = new JRadioButton("Male");
radiobuttonfemale = new JRadioButton("Female");
ButtonGroup btngroup = new ButtonGroup();
btngroup.add(radiobuttonmale);
btngroup.add(radiobuttonfemale);
paneltengah.add(labelname);
paneltengah.add(labelusername);
paneltengah.add(labelpassword);
paneltengah.add(labelgender);
paneltengah.add(labelemail);
paneltengah.add(labelrole);
paneltengah.add(labelhobby);
//// paneltengah.add(textname); when i open this, the layout become awkward
//// paneltengah.add(textusername);
//// paneltengah.add(textpassword);
//// paneltengah.add(radiobuttonmale);
//// paneltengah.add(radiobuttonfemale);
//// paneltengah.add(comboboxhobby);
//// paneltengah.add(comboboxrole);
pane.add(paneltengah, BorderLayout.CENTER);
the following pictures is shown without opening the comment
the following picture is shown with uncomment
what is wrong with my code ?
First of all, a GridLayout sizes all components evenly in its associated Container, which explains why your labels and fields are all the same size. For example, if you had a JTextArea 200 columns × 20 lines in your JPanel, then even the tiniest label would occupy that huge a space as well!
Next, according to the GridLayout Javadoc, when a GridLayout instance is constructed with two non-zero arguments, the number of rows gets fixed and the number of columns is adjusted according to the number of components put into the parent Container.
What I suggest is using a BorderLayout to set up your main form layout. Put your title at NORTH and keep the CENTER for your labels and fields (your current JPanel).
For your labels and fields, the simplest solution might be using a GridLayout(0, 2) (fixed number of columns). But all your components will still be equally sized.
If you need more control over the size of your components (e.g., fields wider than labels), then I suggest using another layout manager such as GridBagLayout. I know it's more complex to manage but using a GridBagLayout formatting preview utility should help. Such a program may be named something like GridBagLab (I know David Geary's book Graphic Java volume 2 — Swing features one on its companion CD).
There is also a GridBagLayout tutorial at https://www.youtube.com/watch?v=Ts5fsHXIuvI.

How to create JCheckBox for elements of an ArrayList

I have an array that fills in by the user. Then each element of this array will be a CheckBox. For example if the array has 6 elements, it must create 6 checkboxes.
This is how I tried to loop through the array and create the checkbox, but it only overwrite on one checkbox.
public static void main(String[] args) {
JFrame frame = new JFrame("Options");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
ArrayList<String> myArrayList = new ArrayList<String>();
myArrayList.add("checkbox 1");
myArrayList.add("checkbox 2");
myArrayList.add("checkbox 3");
myArrayList.add("checkbox 4");
myArrayList.add("checkbox 5");
for(String element : myArrayList){
JCheckBox box = new JCheckBox(element);
frame.add(box);
}
frame.setVisible(true);
}
It is important that I have the access to each single checkbox later, so I can specify for example if checkbox2 is selected, do this.
So is there any way to make these checkboxes dynamically according to the ArrayList's size?
Every time you add something new to the JFrame, it removes the thing that was previously in it.
You'll need to create a JPanel or some other container to hold the JCheckBoxes, and then put that inside the JFrame.
Also, you can keep track of the checkboxes in a List.
For instance:
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(BoxLayout.Y_AXIS, panel));
List<JCheckBox> checkboxes = new ArrayList<>();
for(String element : myArrayList) {
JCheckBox box = new JCheckBox(element);
checkboxes.add(box);
panel.add(box);
}
frame.add(panel);
The main problem is, you're adding all the check boxes to the same location on the frame.
A JFrame uses a BorderLayout by default. A BorderLayout allows a single component to be managed in each of its five available slots. Basically a BorderLayout will ignore all but the last component added to any of the slots
Instead, try changing the LayoutManager to something more useful, like FlowLayout or GridBagLayout depending on your needs
Take a look at Laying Out Components Within a Container for more details.
Depending on your needs, I might be tempered to fill the ArrayList with the JCheckBoxes instead of String or even a Map of some kind, to make it easier to link the text with the JCheckBox

Java iterate through JList which contains JPanel - JLabel

I am trying to iterate over a JList where each item contains:
JPanel - JLabel
Currently what i have is:
System.out.println("Reading all list items:");
System.out.println("-----------------------");
for (int i = 0; i < menuList.getModel().getSize(); i++) {
Object item = menuList.getModel().getElementAt(i);;
System.out.println("Item = " + item);
}
The output i get is:
Item =
javax.swing.JPanel[,0,0,0x0,invalid,layout=java.awt.FlowLayout,alignmentX=0.0,alignmentY=0.0,border=,flags=9,maximumSize=,minimumSize=,preferredSize=]
Instead i want to access the text that is inside the JPanel.
How could this be done?
Edit:
This is how i add my JPanel to the JList
menuList = new JList(v);
v = new Vector <String> ();
menuList.setListData(v);
.....
// get our images
Icon pingImage = new javax.swing.ImageIcon(getClass().getResource("/resources/icnNew.png"));
// add the images to jlabels with text
JLabel pingLabel = new JLabel("Hi there", pingImage, JLabel.LEFT);
// create the corresponding panels
JPanel pingPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
// add the labels onto the panels
pingPanel.add(pingLabel);
v.add(pingPanel);
So the text i want to find is "Hi there"
Then what you need is to check for the elements inside that JPanel. I mean, a panel is a container of UI elements, that said, you need to check for the elements, once you checked for that you need to compare whether it is a label or not, if it is a label then you will be able to get the text of that label.
Can't you show us the code, probably could be easier if you provide the snippet.

Can you make a JFrame randomly choose a picture for it's background

Can you make a JFrame that just randomly chooses the provided three to four pictures as its background. So that when a user opens the JFrame, the JFrame will choose any of the stated pictures to choose from to be a background.
I want it something like this:
ImageIcon background = new ImageIcon("First Image.png");
JLabel label = new JLabel(background);
frame.add(label);
And the second picture:
ImageIcon background2 = new ImageIcon("Second Image.png");
JLabel label2 = new JLabel(background2);
frame.add(label2);
The third:
ImageIcon background3 = new ImageIcon("Third Image.png");
JLabel label3 = new JLabel(background3);
frame.add(label3);
And maybe the fourth:
ImageIcon background4 = new ImageIcon("Fourth Image.png");
JLabel label4 = new JLabel(background4);
frame.add(label4);
And I want some code so then the JFrame can use any one of these codes.
Also, is there a way to change the JFrame title randomly?
Like I want it something like:
'My Game: It's the best!'
...and then when the user opens the JFrame again, the title will change to, maybe:
'My Game: Try it, it's new!' and/or
'My Game: You can play it easily!' and/or
'My Game: Find all the mysteries...' and/or
'My Game: Money don't go on trees!' and other funny lines.
Hope I made it easy for you to understand!
Also consider Collections.shuffle(), illustrated here for List<JLabel> and here for List<Icon>.
You can use java.util.Random class to generate random numbers.
If you want to select random string/image/image path you can just declare an array and get a random item from it. Here's an example code for titles:
//class level variable, supply your own lines.
final String[] TITLES = new String[]{"My Game: It's the best!", "My Game: Try it, it's new!"}
//next snippet is random title generation
//it's better to use only one random instance,
//so you might want to declare this one on class level too
Random random = new Random();
int index = random.nextInt(TITLES.length); //get random index for given array.
String randomTitle = TITLES[index];
frame.setTitle(randomTitle);
You can do the same for image paths/images. Declare an array of type, get an object by random index:
final String[] IMAGE_PATHS = //initialization goes here
Random random = new Random();
String randomImagePath = IMAGE_PATHS[random.nextInt(IMAGE_PATHS.length)];
ImageIcon background = new ImageIcon(randomImagePath);
JLabel label = new JLabel(background);

How to print to a J text box the entire contents of a tree map?

Hi Everyone thanks for taking the time to look at my question.
I would like to use the JText field I have created to display the values of a tree map which contains all the employees: ID numbers (as the key in the map)as well as an Employee object which contains a to string method of all the employee details.
the system seems to be working fine because when I print to the console (CMD) it works fine and prints out all the values in the MAP but when I try print it to a JText box it only prints one object (one employee) from the entire list.
I believe the issue lies with my for loop i am using to access all the details.
the issue lies with this line of code:
writeStrings.setText(writeStrings.getText()+" "+dEmp);
This is the code in its entirety:
public void chooseEmpToAdd()
{
JFrame frameAllEmps = new JFrame();
frameAllEmps.setSize( 450, 140 );
frameAllEmps.pack();
frameAllEmps.setVisible(true);
int x = 0;
System.out.println("ALL Emps from the tree map");
for(int key:employeeMap.keySet())
{
JTextField writeStrings;
writeStrings = new JTextField(20);
Employee dEmp = employeeMap.get(key);
System.out.println("Employe no :" +x+": "+dEmp);
writeStrings.setText(writeStrings.getText()+" "+dEmp);
frameAllEmps.add(writeStrings);
x++;
}
}
writeStrings = new JTextField(20);
You create new JTextField component on every iteration and add it to container.
JFrame uses BorderLayout as a default layout.
This layout puts your JTextField component in the center (frameAllEmps.add(writeStrings)). So you lost previous added JTextField and see only last JTextField component.

Categories

Resources