Get text property from a Component - java

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?

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

Related

How to get text in two layered component

Please I hope that do not hurt your eyes after see the one... so sorry..
I want to get a text as I mentioned above.
Let's have a look at my terrible drawing...
What I want to do is :
I want to get the text from the yellow highlighed box.
I designed my program that I need to get few like the above. I used getComponentCount() to check how many labels there are. It is showing correctly and then I used getComponent(int n) , n = 0, and I was looking for getText().. but there is not.
Always thank you.
Your design is ok.
getComponent() returns a Component rather than a Label.
You just need to specifically cast it back as a Label:
String text = null;
Component c = panel.getComponent(i);
if (c instanceof Label)
text = ((Label)c).getText();
MVC Approach:
A more OO solution would be to separate your model (data) from the view (drawing).
You could create a new model Class, let's say "DrawingModel".
Then provide get()/set() for every property in the model.
You then connect both by drawingView.setModel(drawingModel).
When you need any data component, you can access or set it from DrawingModel class rather than directly from the View.
The component who actually "drives" the application is called the Controller.
The approach is an architectural pattern called Model-View-Controller (or MVC in short).
You can learn more here and here.

Java swing - creating text field on button's place

When specific action is performed, I want to replace button with text field. I know that I have to call button1.setVisible(false); but I don't know how to create text field on the exact same place. I am using NetBeans designer, if you can give me a hint, how to add 2 components at same place, and switch between then, something like switching between layers in photoshop, if something like that is possible, would be great. Thanks
For many components in one space, use a CardLayout as see in this short example.

GWT 2 ButtonCell in one row Adding Event

could someone help me. I'm new to gwt and maybe this is so simple. but I can't seem to figure this out...
I create 2 button for a row in a celltable, each with this method:
protected void addButtonColumn(String header, final IHasValue<Row, Button> hasVal){
Column<Row, String> column = new Column<Row, String>(new TextButtonCell()) {
#Override
public String getValue(Row object) {
return ((Button)hasVal.getValue(object)).getText();
}
};
column.setFieldUpdater(new FieldUpdater<Row, String>() {
#Override
public void update(int index, Row object, String value) {
((Button) hasVal.getValue(object)).click();
}
});
table.addColumn(column, header);
}
I want each button to something different when clicked, but it doesn't work. i know that i should do something in setfieldupdater but i don't know what.
Your use of the TextButtonCell to contain a Button (i.e. a widget) doesn't really make a lot of sense - wouldn't it be easier to let the cell have access to the data, and use the ValueUpdater to trigger some kind of behavior based on that data directly?
Cells are not widgets - they are much simpler than widgets. This chiefly means two things: they are faster to draw, and stupider. Both of these things are as a result of a single cell instance being used to draw many pieces of data in slightly different ways. If you are going the effort of building a button per element, it doesn't make sense to use a cell-based widget then - you are nearly drawing everything twice, and getting the worst of both worlds (slow code, that is hard to work with).
Don't use a Button with ClickHandlers attached, but some other abstraction to deal with clicks, like a Command instance for each row, or even better, some kind of handler that accepts the row instance clicked. It might even make sense to have a FieldUpdater instance passed in as a parameter for your method (and maybe make the IHasValue generic on String instead of Button, so your models don't need to wrap widgets).
(This may not be answering your question directly, but is instead hopefully helping shed some light on why we use cells at all, and how to best write code that takes advantage of cells.)

How to increase the height of Textarea in jtable dynamically

I have a standalone application in which I have a Jtable. In my table, when I type the text, the height of the Textarea should increase dynamically with the text. How can I do this?
Can someone help me with an example how to do this?
Thanking You
Chaithanya
It wasn't clear from your question - are you using a JTextArea or a TextArea? The reason it's ambiguous is people generally don't mix and match the light and heavy-weight frameworks (e.g. put awt components within a swing component).
If it's a JTextArea, I think your best bet is probably to use a DocumentListener.
DocumentListener myListener = ??;
JTextArea myArea = ??;
myArea.getDocument().addDocumentListener(myListener);
http://java.sun.com/docs/books/tutorial/uiswing/components/generaltext.html#doclisteners
I think what you'll need to do is listen for changes, and whenever something is added to the file, call the getLineCount() method, and compare it with the getRows() method. If it's broken the threshold, then use a setRows() call to increase the number of rows.
Will probably need to file some sort of UI change, especially to propagate up to the JTable.

Reset/remove a border in Swing

Here's a very specific coding question:
I've recently been asked to maintain some old-ish Java Swing GUI code at work and ran into this problem:
I've attached my own subclass of InputVerifier called MyFilenameVerifier to a JTextField (but it may as well be any JComponent for these purposes). I've overridden the verify() method such that it calls super.verify(input) (where input is the JComponent parameter to verify()). If super.verify(input) comes back false, I do:
input.setBorder(BorderFactory.createLineBorder(Color.RED));
This is a convention used throughout the UI of this application that started long before me, so I don't have a lot of choice as far as using other ways to get the users attention (wish I did). This is just the way it works.
Problem is, once the user goes back and types something valid into the text field, I need a way to set it back to default border (instead of just saying set it to Color.GRAY or whatever, which is a different color from its original border). I need a way to say, "remove the extra decoration and go back to normal" or just set the border to its default, in other words.
Couldn't you just call input.getBorder() and cache it somewhere before setting the border to red?
Or without caching anything, you could tell the JComponent to update its UI back to the look and feel's defaults via component.updateUI. That should make the component reset its colors, borders, fonts, etc to match the original settings.
input.getBorder()
Wouldn't it be awesome if no one ever saw this and I got away free without the ass-beating I deserve for asking this question?
Not sure how your system is build, but I think you can store the original border before changing it. So you can change it back later
// assuming the Border was not null before
if (!super.verify(input)) {
original = input.getBorder();
input.setBorder(...);
} else {
if (original != null) {
input.setBorder(original);
original = null; // not needed
}
}
You need to preserve the existing border when you change it.
One way to do this is to use the methods putClientProperty() and getClientProperty(), which you'll find documented in the API.
Another possibility, if there are only a few input widgets you need this for is to subclass, e.g. JTextField, add setBorderOverride() and modify getBorder() to return "overriddingBorder" if it is not null.
Then you just use setBorderOverride(redBorder) to make it red and setBorderOverride(null) to clear it.
This of course depends on the painting to use getBorder(), which it may or may not do, and which may be implementation specific.
Incidentally, you only need a single static reference to the border-- it's the selfsame border instance used by all JTextFields.

Categories