I'm making a simple GUI where the user can select an item from a list of Strings using the JList<String> component, and I want my program to update a JTextField with some data describing the selected item. I know I need an event listener, but I'm confused as to what I should use to detect a change in selection in my list.
You need to add it to the JList object:
myJList.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
System.out.println("Hello you selected me! "
+ dataList.getSelectedValue().toString());
}
});
Related
I'm making a To-Do List application and I have a PrimaryList frame and a SubList frame. When a user selects something from the PrimaryList (Grocery...or something like that) and then hits a forward arrow JButton, it is supposed to launch up the SubList frame. Now here is what I have for the actionPerformed method of the forward arrow button called btnArrow.
private void btnArrowActionPerformed(java.awt.event.ActionEvent evt) {
lstToDoLists.addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent e){
if (lstToDoLists.getSelectedIndex() > 0){
btnArrow.addActionListener(new ActionListener(){
public void actionPerformed (ActionEvent ae){
if (btnArrow==ae.getSource()){
SubList sublist = new SubList();
sublist.setVisible(true);
}
}
});
}
}
});
}
Now, when I run the PrimaryList file and click on an item in my JList and then select the forward arrow button, I get nothing. But then when I click another element from the list and press the forward arrow button again, my SubList pops up twice.
Something isn't write with what I've written and I am hoping someone else will know how to fix this problem.
You're adding listeners inside of listeners -- something that you don't want to do, since this means that new listeners will be added, each time an event occurs.
Solution: don't add listeners inside of other event listeners but rather add the listeners once and in your code's constructor or initialization method.
Note that I would not use a ListSelectionListener at all. Instead I'd just use a single ActionListener on the button. Then in that listener, get the list's selection and use it.
e.g.,
private void btnArrowActionPerformed(java.awt.event.ActionEvent evt) {
// if list contains String:
String selectedItem = (String) lstToDoLists.getSelectedItem();
// check that selectedItem isn't null, i.e,
if (selectedItem != null) {
// TODO: do something with selection here
}
}
As a side recommendation, please look at The Use of Multiple JFrames, Good/Bad Practice?.
I have a JComboBox. I would like it to work so that if a certain item is selected ("Other"), immediately, several more items are displayed in the same combo box (something like a submenu, but inside the combo box). I'm having a devil of a time getting this to work.
Does anyone have any ideas on how to do this?
EDIT: misunderstood your question!
I assume that you are clicking on an item in the JComboBox? Than simply add this code
comboOther.addActionListener (new ActionListener () {
public void actionPerformed(ActionEvent e) {
comboOther.addItem("new item 1");
comboOther.addItem("new item 2");
comboOther.addItem("new item 3");
// more
}
});
I'd like to add to a database, and my editable comboBoxModel when I enter a new name into the comboBox. I have the method for adding to the database down fine, I'm just trying to get it to somehow listen to an entry being added to the ComboBox.
What's the Best way to do this?
I've read the Java tutorial on Editable ComboBoxes, and noted where it said:
An editable combo box fires an action event when the user chooses an item from the menu and when the user types Enter. Note that the menu remains unchanged when the user enters a value into the combo box. If you want, you can easily write an action listener that adds a new item to the combo box's menu each time the user types in a unique value.
So I thought to myself, ok lets try this, and looked up some examples. Here is my attempt, essentially copy pasted out of the example I found, with my variable names:
playerNameComboBox.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("comboBoxEdited")) {
System.out.println("Adding new player!");
IController.Util.getInstance().addNewPlayer();
playerNameComboBox.insertItemAt(playerNameComboBox.getSelectedItem(), 0);
}
}
});
When I type in a new name, and press enter, it does nothing. No new database entry and no addtional option on the ComboBox. I haven't attached an action command to the ComboBox as I thought the example above assumed it would have that as default, and so did I.
But how do I get it to shout out that action command when I press enter, with the focus on the comboBox? I would have thought that comboBoxes would have had some sort of default behaviour to shout that out? Do I need to use an if(playerNameComboBox.hasFocus()) statement? Should I implement some kind of keylistener when my comboBox hasFocus()?
I'm very new at Java, so I'm unsure as to how this sort of thing should be done; any help is very much appreciated.
As requested, here is my short example in which names may be added to a JComboBox.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Test extends JFrame {
private JComboBox box;
public static void main(String[] args) {
new Test();
}
public Test()
{
super();
setSize(200, 100);
setDefaultCloseOperation(EXIT_ON_CLOSE);
box = new JComboBox();
box.setEditable(true);
getContentPane().add(box);
box.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("comboBoxEdited")) {
System.out.println("Adding new player!");
box.insertItemAt(box.getSelectedItem(), 0);
}
}
});
setVisible(true);
}
}
I'm quite new to Java Swing. And I'm stuck on trying to add a ListSelectionListener on a JComboBox instance. It seems only the ListSelectionModel interface has addListSelectionListener method. I kind of cannot figure it out...
Why I want to do add it is that I want program do something even the item in the combo box is not changes after selecting.
POTENTIAL ANSWER
I was simply thinking of attaching an actionListener on combobox not working. and i think it's bug of openjdk. I've reported it here
Thanks in advance.
Take a look at JComboBox#addItemListener:
JComboBox combo = createCombo();
combo.addItemListener(new ItemListener()
{
#Override
public void itemStateChanged(ItemEvent e)
{
if (e.getStateChange() == ItemEvent.SELECTED)
{
Object selectedItem = e.getItem();
// Do something with the selected item...
}
}
});
This event is fired for both mouse and keyboard interaction.
For JComboBox, you'll have to use ActionListener.
JComboBox jComboBox = new JComboBox();
jComboBox.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("combobox event");
}
});
AFAIK, actionPerformed is raised whenever the user makes a selection for the JComboBox even if it's the same item that was already selected.
It depends on your requirement. The ActionEvent is only fired when the keyboard is used, not when the selection changes as the mouse is moved over the items.
If you want to do some action when the item selection changes even if the mouse is moved then yes you will probably need access to the JList. You can access the JList used by the popup with the following code:
JComboBox comboBox = new JComboBox(...);
BasicComboPopup popup = (BasicComboPopup)comboBox.getAccessibleContext().getAccessibleChild(0);
JList list = popup.getList();
list.addListSelectionListener(...);
Use a PopupMenuListener. When the popup menu closes get the selected index and do your processing.
I've tried using getInputMap() + getActionMap() on a JComboBox and it seems to have no effect.
I've tried addActionListener() / addItemListener() on a JComboBox and I can't seem to distinguish a change of selection from someone pressing the Return/Enter key.
Any suggestions? In my application, I want the Return/Enter key to be stronger than just selecting, it's a selecting + applying action.
Here's my code to setup the key binding. It works fine (e.g. note("hit ENTER") is called) when component is a JList, but doesn't work when component is a JComboBox.
private void setupApplyProfile(final JComponent component, final MyComboBoxModel mcbm)
{
String enterAction = "applyItem";
KeyStroke enterKey = KeyStroke.getKeyStroke("ENTER");
component.getInputMap().put(enterKey, enterAction);
component.getActionMap().put(enterAction, new AbstractAction()
{
#Override public void actionPerformed(ActionEvent e) {
note("hit ENTER");
applySelectedProfile(mcbm);
}
});
}
Aha, this seems to work: note("cb editor action") gets called when I hit Enter in the combo box field.
comboBox.getEditor().addActionListener(new ActionListener() {
#Override public void actionPerformed(ActionEvent arg0) {
note("cb editor action");
}
});
In my application, I want the Return/Enter key to be stronger than just selecting, it's a selecting + applying action.
If I understand the question you can use the following:
comboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
The ActionEvent and ItemEvents will only be fired when an item is selected from the drop down list when you use the mouse or the enter key. The eEvents will not be fired if you navigate the drop down list using the up/down arrow keys.