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.
Related
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.
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
I'm trying to make a simple calculator in Java using Swing, and I've created my buttons the following way:
//Our number keypad
public static JPanel numbers(){
//our panel to return
JPanel panel = new JPanel();
//Create and add 3x4 grid layout to panel
GridLayout gl = new GridLayout(3, 4);
panel.setLayout(gl);
//For creating and adding buttons to panel
for(int i = 0; i < 10; i++){
//Create a new button where the name is the value of i
String name = "" + i + "";
JButton button = new JButton(name);
//add action listener
button.addActionListener(handler);
//Add button to panel
panel.add(button);
}
return panel;
}
My question is how do I reference each specific button in my event handler? I can't think of a way to do this without having to manually create each button rather than using a loop.
Thanks.
In your listener, call event.getSource(), and that will return the button which has been pressed. Get the text of the button, and you have its number.
Or create a different instance of your handler for every button, and pass the value of the button (i) to the constructor of the handler. This last solution is cleaner, IMO, because it doesn't depend on the text of the button. If you replaced the text by an image, for example, the first technique wouldn't work anymore.
You can distinguish created buttons by adding the following inside handler:
String buttonText = ((JButton) e.getSource()).getText();
if (<text1>.equals(buttonText)){
//do the stuff
} else if (<text2>.equals(buttonText)){
//do the stuff
} else {
//do the stuff
}
Method #1: go through the child components of the parent JPanel (quite tedious, has to be rebuilt every time you modify the contents of that JPanel). Make sure they're JButtons by using an if . . instanceof clause.
Method #2: as you create them in that loop, add them to a List (or even better, a Map). I prefer a Map personally as it lets me customise the key for that specific JComponent
i.e.
HashMap<String, JComponent> buttonList = new HashMap<String, JComponent>();
for(. .) {
buttonList.put("nameForEachButton", button);
}
I recommend generating the button name based off of the loop counter. Either use your existing name value, or just set it to "button" + i;
Declare your buttons using an array.
JButton[] button = new JButton[9]; //outside the for loop
for (int i = 0; i < 10; i++) {
//put your code
button[i] = new JButton(name);
//your code
}
Is there a way to add jcheckboxes into a jscrollpane?
I have an array of checkboxes and I want to add them into a Jscrollpane, which i will then add into a JOptionPane. So far I have this:
Object[] books = new Object[10000];
books[0] = "Choose books to purchase: ";
for(int l = 1;l<checkboxes.length;l++)
{
books[l] = checkboxes[l];
}
JList list = new JList(checkboxes);
//JTextPane test = new JTextPane();
//test.add(checkboxes[0]);
JScrollPane myScrollPane = new JScrollPane(list);
myScrollPane.setPreferredSize(new Dimension(250,250));
JOptionPane.showMessageDialog(null, "Choose the books you want to purchase below.\nPlease note that each book has a $5 shipping charge.\nThe books are formatted as Title - Author - Price", "Reminder",JOptionPane.PLAIN_MESSAGE);
JOptionPane.showMessageDialog(null,myScrollPane,"Book List",JOptionPane.OK_CANCEL_OPTION);
The output does not give me the checkboxes, just the pointer of the checkboxes i think.
As you can see, I've tried putting the checkboxes into a JList but failed.
Thanks a lot guys!
You can add the checkboxes to JPanel and that Jpanel can be shown in JDialog instead of JOptionPane.
And to add the Checkboxes to JPanel u can check this link
How to use JCheckbox array in JPanel array
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.