Reputation: 55
i have jdialog. and i have added 50 buttons inside a jpanel in the jdialog. Now i want to get the values of the buttons which is set by button.setText() now my code looks like this
Component[] all_comp=mydialog.getComponents();
for(int i=0;i<=all_comp.length;i++)
{
Container ct=all_comp[i].getParent();
String panel_name=ct.getName();
}
i tried my best to find out all possible ways like taking all other functions of the component class. but no result. now i want to get the value of the buttons.(like button.getText). how to do that??
Upvotes: 1
Views: 2498
Reputation: 3994
What you really want to do is pass mydialog
into a method that will find all of the JButtons that are contained in it. Here is a method where if you pass in a Container
(JDialog
is a Container
) and a List
it will fill up the List
with all of the JButtons
the JDialog
contains regardless of how you added the JButtons
.
private void getJButtons(Container container, List<JButton> buttons) {
if (container instanceof JButton) {
buttons.add((JButton) container);
} else {
for (Component component: container.getComponents()) {
if (component instanceof Container) {
getJButtons((Container) component, buttons);
}
}
}
}
Basically this method looks to see if the Container
passed in is a JButton
. If it is then it adds it to the List
. If it isn't then it looks at all the children of the Container
and recursively calls getJButtons
with the Container. This will search the entire tree of UI components and fill up the List
with all JButtons
it finds.
This is kind of ugly to have to create a List
and pass it into the getButtons
method so we will create a wrapper method that looks nicer
public List<JButton> getJButtons(Container container) {
List<JButton> buttons = new ArrayList<JButton>();
getJButtons(container, buttons);
return buttons;
}
This convenience method simply creates your List
for you, passes it to our recursive method and then returns the List
.
Now that we have the recursive method and the convenience method we can call the convenience method to get a list of all of our JButton
s. After that we just loop over the items in the list and call getText()
or whatever else you want to do with your buttons:
for (JButton button: getJButtons(mydialog)) {
String text = button.getText();
...
}
Upvotes: 1
Reputation: 115368
You have to check whether current component is a button. If it is, cast it to button and call its getText()
:
Component[] all_comp=mydialog.getComponents();
for(int i=0;i<=all_comp.length;i++) {
if (all_comp[i] instanceof Button) {
String text = ((Button)all_comp[i]).getText();
// this is the text. Do what you want with it....
}
}
Upvotes: 1