Reputation: 690
I have a JPanel
called panelCreatePuzzle
with 100 JButton
's.
I used
Component[] cells = panelCreatePuzzle.getComponents();
To get an array of all the buttons. Now I want to print the text of each button. I have no clue how to do this. I tried the following:
for (Component cell:cells){
System.out.println(cell.toString());
}
Which does print something containing the text:
javax.swing.JButton[,321,321,30x30(...),text=here is the text,defaultCapable=true]
I can of course extract it from this string, but is there a more direct way that just gives me the text without anything else?
Upvotes: 0
Views: 490
Reputation: 347194
There are better ways to achieve what you're trying to do, but...
for (Component cell:cells){
if (cell instanceof JButton) {
JButton btn = (JButton)cell;
String text = btn.getText();
}
}
Basically, you need to determine if the component is actually a JButton
or not and if it is, you can then safely cast it and work with it.
This is limited and a little brute force. A better approach might be to supply a getter which return an array of the buttons which represent the cells (rather then looking at all the buttons, which might include things you don't want).
Probably the best solution though, is to use some kind of model, which represents the current state, which can then be used to displayed through the UI and manipulated in what ever form you want in a de-coupled manner.
This reaches into a large array of concepts, including "model-view-controller" and "observer pattern", concepts which you should take the time to investigate and learn
Upvotes: 2