How to update JTextArea in Java Swing? - java

I have a JComboBox named "jComboBox18" and a JTextArea "jTextArea11". Now I want that whenever a item is selected from the "jComboBox18" combo box its corresponding description is shown in the "jTextArea11" textarea.
I have added the appropriate listener to the JComboBox But the JTextArea is not showing any text. The code that I have written is as follows:
private void jComboBox18ItemStateChanged(java.awt.event.ItemEvent evt) {
Object item = jComboBox18.getSelectedItem();
if(item != null) {
ems.logic.Process selectedProcess = (ems.logic.Process)item;
jTextArea11.setText(selectedProcess.getProcessDescription());
jTextArea11.updateUI();
jTextArea11.revalidate();
jTextArea11.validate();
}
}
=====================EDITED===========================================
The method is being called for sure. I am changing the state of one more combobox
which is also being written in this method and its state changes successfully whenever item is selected from the "jComboBox18"

I think That should work. In fact, you should only need the setText() call. My guess is that you're function isn't getting called for some reason. Put a break point in your code and make sure it's getting called.

In the code shown your method is named as jComboBox18ItemStateChanged. Are you sure this method is being called. The ItemListener for a JComboBox should implement the interface ItemListener which declares that the subclasses should implement the below method.
void itemStateChanged(ItemEvent e);
How are you adding an instance of ItemListener to your JComboBox ?
EDIT:
After reading your edit and comments one another possiblity that I can think of is that:
you have a listener that is triggered when the textarea is updated and probably itis undoing the changes done in JComboBox listener.

Related

How delay populates second JComboBox until first JComboBox gets selected

I have 2 JComboBox, the second gets populates from Database after an item gets selected on first JComboBox. The problem is that the second jcombobox go to populate every time I type a letter. I want to make the second jcombobox wait until the item in first jcombobox gets complete entered.
private void jobCdItemStateChanged(java.awt.event.ItemEvent evt) {
if (evt.getStateChange() == ItemEvent.SELECTED
&& jobCd.getSelectedItem() != "Select..."
&& jobCd.getSelectedItem().toString().length() > 0) {
populatePartNoListFilter();
}
}
A little code would help to know exactly what you are doing but my guess is that your first combo is editable and you are populating the second combo using an event listener that's being called on every key stroke.
According to the documentation using an ActionListener when the combo is editable should work since:
The ActionListener will receive an ActionEvent when a selection has
been made. If the combo box is editable, then an ActionEvent will be
fired when editing has stopped.
If you are using an ActionListener but you still don't find the behavior fits your needs you could populate the second combo by adding a FocusListener on the first one and move the code that populates the second to its focusLost() method.
If this option doesn't suit your needs either, I recommend reading the documentation for the different available events, or give a detailed description of the behavior you are looking for so that someone might come up with a suggestion of the event handling you need to do.

How does the ActionListener work?

I found similar code to the following on Oracle's website. I stripped some irrelevant stuff regarding layout for space reasons.
private JTextField textField;
public class TextDemo extends JPanel implements ActionListener
{
public TextDemo()
{
textField = new JTextField(5);
//This causes a leaking this in constructor warning...
textField.addActionListener(this);
//code here for layout and to add the textfield to the panel
}
private static int ctr = 0;
#Override
public void actionPerformed(ActionEvent evt)
{
System.out.println(ctr++);
}
}
So I made a print statement to print and increment a counter to check when this actionListener is detecting an action.
I was wondering:
Is the only action that triggers this method the enter button?
In my constructor where I attached this to the action listener of the textField object, what exactly happens?
An action event occurs, whenever an action is performed by the user.
Examples: When the user clicks a button, chooses a menu item, presses Enter in a text field. The result is that an actionPerformed message is sent to all action listeners that are registered on the relevant component.
this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this
textField.addActionListener(this); // registering actionlistener
Capturing the action event
#Override
public void actionPerformed(ActionEvent evt)
{
System.out.println(ctr++); //perform some action on click
}
http://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html
As suggested by Hovercraft Full Of Eels you can also use annonymous inner class as below
textField.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
//do something
}
});
AFAIK, yes. The listener is called when enter is pressed while the textfield has the focus.
The current object, being constructed, is added to the list of ActionListeners of the text field, so that when enter is pressed in the text field, the current object's actionPerformed() method is called. It's generally a bad practice to pass an object not being fully constructed to another object, because the other object could call it back directly and the object wouldn't be functional, since not fully constructed yet.
First: Typically one uses a DocumentListener for a JTextField. It tells lots more interesting information about what is going on. It actually ties to the document (a sort of Model) that lies behind the GUI field.
Now:
Q1 - It's hard to figure out which mouse and keyboard actions cause the various events on the Swing screen components. As I remember, may be it for ActionPerformed. But there can be custom code added to a sub-class of a JTextField that causes an action event to fire for anything you want. You DO have to be careful if you do this.
Q2: The Listener object is stored in a list of all the objects that want to know when the text field has that action event occur. When it occurs, the text field calls the actionPerformed() method on all the objects in its listener list.
You might want to do some research on the Observer Pattern. That is the a name often used for bits of code that do this sort of thing. It can be used in many situations. The key is that it loosely couples the listener and the listenee (observer and observed). The object listening only has to tell the object to which it is listening that it want to be notified in certain cases. The object that is being listened-to keeps a list of all the various objects listening and what events they want to be informed of. That's all the connection and with the use of simple interfaces, it can be programmed simply.
Is the only action that triggers this method the enter button?
Yes. For JTextFields an ActionEvent is dispatched by pressing ENTER.
In my constructor where I attached this to the action listener of the textField object, what exactly happens?
You register the ActionListener with the component. When an ActionEvent is triggered it dispatches an ActionEvent where actionPerformed is invoked, passing it the details of the source object in the ActionEvent.
The preferred approach for the implementation of ActionListeners is to use a separate anonymous listener per component or a single concrete Action for shared functionality.

how to add a mouse listener to a JTable's cell holding a Boolean value rendered as checkbox

I have a JTable with a custom model implemented extending AbstractTableModel.
public abstract class AbstractTable extends AbstractTableModel{
public Class<? extends Object> getColumnClass(int c) {}
}
Because I've implemented the getColumnClass method, Boolean values are rendered in the table like checkboxes.
I would like to intercept checkbox's change of status but unfortunately I can't add directly a mouse listener, because I don't have a reference to the checkbox itself, which it isn't created by me.
How can I set a mouse listener to intercept the checkbox status change event?
EDIT:
#jzd answer is correct. I can catch the change in setValue method. But I would like to know how to implement a mouse listener based approach.
Particularly, I would like to avoid putting the logic inside setValue().
In this example of selectable values, the setValue() method is not overridden, except to update the internal data structure and fire the appropriate event. ValueEditor extends AbstractCellEditor and implements ItemListener, while ValueRenderer extends JCheckBox. In this way the editor can listen to the renderer's JCheckBox inside the editor's itemStateChanged().
Addendum: Adding a CellEditorListener is another approach, shown here for JTree. Note that JTable itself is a CellEditorListener.
I can't resist with #jzd advice really no, I think that not, not ensure me going throught TableMode#setValue,
but basically there are two options
1) TableModelListener
2) AFAIK only TableCellEditor#isCellEditable can do that in connections with JCheckBox or JRadioButton in JTable
public boolean isCellEditable(EventObject getEvent) {
MouseEvent me = (MouseEvent) getEvent;
JTable table = (JTable) (me.getSource());
Point point = me.getPoint();
int column = table.columnAtPoint(point);
int row = table.rowAtPoint(point);
Rectangle rec = table.getCellRect(row, column, true);
//...
}
Seems like adding a mouse listener is an extra step. I would suggest intercepting the change in the setValue() method of the model.
If you can't change the setValue() method then the next best thing is a CustomEditor that will block changes because this is not a good way to catch and hide the mouse click even from the default boolean editor.
I was having exactly the same problem, and I also know that you asked specifically for a mouse listener to the checkbox editor, but a workarround might be adding a TableModelListener as described here under the section "Listening for Data Changes", and try to simulate the behavior when you detect the change, but if you want to know when the mouse is over the checkbox or things like that < specific actions of the mouse >, I'm affraid that you'll have to make yout own implementation of a cell Editor, which implements those behaviors... At least thats what I would do...
Grettings!...

Java: JList ListSelectionListener only on MouseClick

I'm fairly new to Java, and have exhausted my Google'ing for this problem with selection on a JList component. I have a list of strings that dynamically change when the user clicks various JButtons. My JList selection mode is set to SINGLE_SELECTION, and the ListSelectionModel is registered to a custom ListSelectionChangeHandler that implements ListSelectionListener.
My problem is that every time the JList model's contents get modified (by clicking a JButton), the ListSelectionChangeHandler gets called and a NullPointerException occurs - e.g. The user has an item selected in the list, clicks a button, the list contents change, and the listener gets called. I want the ListSelectionListener to only perform some action when a MouseClick fires the event. How can I prevent my listener from firing when the model data gets modified?
Relevant Code:
this.suggestionsList = new JList();
this.suggestionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
ListSelectionModel model = this.suggestionsList.getSelectionModel();
model.addListSelectionListener(new ListSelectionChangeHandler());
class ListSelectionChangeHandler implements ListSelectionListener {
#Override
public void valueChanged(ListSelectionEvent arg0) {
Object selectedValue = suggestionsList.getSelectedValue();
// Perform action on selectedValue
// Enable/Disable components as needed
}
}
Thanks for the help!
The easiest way, of which I can think, is to make a switcher - boolean variable, that will be checked every time in your listener before it starts to really do something. Then you can start all of you modifications with switching this variable off. In case of multithreading, you may need some synchronization here.

Java - Why do component functions call actionPerformed?

In my code, two comboboxes are added to actionListener( this );
In another part of my code, I call a combobox function that sets an index to a certain value. This in turn calls actionPerfoemed again and so getSource == comboBox is true. Every time I call a set function it calls actionPerformed again, creating a stack of function calls that then unwinds down to the first.
Is there a way to prevent this?
If the problem is just the initial setting, you can defer adding the listener until after both have been initialized. There's more discussion here.
From the Swing tutorial,
Combo boxes also generate item events, which are fired when any of the items' selection state changes.
These events will be generated either when a user clicks on the items with the mouse, or when your software calls setSelectedIndex().
Perhaps you don't want your actionPerformed() method in this to be called when your software calls setSelectedIndex(). You may need a Boolean eventInitiatedBySoftware. In your main (this) class, you could say
synchronized(eventInitiatedBySoftware) {
eventInitiatedBySoftware=true;
comboboxeditor.setSelectedIndex(n);
}
and then in your listener:
public void actionPerformed(ActionEvent ae) {
synchronized(eventInitiatedBySoftware) {
if (eventInitiatedBySoftware) {
eventInitiatedBySoftware=false; // clear your flag.
return; // don't want to process this event.
}
// the rest of your method goes here
}
When your software wants to adjust the value, it will set the Boolean to true. The actionPerformed method will be called, but your test will realise that this event was initiated by the software, and return before doing any of your existing code. It will clear the Boolean, so that if a user now uses the mouse to perform a selection action, your code will realise that it wasn't softwareInitiated.
BTW, It's possible that you misunderstand the event concept. For example, I suspect you are actually adding "this" as an event listener for each combobox, rather than adding comboboxes as listeners to "this". You might like to look at the Writing Event Listeners trail.

Categories

Resources