Java - updating textFields from JList - java

I am making an address book GUI with Java and I have a JList that displays all the names of the people in my ArrayList (this is populated by the updateinfo method mentioned below). I want it so when I click an item on the JList, the TextFields are then updated with that persons details. Before I have only used buttons and therefore actionListeners. I think I understand that a JList must use ListSelectionListener but I cannot seem to implement this. I have added a snippet of my code below. Can somebody please help?? For continuity with my actionlisteners I would like to have it as an inner class but this is not vital
JList jl;
DefaultListModel list;
list = new DefaultListModel();
this.jl = new JList(this.list);
//add ListSelectionListener????
updateList();
this.add(this.jl, layout);

You can add the listener and then just query the currently selected index.
I did a sample for you, I hope you find it useful.
This is the relevant section:
private JComponent list() {
final JList list = new JList( data);
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
int i = list.getSelectedIndex();
nameTextField.setText( i >= 0 ? data.get( i ) : "" );
}
});
return new JScrollPane( list );
}
Bear in mind that's not the only way to go, this is just an starting point for you.
Here's the complete working sample:
import java.util.Vector;
import java.util.Arrays;
import java.awt.BorderLayout;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JLabel;
import javax.swing.JComponent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;
public class JListSample {
private Vector<String> data = new Vector<String>(
Arrays.asList( new String [] {
"one", "two", "three"
})
);
private JTextField nameTextField;
public static void main( String [] args) {
JListSample s = new JListSample();
s.run();
}
public void run() {
JFrame frame = new JFrame("Selection test");
frame.add( list(), BorderLayout.WEST );
frame.add( editPanel() );
frame.pack();
frame.setVisible( true );
}
private JComponent list() {
final JList list = new JList( data);
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
int i = list.getSelectedIndex();
nameTextField.setText( i >= 0 ? data.get( i ) : "" );
}
});
return new JScrollPane( list );
}
private JComponent editPanel() {
JPanel panel = new JPanel();
panel.add( new JLabel("Name:") );
nameTextField = new JTextField(10);
panel.add( nameTextField );
return panel;
}
}
This is what is displayed:
sample http://img177.imageshack.us/img177/6294/capturadepantalla200911k.png

You just add the selection listener to the list, like that:
jl.addSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
// evaluate e if necessary and call a method
// in your class to write the text in the textfield
int selectedRow = e.getFirstIndex(); // more complicate for multiselects
updateTextFieldWithName(selectedRow); // to be implemented
}
});
Using an anonymous class like here is the quickest way. It's a bit hard to read but a typical pattern.
(just read you preferred an inner class, but I can't code that here on the fly with no IDE at hand...)

Yes you will want to use a ListSelectionListener for this, you will also probably want to set the list to single selection(ListSelectionModel.SINGLE_SELECTION). This will allow the user to only select one item in the list. You can then add you listSelectionListener, and in the valueChanged of the event do something like the following(not exact syntax).
valueChanged(ListSelectionEvent e){
int idx = e.getFirstIndex();
int idx2 = e.getLastIndex(); //idx and idx2 should be the same if you set SingleSel
if(idx==idx2){
//here you can get the person detail however you have them stored. You can get them from the model like so,
Object personObj = MYLIST.getModel().getElementAt(int index);
}
}

I think I understand that a JList must
use ListSelectionListener but I cannot
seem to implement this
Well, then start by reading the JList API. You will find a link to the Swing tutorial on "How to Use Lists", which contains a working example.
Also in the tutorial you will find a section on "How to Write a List Selection Listener" which contains a second example.
Start with the tutorial for your basic questions.

Related

I wanted to add ItemListener for jList but i m unable to do so ,suggest me how can i add itemListener for listbox [duplicate]

I have a JList, where i am displaying some ID's. I want to capture the ID the user clicked and dis play it on a JLabel.
String selected = jlist.getSelectedItem().toString();
The above code gives me the selected JList value. But this code has to be placed inside a button event, where when i click the button it will get the JList value an assign it to the JLabel.
But, what i want to do is, as soon as the user clicks an item of the JList to update the JLabel in real time. (without having to click buttons to fire an action)
A simple example would be like below using listselectionlistener
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class JListDemo extends JFrame {
public JListDemo() {
setSize(new Dimension(300, 300));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
final JLabel label = new JLabel("Update");
String[] data = { "one", "two", "three", "four" };
final JList dataList = new JList(data);
dataList.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent arg0) {
if (!arg0.getValueIsAdjusting()) {
label.setText(dataList.getSelectedValue().toString());
}
}
});
add(dataList);
add(label);
setVisible(true);
}
public static void main(String args[]) {
new JListDemo();
}
}
Why don't you put a ListSelectionListener on your JList, and add your above code in to it.
I'm assuming you already know how to create listeners on JButtons, based on your question, so you just need to tweak it to create a ListSelectionListener instead, then assign the listener to your JList using jlist.addListSelectionListener(myListener);
There is a nice tutorial here that should get you started, or refer to the documentation
You should be aiming for something like this...
jlist.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent event) {
if (!event.getValueIsAdjusting()){
JList source = (JList)event.getSource();
String selected = source.getSelectedValue().toString();
}
}
});
Use a ListSelectionListener:
JList list = new JList(...);
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent evt) {
if (!evt.getValueIsAdjusting()) {
// code here
}
}
});

How to refresh JTable with always-changing tableModel?

2015.5.5 22:11 updated. I found that, when I create a sorter and call setRowSorter() method in the MyTable's construction, afterwards, it
will keep the original line number(in which the data still refresh
correctly but not easy to discover)even though the dataModel inside is
already changed many times which can be proven as
printf(getModel().getRowCount()). What's more,
MyTable.getAutoCreateRowSorter() always return true. I must explicitly
call setAutoCreateRowSorter(true) to fix the issue it if I called
setRowSorter(). I am happy but this is still wierd.
[2015.5.5 6:19 updated] I have found a way to access: make a "setRow" with the combination of insertRow() and removeRow() and everytime I
update, I setrRow all the rows in the table. It reflect immediately in
the UI. BUT there will be a series of error begin with "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Invalid index" and I guess it's about some kiind of swing thread problem because I can see "RepaintManager" or "paint" in the error. It occurs especially when I move the scrollbar when it's running.(but it still occur if I don't move it)
I have a JTable in a JScrollPane in a JFrame. I initial a MyTableModel with a data and use it to Create a JTable.Like this
MyTableModel extends DefaultTableModel{
Data data;
//object
MyTableModel (Data a){
data = a;
// do something to initial the table model,like build object[][] and add rows.
}
}
class main{
MyTableModel tm = new MyTableModel(data);
Jtable table = new JTable(tm);
JScrollpane jsp = new JScrollpane(table);
JFrame window = new JFrame();
window.getxxxpane().add(jsp);
}
So, as my data is always changing/updating and the changed row is plural and impossible to caculate.
while(true){
data.change();
refreshing the table to display the data immediately;
}
my idea is to simply build a new MyTableModel object and set it as the table's model like:
table.setModel(new MyTableModel(data)); //data had been changed.
which doesn't work.
and I tried this:
tm = MyTableModel(data);
tm.fireTableDataChanged();
which doesn't work either.
and the combination as well:
MyTableModol nm = new MyTableModel(data); //data had been changed
table.setModel(nm);
nm.fireTableDataChanged();
Could someone please give me some clue to change the TableModel object in an unchangable Jtable and update everytime.I dont want to change the tableModel Object because the calculation is huge, instead ,i Want to always create a new object with the construction method's parameter(changed data).
the most worst method is to remove the JScrollpane and rebuild one table/tablemodel/jscrollpane and re-add it, in which I have to call window.setVisible(true). window.repait() doesn't work,either,unless I move it.
I create a space-wasting but runnable program for demostration ,which most of them are nonsense.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Formatter;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
class TM extends DefaultTableModel {
int[] inside;
static String[] columnNames = { "Hellium", "Radon",
};
TM(int[] data) {
super(columnNames, 0);
this.inside = data;
update();
}
void update() {
Object[][] data = new Object[2][columnNames.length];
for (int i = 0; i < 2; ++i) {
data[i][0] = inside[0];
data[i][1] = inside[1];
// setValueAt(aValue, row, column);
addRow(data[i]);
}
fireTableDataChanged();
}
}
class idkName {
TM tm;
JButton jb, jb2;
int data[] = { 1, 2 };
int data2[] = { 9, 10 };
JTable table;
JScrollPane jsp;
JFrame twindow;
idkName() {
JFrame window = new JFrame();
window.setSize(400, 400);
window.setLayout(new BorderLayout());
jb = new JButton("show");
jb2 = new JButton("change model");
window.add(jb, BorderLayout.EAST);
window.add(jb2, BorderLayout.WEST);
twindow = new JFrame();
jb.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
tm = new TM(data);
table = new JTable(tm);
jsp = new JScrollPane(table);
twindow.getContentPane().add(jsp);
twindow.setSize(500, 500);
twindow.setVisible(true);
}
});
window.setVisible(true);
jb2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
// tm = new TM(data2);
tm = new TM(data2);
System.out.println(""+tm.getValueAt(0,0));
tm.fireTableDataChanged();
twindow.setVisible(true);
}
});
}
}
public class main2 {
TM tm;
public static void main(String[] args) {
idkName i = new idkName();
}
}
If you're going to extend DefaultTableModel, then when the data is changed, you need to update it in DefaultTableModel's internal representation using the setValueAt or setDataVector methods. If you have extensive changes (which it sounds like you do), use the setDataVector method to change all the cells and the table structure at once. Your example code looks like it's missing some updates because it's not pushing the new values in to the DefaultTableModel's data vectors.
But since you have a lot of updates, you're probably better off avoiding DefaultTableModel and just extending AbstractTableModel, using your own custom data storage, and calling the appropriate fireXxx() methods whenever your data changes. This will probably be more efficient in terms of both data conversion and number of events raised.
And then make sure all the event and value change work is done on the AWT event thread, using SwingWorkers or other threading support.

Populating a JComboBox with an ArrayList from another class

I am trying some self teachings and am working on a small app that reads details from a text file and shows them in a JComboBox for selection. The plan is to be able to select an item from the combobox, push the button and have a pop-up message appear with text depending on the selection, but I digress.
Currently, when it compiles the combobox is showing what I think to be some kind of exception. It says [Ljava.lang.Object;#175078b.
What am I doing wrong here?
This is the class that has the ArrayList:
import java.io.File;
import java.io.FileNotFoundException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.Scanner;
public class Stuff {
private ArrayList<String> list;
private String name;
private ArrayList<String> getList() {
return list;
}
private void setList(ArrayList list) {
this.list = list;
}
public Stuff() {
readNames();
}
public void readNames() {
File file = new File("Names.txt");
try {
ArrayList<String> list = new ArrayList<>();
Scanner in = new Scanner(file);
while (in.hasNextLine()) {
list.add(in.nextLine());
}
Collections.sort(list);
// for (int i = 0; i < list.size();++i){
// System.out.println(list.get(i));
// }
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
This is the class with the GUI:
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.util.ArrayList;
import javax.swing.*;
public class GUI extends JFrame{
private JLabel label = new JLabel("Who is the most awesome?");
private JComboBox box = new JComboBox();
private JFrame frame = new JFrame();
private JTextArea text = new JTextArea();
private JButton button = new JButton("Press Me");
private JPanel panel = new JPanel();
private ArrayList<Stuff> list = new ArrayList<>();
private JFrame getFrame(){
return frame;
}
private ArrayList<Stuff> getList(){
return list;
}
private void setList (ArrayList<Stuff> list){
list = list;
}
public GUI(){
buildGUI();
}
private void buildGUI(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.setLayout(new FlowLayout());
panel.add(label);
panel.add(box);
panel.add(button);
box.addItem(list.toArray());
frame.add(text);
frame.add(panel, BorderLayout.CENTER);
frame.setSize(400,100);
frame.setVisible(true);
}
}
Your problem is in the line: box.addItem(list.toArray());
The addItem() method for a JComboBox requires an Object as a parameter. Typically, a String object is used as the parameter. Instead, what you are doing is trying to add the actual list reference to the combo box when you really meant to add every item in the list.
Instead, you should add the individual items in the list as follows:
for(Stuff stuff : list) {
box.addItem(stuff.getName());
}
EDIT: Reading your original worded problem again, I think your second code snippet regarding the GUI should not be using another ArrayList of Stuff if you actually intended to use the ArrayList in one instance of a Stuff object. Therefore, you should first change:
private ArrayList<Stuff> list = new ArrayList<>();
to
private Stuff = new Stuff();
and change the for loop to iterate through stuff.getList() instead of list. To clarify, the for loop might look like:
for(String detail : stuff.getList()) {
box.addItem(detail); // add each extracted detail from the text file that was stored in the list of the stuff object
}
The main problem is you're adding a single array to the combo box...
box.addItem(list.toArray());
You either need to build a ComboBoxModel around the list the list of items...
DefaultComboBoxModel model = new DefaultComboBoxModel(list.toArray(new Stuff[list.size()]));
box.setModel(model);
Or add each item from the list to the combo box
for (Stuff stuff : list) {
box.addItem(stuff);
}
See How to use combo boxes for more details
The responsibility for rendering values in JComboBox comes down to the ListCellRenderer.
Take a look at Providing a Custom Renderer for more details.
This approach allows you to custom how the object is rendered without having to modify the underlying object itself. It also means that you maintain the object relationship. Rather then having to provide some kind of mapping between the view and the original list of objects, you can simply get a direct reference of the object from the combo box, because the ListCellRenderer is performing the transformation for you.
Now, having said that, this will prevent the user from been able to use combo boxes built in search feature.
To that end, check Combo Box With Custom Renderer for a possible work around. This is authored by our very own camickr

Get selected `JCheckBox` associated `id` on swing

Before I asked this question, I went through many examples, some of them are related, but did not answer my needs:
How to get the selected index of JCheckbox?
Java- Reading whether a checkbox is checked or not
I have a list as keyMessageList which includes id as Long and associated keyWord as String.
I displayed keyWord's name on my jpanel using following code:
for (KeyMessage obj : keyMessageList) {
checkBox = new JCheckBox(obj.getSmsKey());
displayKeywordPanel.checkBooxPanel.add(checkBox);
}
I got the following output:
Now, My requirement is: If I select keywords, I need to get the id associated with the selected keyword. I have done similar things many times in web applications like this, but now I need to do the same thing on swing. I used the following code on web application to fulfill the requirements.
Code for web:
<h:selectOneMenu id="branch" value="#{createUser.branchId}" required="true" requiredMessage="Please choose branch">
<f:selectItems value="#{allBranch}"/>
</h:selectOneMenu>
Can any swing expert please help me.
Note I may select multiple checkBox and keyMessageList returns from JPA query.
I have a list as keyWordsList which includes id and associated keyWord.
Don't use a List. Instead use a Map with the "keyword" as the key and the "id" as the value. Then when you select a check box you get the ID from the Map.
Another option would be to create you JCheckBox as follows:
JCheckBox checkBox = new JCheckBox(keyword);
checkbox.setActionCommand( id );
Then later you access the id of the selected checkbox by using the getActionCommand() method.
You can get displayKeywordPanel.checkBooxPanel.getComponents() array. Iterate through the array and store indexes. Then use the indexes to get elements from the keyMessageList
I think you can extend your own JCheckBox (let say JCheckBoxWithID) which allow you keep the id. Then use a List to store/remove ids everytime a checkbox is selected/unselected using an ItemListener
This way you'll be avoiding iterate over your checkboxPanel asking who is selected and keeping separated responsibilities:
JCheckBox just shows a keyword and holds an id
List just stores selected ids
ItemListener handles the event when a JCheckBox becomes selected/unselected and adds/removes its id to/from List
Hope this example be helpful:
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Tests {
private void initGUI(){
/* This list will store selected ids */
final List<Integer> selectedIds = new ArrayList<>();
ItemListener itemListener = new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if(e.getSource() instanceof JCheckBoxWithID){
JCheckBoxWithID checkBoxWithID = (JCheckBoxWithID) e.getSource();
if(checkBoxWithID.isSelected()){
selectedIds.add(checkBoxWithID.getId());
} else {
selectedIds.remove(checkBoxWithID.getId());
}
}
}
};
String[] keyWords = new String[]{"Help 1", "Help 2", "Help 3", "Help 4", "Help 5", "Help 6"};
Integer id = 0;
JPanel checkBoxesPanel = new JPanel(new GridLayout(3,3));
/* Add many checkbox as you keywords you have */
for(String keyWord : keyWords){
JCheckBoxWithID checkBoxWithID = new JCheckBoxWithID(keyWord, id);
checkBoxWithID.addItemListener(itemListener);
checkBoxesPanel.add(checkBoxWithID);
id++;
}
JButton submit = new JButton("Submit");
submit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, Arrays.toString(selectedIds.toArray()), "Selected IDs", JOptionPane.INFORMATION_MESSAGE);
}
});
JPanel content = new JPanel(new FlowLayout(FlowLayout.LEADING));
content.add(checkBoxesPanel);
content.add(submit);
JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(content);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Tests().initGUI();
}
});
}
class JCheckBoxWithID extends JCheckBox {
/* I use Integer but the id could be whatever you want, the concept is the same */
private Integer _id;
public JCheckBoxWithID(String text, Integer id) {
super(text);
_id = id;
}
public void setId(Integer id){
_id = id;
}
public Integer getId(){
return _id;
}
}
}
Here's a print screen:

java swing, highligth item in jcombobox popup

i want to highlight an item inside popup list.
I say "highlight" becouse i don't want to select it (for example by calling setSelectedItem) but only make it selected inside the jcombobox popup.
How can i do?
The following sort of works in that an item other than the first is selected. However, if you use the keyboard to change selection, it always starts from the first because that is the one that is selected.
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.plaf.basic.*;
public class ComboBoxSelect extends JFrame
{
public ComboBoxSelect()
{
String[] items = { "Item1", "Item2", "Item3", "Item4", "Item5" };
JComboBox comboBox = new JComboBox( items );
add( comboBox );
comboBox.addPopupMenuListener(new PopupMenuListener()
{
public void popupMenuWillBecomeVisible(PopupMenuEvent e)
{
JComboBox comboBox = (JComboBox)e.getSource();
BasicComboPopup popup = (BasicComboPopup)comboBox.getAccessibleContext().getAccessibleChild(0);
JList list = popup.getList();
list.setSelectedIndex(2);
}
public void popupMenuCanceled(PopupMenuEvent e) {}
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {}
});
}
public static void main(String[] args)
{
ComboBoxSelect frame = new ComboBoxSelect();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
}
This write-up provides guidance on how you could modify JComboBox:
http://www.orbital-computer.de/JComboBox/
Although it's written for auto-complete functionality, a custom mechanism to highlight without selecting would be very similar (and probably easier).

Categories

Resources