I have a JList which is a list of names and I want to print out any item that I select from the list. It sounds simple but I do not know how to do it. Here is my code:
final DefaultListModel<String> myNamesList = new DefaultListModel<String>();
final JList list = new JList(myNamesList);
final Object chosenName = list.getSelectedValue();
list.addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent e) {
System.out.println(chosenName);
}
});
Make sure the
Object chosenName = list.getSelectedValue();
line is within the valueChanged() method. Otherwise it will always be the initial selected value.
Related
first post here.
How to write method which can change values in JTable when app is on running? getValIn() returns me values in english (i used ResourceBundle for that and its work), but if i change the combobox I want have this value in french in JTable.
It's a piece of code.
public void show(){
String[] lang = {"en", "fr"};
List<String> columns = new ArrayList<String>();
Object[][] obj;
JComboBox combobox = new JComboBox(lang);
combobox.setSelectedIndex(0);
combobox.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
if(combobox.getSelectedItem().toString().equals("en")){
selectedLang ="en";
}else{
selectedLang = "fr";
}
}
});
obj = getValIn(selectedLang);
TableModel tb= new DefaultTableModel(obj, columns.toArray());
JTable table = new JTable(tb);
It's not necessary to be in JCombobox.
Thanks, have a nice day!
I got a quite tricky problem when I do some code on JTable
I need to add one line In JTable when I click "Add" button, and I want one of the columns to render
as a JComboBox
the problem is that when I only add one line, it works fine.
but when I add multiple lines a time, no matter which combobox I choose item from, It will always trigger the last comboBox's event(seems always the same combobox since I have printed the hashcode of jComboBox in MyComboxActionListener class. it's the same).
why is that happens , I can't figure it out. Since It's totally a new comboBox and a new listener when I add one line.
Following is the code.
Thanks in advance.
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {
ProducedProcedure_new addedProducedProcedure = new ProducedProcedure_new(); // the new item
componentProcedureTableModel.getWorks().add(addedProducedProcedure); //add one line to the table
componentProcedureTableModel.fireTableRowsInserted(componentProcedureTableModel.getRowCount()-1, componentProcedureTableModel.getRowCount()-1);
jTable1.changeSelection(componentProcedureTableModel.getRowCount()-1,0, false, false);
List<String> procedureNames = produceCardManager.getProcedureNames(componentIdTextField.getText().trim(),false); //get the items added to combobox
renderColumnAsCombox(1,procedureNames,addedProducedProcedure); //-------------------------------------------
}
void renderColumnAsCombox(int columnIndex , List<String> items,ProducedProcedure_new producedProcedure) {
TableColumn col = jTable1.getColumnModel().getColumn(columnIndex);
JComboBox comboBox = new JComboBox();
for(String item : items) {
comboBox.addItem(item);
}
MyComboxActionListener myComboxActionListener = new MyComboxActionListener(columnIndex,comboBox,producedProcedure);
comboBox.addActionListener(myComboxActionListener);
col.setCellEditor(new DefaultCellEditor(comboBox));
}
class MyComboxActionListener implements ActionListener { // listen for the select event of the combobox
private JComboBox jComboBox;
private ProducedProcedure_new producedProcedure;
private int columnIndex;
public MyComboxActionListener(int columnIndex,JComboBox jComboBox,ProducedProcedure_new producedProcedure) {
this.columnIndex = columnIndex;
this.jComboBox = jComboBox;
this.producedProcedure = producedProcedure;
}
#Override
public void actionPerformed(ActionEvent e) {
String selectedItem = (String)jComboBox.getSelectedItem();
producedProcedure.getProcedure().setProcedureName(selectedItem);
producedProcedure.getProcedure().setProcedureId(String.valueOf(produceCardManager.getProcedureId(selectedItem)));
producedProcedure.getProcedure().setFactor(produceCardManager.getProcedureFactor(selectedItem)); //automately update the factor
((ComponentProcedureTableModel_new)jTable1.getModel()).fireTableDataChanged();
}
}
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 need to put the following array into a JComboBox and then store the selected value when the "Submit" button is clicked.
listOfDepartments = new String[5];
listOfDepartments[0] = "Mens Clothing";
listOfDepartments[1] = "Womens Clothing";
listOfDepartments[2] = "Childrens Clothing";
listOfDepartments[3] = "Electronics";
listOfDepartments[4] = "Toys";
//Department: ComboBox that loads from array
// Store values
JButton buttonSubmit = new JButton();
buttonSubmit.setText("Submit");
container.add(buttonSubmit);
buttonSubmit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
//store value from combobox in a variable
}
});
First, create a model...
DefaultComboBoxModel model = new DefaultComboBoxModel(listOfDepartments);
comboBox.setModel(model);
Second, get the selected value when the actionPerformed event is raised...
String value = (String)comboBox.getSelectedItem();
Take a look at How to Use Combo Boxes for more details.
I'm making a swing based application where I have a JList that periodically get's updated with different orderings of the same data, gets infrequently updated with new items, and also infrequently updated with less items. I'm trying to figure out the best way to make this look good. Right now, I just call
JList.setListData(String [] data);
Which doesn't look too great, and it clears the selected items.
I want a way to update it that only clears the selected items if it was removed from the list, but otherwise keeps the same items selected, even if their index changes. I was looking into keeping track of which indexs are selected and then setting the selected items after changing the data but that sounds horrible. I also looked at ListModels and keeping track of my own but it seems that which items are selected is kept in the JList itself so that wouldn't work perfectly either.
I'd really appreciate any suggestions.
I made you a working example.
I've used the JList like you requested, added buttons that resort, add, and delete from the list.
Anyways, hope this helps!
Cheers.
public class Test {
private static String selectedValue = null;
private static JList jList = new JList();
public static void main(String args[]) {
JFrame jFrame = new JFrame();
jFrame.setSize(500, 500);
jFrame.setLocationRelativeTo(null);
jFrame.setLayout(new GridLayout(4, 1));
jList = new JList(new String[]{"1", "2", "3", "4", "5"});
jFrame.add(jList);
JButton rearrangeButton = new JButton("rearrange");
rearrangeButton.addActionListener(new Test().new SelectedListener());
jFrame.add(rearrangeButton);
JButton addButton = new JButton("add");
addButton.addActionListener(new Test().new SelectedListener());
jFrame.add(addButton);
JButton deleteButton = new JButton("delete");
deleteButton.addActionListener(new Test().new SelectedListener());
jFrame.add(deleteButton);
jFrame.setVisible(true);
}
private class SelectedListener implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
storeSelected();
if (actionEvent.getActionCommand().equalsIgnoreCase("rearrange")) {
jList.setListData(new String[]{"5", "4", "3", "2", "1"});
} else if (actionEvent.getActionCommand().equalsIgnoreCase("add")) {
List< String> items = new ArrayList< String>();
for (int item = 0; item < jList.getModel().getSize(); item++) {
items.add(jList.getModel().getElementAt(item).toString());
}
items.add("new");
jList.setListData(items.toArray());
} else if (actionEvent.getActionCommand().equalsIgnoreCase("delete")) {
List< String> items = new ArrayList< String>();
for (int item = 0; item < jList.getModel().getSize(); item++) {
items.add(jList.getModel().getElementAt(item).toString());
}
items.remove(0);
jList.setListData(items.toArray());
}
reSelect();
}
}
private static void storeSelected() {
if (jList.getSelectedIndex() > -1) {
selectedValue = jList.getSelectedValue().toString();
} else {
selectedValue = null;
}
}
private static void reSelect() {
if (selectedValue != null) {
jList.setSelectedValue(selectedValue, true);
}
}
}
It seems the standard JList has no methods to adjust the sorting (why on earth did they only added that to a JTable ...), but there is a tutorial for sorted lists