I am using 4 JLists that is an array,
JList jlst = new JList[4];
Then I am adding first list items from array of objects,
jlst[0].setListData(getObjAL());
Here the function getObjAL() function will give the array of objects.
I want to display selected item of first list(jlst[0]) into second list(jlst[1]).
For that I am writing the code,
jlstPrimitives[i].addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent listevt) {
Jlist objLstTemp = (Jlist) listevt.getSource();
jlst[1].setListData(objLstTemp.getSelectedValue()));
}
});
But it is not displaying in list[1].
Please any one help me...
I can think of a dozen things that might be going wrong, none of which would affect you. For better support in the future, post a runnable example that demonstrates your problem. Pasting code out of context doesn't help (alot).
From your code, getObjAL() seems to be returning a Object[] array (single dimension), yet when you select a value, you seem to be assuming that the selected value is actually an array, which I'm pretty sure it isn't.
JList#setListData is expected either a object array (Object[]) or Vector.
Try something like this instead.
jlstPrimitives[i].addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent listevt) {
Jlist objLstTemp = (Jlist) listevt.getSource();
jlst[1].setListData(new Object[]{objLstTemp.getSelectedValue()}));
}
});
Related
Example:
I made a table, and I want a search box for each column. I hid the column titles with this code:
table.setTableHeader(null);
And put a textField and Button to each top of columns. Now I can search for each different column, but I can't sort the items.
I want to sort the column items when I click the top button. I tried some thing but it is so complex for a beginner as me.
Is there any way to do it? Or all the thing i tried useless and there is much easy way to do it? I hope explained it right.
Note :
I have found this code.I dont even know if it does what i need. I did try it but getting error.
/** Default sort behaviour, plus every third click removes the sort. */
private final class CustomSorter extends MouseAdapter {
#Override public void mouseClicked(MouseEvent aEvent) {
int columnIdx = fTable.getColumnModel().getColumnIndexAtX(aEvent.getX());
//build a list of sort keys for this column, and pass it to the sorter
//you can build the list to fit your needs here
//for example, you can sort on multiple columns, not just one
List<RowSorter.SortKey> sortKeys = new ArrayList<>();
//cycle through all orders; sort is removed every 3rd click
SortOrder order = SortOrder.values()[fCountClicks % 3];
sortKeys.add(new RowSorter.SortKey(columnIdx, order));
fSorter.setSortKeys(sortKeys);
++fCountClicks;
}
private int fCountClicks;
}
}
And did try this and getting same error.
btnNewButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
table.getRowSorter().toggleSortOrder(1);
}
});
Error:Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
This is the code: Code
This is the what program looks like : Picture
In the ActionListener of your JButton you can try sorting the column with code like:
table.getRowSorter().toggleSortOrder(columnIndex);
This should allow you to click the button to reverse the sort order each time it is clicked.
Edit:
As I said in my comment you need to learn how to solve a NullPointerException.
The stack trace when I run the code states:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at frame1$2.actionPerformed(frame1.java:83)
Line 83 is:
table.getRowSorter().toggleSortOrder(0);
So you have two variables at that statement:
table
table.getRowSorter()
It is up to you to determine which variable is null
So you add debug code before that statement:
System.out.println( table );
System.out.println( table.getRowSorter() );
If you do you will see that table.getRowSorter() returns null.
So now you can ask a proper question like:
"Why does table.getRowSorter() return null?"
The answer is simple you didn't set the properties of the table to do sorting.
This is easily done by adding:
table.setModel(model);
table.setAutoCreateRowSorter(true); // added
In the future do some basic debugging BEFORE asking a question. You can't code if you don't know the basics of debugging code.
My original answered assumed you new how to sort columns in a table when using the table header and you just wanted to know how to use a separate button. That is why a "MRE" should be posted with EVERY question so we don't have to guess what your code is really doing.
I am pretty new in Java programming, I have been trying to solve this simple program
it reads user input, then the ADD button will simply display the typed string on the JList.
The remove button will simply remove the desired item in the JList.
I am quite confused how to put the action listener thing in the code, or get text whatever
it is. I'd really appreciate if you can help me solve this simple GUI.
It reads user input in JText (String) and when I click the add button (maybe action performed?) the String will be basically populated in JList. and the Remove button will
simply remove the selected String in JList.
Step 1
Bind the code to the specific event, using the addActionListener method.
button.addActionListener(new ActionListener({
public void actionPerformed(ActionEvent e)
{
// Bind the method to the button.
}
});
Step 2
Populate that method with the relevant code.
String value = jTextBox.getText();
// Grab the String value.
jListModel.addElement(value);
// And add it to the list model that informs the JList.
Altogether
button.addActionListener(new ActionListener({
public void actionPerformed(ActionEvent e)
{
String value = jTextBox.getText();
// Grab the String value.
jListModel.addElement(value);
// And add it to the list.
}
});
Useful Links
Here is a very good tutorial from Oracle detailing how to manipulate lists a million and one different ways.
I need to remove all items from the combo box
int itemCount = combo.getItemCount();
for(int i = 0; i < itemCount; i++){
combo.removeItemAt(0);
}
This code will remove all items except the last one. It gives a NullPointerException.
How to fix that?
The code in the question would normally work. However, it looks like a threading issue. Another thread may be messing with the items.
However, I sugeest you should better use the removeAllItems(); method:
combo.removeAllItems();
How about JComboBox.removeAllItems()?
You can use
this.combo.removeAllItems();
to remove all the items in JComboBox.
In second line:
combo.removeItemAt(0);
I think instead of 0 it should be i.
do it in reverse order as:
for(int i=combo.getItemCount()-1;i>=0;i--){
combo.removeItemAt(i);
}
But in my case combo.removeAllItems() works fine
use .removeAllItems() methods to remove all items from combo box.
The assumption that it is related to another thread is not always true. It can be the thread itself causing the issue.
This exception may happen because an event is triggered when a combo item is removed and in this event handling method you still refer to combobox items.
For example when you delete somewhere (other than in actionPeformed()) in your code the last item from a combo box with combo.removeItemAt(0) or removeAllItems() then still the event actionPerformed will be fired/executed. But very often the actionPerformed() method contains code to react on user actions (user clicked somewhere on the combobox). So, when the last item has been deleted there is no more item in the combobox and any reference to an item or index in actionPerformed() will cause an exception.
The solution to this is to move the code from actionPerformed() to e.g. mouseClicked() or another event handler depending on what you want to do.
removeAllItems() it does remove all things but after the add data to the combo box it will not show there ,the nullPointException will shows
Use this to remove all the elements from the combo box :
DefaultComboBoxModel model = (DefaultComboBoxModel) ComboBox.getModel();
model.removeAllElements();
Usually it happens because you have an event associated JComboBox. It is solved if you have control item in the JComboBox to act, for example:
jComboBoxExample.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent e) {
do_run ();
}
});
public void do_run() {
int n=jComboBoxPerfilDocumentos.getItemCount(); <--THIS IS THE SOLUTION
if (n> 0) {
String x = jComboBoxPerfilDocumentos.getSelectedItem (). ToString ();
}
}
I have JList that grows in size along with the JFrame. I have the following code:
defaultListModel = new DefaultListModel<SData>();
for (String string: listOfStrings) {
defaultListModel.addElement(string);
}
jList = new JList<String>(defaultListModel);
jList.setCellRenderer(jListCellRenderer);
jList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent arg0) {
//codes to go
}
});
jList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
jList.setLayoutOrientation(JList.VERTICAL_WRAP);
scrollPane = new JScrollPane(jList);
If I set some value for setVisibleRowCount method, the row number becomes fixed and If I don't set value, default value of 8 comes to play. I want to have this value dynamically changing.
I just found that jList.setVisibleRowCount(0) makes it self adjustable, when resizing JList.
Echoing #kleopatras's comment, it's not clear what controls setVisibleRowCount(). This example grows the enclosing Window as rows are added, up to a predefined limit, then the scrollbar takes over. It might give you some ideas, or you can use it as the basis of your sscce as #Andrew suggests.
Addendum: If the size of JList will control the count, I'd start with half of the model's size(). Then add one visible row for every n added to the model, in a fixed ratio that is pinned to a predefined limit. To maintain a reliable count, you'll have to implement your own ListModel or override the mutators in DefaultListModel.
I have a perfectly normal ArrayList<MyObject> that I need to edit and pick an object from.
In the application window, I have a JComboBox to select the appropriate choice from the list. I'm writing an editor dialog for these objects, which just includes a JList of these objects and editor fields. It's easy enough to do; I'll just have a ListModel implementation of some kind. Stick the ArrayList in, access it through the usual fields. The stuff in the GUI list is 1:1 representation of the stuff in the actual list. Easy.
But the combo box in the main application window is giving me a bit of a headache, because I need a special value. Ideally, the first item in the list should be "(None)", and return a null.
Do I just need to write some sort of weird ComboBoxModel implementation for this, or is there an easier, already implemented way to do this? I'd definitely imagine this sort of situation has cropped up before.
Implementing your own ComboBoxModel should be quite easy.
Since this solution creates a new Vector from your ArrayList, changes to yourArrayList after creating Vector won't be visible in your JComboBox. If you need this, then you'll have to implement your own ComboBoxModel (see DefaultComboBoxModel implementation).
You would have to do this anyway, since there is no DefaultComboBoxModel constructor that takes a List.
class SpecialComboBoxModel extends DefaultComboBoxModel {
public final static String NULL_ELEMENT = "<None>";
public SpecialComboBoxModel(Vector v) {
super(v);
}
#Override
public int getSize() {
return super.getSize() + 1;
}
#Override
public Object getElementAt(int index) {
if( index == 0) {
return NULL_ELEMENT;
}
return super.getElementAt(index - 1);
}
}
ArrayList<String> yourArrayList = new ArrayList<String>();
yourArrayList.add("Value1");
yourArrayList.add("Value2");
Vector<String> v = new Vector<String>(yourArrayList);
dropdown.setModel(new SpecialComboBoxModel(v));
You might want to use a null-object. For example
public class MyObject {
public static final MyObject NULL_OBJECT = new MyObject();
..
}
and then in your ArrayList just call:
arrayList.add(0, MyObject.NULL_OBJECT);
You null-object should have all of its properties set to null (or to some reasonable defaults), and your toString() method (if you are using it), should return "(none)" if all the fields are null.