I am stuck with Jlist and never thought that Jlist can be that complicated.
With a left mouse click on Jlist item I want to do some action. I know that i need action listener but I was not able to get it work.
In my specific case there are saved paths to .sql files in JList. When I click on item in JList I want to read from that file and save it to JTextArea.
Maybe I am putting listener on wrong place in code? Or I am coding wrong?
Model Name = model
JList Name = SQLScriptList
Jtextarea Name = SQLEditor
With this code I tried to save item from the list in specific label or textbox just to see if action work.
//Copy from LIST to TextArea
MouseListener mouseListener = new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 1) {
String selectedItem = (String) SQLScriptList.getSelectedValue();
// add selectedItem to your second list.
DefaultListModel model = (DefaultListModel) SQLScriptList.getModel();
if (model == null) {
//model = new DefaultListModel();
SQLScriptList.setModel(model);
}
model.addElement(selectedItem);
}
SQLScriptList.addMouseListener(mouseListener);
}
//list.addMouseListener(mouseListener);
};
Solved
Here is solution that worked in my case:
private void SQLScriptListMouseClicked(java.awt.event.MouseEvent evt) {
JList list = (JList) evt.getSource();
if (evt.getClickCount() == 2) {
int index = list.locationToIndex(evt.getPoint()); //GET INDEX 0,1,2,3
try {
FileReader reader = new FileReader(files[index]);
SQLEditor.read(reader, files[index]); //Object of JTextArea
} catch (Exception e) {
e.printStackTrace();
}
}
}
When I click on item in JList I want to read from that file and save it to JTextArea.
Normally this is not done on a single mouse click.
Typically the Action is invoked when the user:
uses the Enter key, or
double clicks on the item
For this type of processing check out List Action which allows you to provide an Action to be invoked in either of the above situations.
Otherwise you should use a MouseListener, not a ListSelectionListener as suggested in the comments above, since the user should be able to navigate through the items in the list using the down/up arrow keys without causing the action to be invoked. Read the section from the Swing tutorial on How to Write a MouseListener for working examples.
Related
I want to update JComboBox when I type in the JComboBox editor. It will get the text of JComboBox editor in real time and add some items based on the text. I have tried like this:
final JTextField tfListText = (JTextField) comboBox1.getEditor().getEditorComponent();
tfListText.addCaretListener(new CaretListener() {
private String lastText;
#Override
public void caretUpdate(CaretEvent e) {
String text = tfListText.getText();
if (!text.equals(lastText)) {
lastText = text;
comboBox1.removeAllItems();
// get some items based on text
comboBox1.addItem(someItems1);
...
}
}
});
However, the selected item of JComboBox was changed when using method removeAllItems() or addItem(), and it caused an endless loop triggering the CaretListener again.
So how to update JComboBox without selected item being changed, or is there any other way to add items based on the input content in real time
I have a class that extends BasicTabbedPaneUI and does some paint component overriding.
I want to be able to add a addMouseListener to the class I use it in to check when the user selects a tab the current tab index and the previous tab index.
NOTE: The user is able to navigate to tabs via the keyboard and not just clicking on a tab and I want to be able to make sure the previous index tracks this. So in the example below preIndex would equal the previous index regardless to whether the user navigated to it via the keyboard or mouse.
Any ideas please?
tabbedPane.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
JTabbedPane tabP = (JTabbedPane) e.getSource();
int currIndex = tabP.indexAtLocation(e.getX(), e.getY());
int prevIndex = ?????
}
});
Many thanks!!!!
I would use the change listener instead of mouse listener (it's called in both cases: for mouse and key event triggered tab change). If you cannot determine previously selected tab you can use following approach: save currently selected tab index as client property of the tabbed pane.
private static final String OLD_TAB_INDEX_PROPERTY = "oldTabIdx";
tabbedPane.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
JTabbedPane tabP = (JTabbedPane) e.getSource();
int currIndex = tabP.getSelectedIndex();
int oldIdx = 0;
Object old = tabP.getClientProperty(OLD_TAB_INDEX_PROPERTY);
if (old instanceof Integer) {
oldIdx = (Integer) old;
}
tabP.putClientProperty(OLD_TAB_INDEX_PROPERTY, currIndex);
// now we can use old and current index
}
});
I have this bug, after populating the JList, I try to retrieve the value of the selected item. But when I am doing it, it is called twice.
Here is my code :
public CaveAdventureUI(CaveGame game) {
initComponents();
playerCarryItemModel = new DefaultListModel();
caveCarryItemModel = new DefaultListModel();
this.caveGame = game;
this.world = game.getCaveWorld();
listSelectionModel = this.jListCaveCarryItems.getSelectionModel();
listSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
this.listSelectionModel.addListSelectionListener( new SharedListSelectionHandler());
//for debug purpose,see the world grid in console
game.drawCaves();
//new JComboBox(Mood.values());
createGridQuarePanels();
//world.startGame(GameLevel.Beginner);
update();
}
private class SharedListSelectionHandler implements ListSelectionListener {
public void valueChanged(ListSelectionEvent listSelectionEvent) {
ListSelectionModel lsm = (ListSelectionModel)listSelectionEvent.getSource();
if (!lsm.isSelectionEmpty()) {
Occupant opt = mapOccupants.get(Integer.toString(jListCaveCarryItems.getSelectedIndex()));
System.out.println("selected index :" +jListCaveCarryItems.getSelectedIndex() +"[["+opt.getName()+"]]");
}
}
}
In the above code, when I am making selection on jList : jListCaveCarryItems, it triggers the SharedListSelectionHandler class. However, when I am clicking on the JList, it print out the selected value twice.
Can anyone help me to figure it out?
Thanks & Regards,
2 ListSelectionEvents are dispatched when the JList is selected—one during and another after the selection event. From How to Write a List Selection Listener
The isAdjusting flag is true if the user is still manipulating the selection, and false if the user has finished changing the selection.
Therefore, ensure that the ListSelectionEvent value is not adjusting.
public void valueChanged( ListSelectionEvent listSelectionEvent) {
if ( !listSelectionEvent.getValueIsAdjusting() && !lsm.isSelectionEmpty()) {
Occupant opt = ...
...
}
}
I have 2 comboboxes and a spinner, that work like this: if the selected item of the first combo is changed, the second combo keeps its selected item but re-calls the spinner (the spinner is linked only to the second box). My problem is that I can't trigger the stateChange listener of the spinner when I do this.
Here is the code for forcing the second box to reselect its last item when the first one is changed (nothing wrong here, it works just fine):
String orientare = (String) orientareComboBox.getSelectedItem();
orientareComboBox.setSelectedItem(orientare);
This is the code for the second box actionListener:
public void actionPerformed(ActionEvent e) {
JComboBox combo = (JComboBox) e.getSource();
String value = combo.getSelectedItem().toString();
if (value.equalsIgnoreCase("oblica"))
{
unghiSpinner.setEnabled(true);
double unghi = (double) unghiSpinner.getValue();
unghiSpinner.setValue(new Double(unghi));
}
}
And the spinner's Listener:
public void stateChanged(ChangeEvent e)
{
if (unghiSpinner.isEnabled())
{
// do something
}
}
I do not know what command I should use for unghiSpinner to trigger its listener, because setValue() can't do it.
I don't see you changing the value of your JSpinner in the code above. It appears that all you do is set the spinner's value to the same value that it held previously, and that shouldn't trigger the listener. To trigger a change listener to fire you must change the state of the observed entity.
I'm writing a gui program and have an AbstractAction for a Jbutton that opens a file. In a JComboBox I have a list of the files that have been opened. The AbstractAction for the JComboBox will change back to any of the files that have been opened. When I update the list for a JComboBox though the action fires.
So when I actually open a file the JComboBox action fires, and when I use the JComboBox the action fires once, then a second time when updating.
Is there a way i can stop the event when just updating the JComboBox list?
Thanks in advance
The answer is in the design, particularly in separation of concers: don't think view-with-two-actions, instead think many-views-change-state-of-single-data.
In pseudo-code something like:
// data class
public class MyOpenFilesBean {
private File currentFile;
public void setCurrentFile(File current) {
File old = getCurrentFile();
this.currentFile = current;
firePropertyChange("currentFile", old, getCurrentFile());
}
public File getCurrentFile() {
return currentFile;
}
}
// view wiring (view --> data)
Action open = new AbstractAction(...) {
public void actionPerformed(...) {
File choosenFile = // grab it from whereever in the view
myOpenFileBean.setCurrentFile(choosenFile);
}
};
myButton.setAction(open);
myComboBox.setAction(open);
// view wiring (data --> view)
PropertyChangeListener l = new PropertyChangeListener() {
public void propertyChanged(...) {
if ("currentFile".equals(evt.getPropertyName()) {
// a method implemented to update f.i. the combo selection
updateView((File) evt.getNewValue());
}
}
};
myOpenFileBean.addPropertyChangeListener(l);