Scroller on Jlist - java

Here is my code to create a Jlist and filling it up using action listener
At the first place I used an array of string to fill up the Jlist and I had scroller.
Then for upating Jlist I need to change the mode of the Jlist to DefaultListModel and as soon as I did that change I lost my scroller.
I donot know what went wrong
Can any one help me please
private Component makeListView() {
final DefaultListModel<String> listModel = new DefaultListModel<String>();
final JList<String> list = new JList<String>(listModel);
list.setModel(listModel);
updateCourseListPanel(listModel);
notifyObserverInModelForClickingOnListItem(list);
list.setPreferredSize(getSize());
list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
list.setVisibleRowCount(-1);
list.setFixedCellWidth(80);
JScrollPane listScroller = new JScrollPane(list);
listScroller.setPreferredSize(getMaximumSize());
setVisible(true);
return list;
}

hard to tell from your snippet (as you didn't show the code that calls it): on face value, the issue is that you return the list instead of the scrollPane it's added to.
The deeper issue is that you seem to (guessing only, though, for lack of details :-) re-create the list whenever the data needs to be updated. A better approach is to separate the creation of the list and its model from its update and only update the model as needed:
private Component makeListView() {
final DefaultListModel<String> listModel = new DefaultListModel<String>();
final JList<String> list = new JList<String>(listModel);
list.setModel(listModel);
list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
list.setFixedCellWidth(80);
JScrollPane listScroller = new JScrollPane(list);
return listScroller;
}
private void update(Jlist list) {
updateCourseListPanel(list.getModel());
notifyObserverInModelForClickingOnListItem(list);
}
BTW, never-ever call any of the setXXSize methods, some reasons

Related

Jlist not displaying my items in String

JButton btnAdd = new JButton("add");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Main selectedValue = (Main)courseList.getSelectedValue();
if(selectedValue !=null){
orderList.addElement(chosenList);
}
}
});
i have created a addButton which adds elements from one Jlist to another Jlist. However, when i run my applction and click the add buttton it gives me this error in my chosenList Jlist:
javax.swing.JList[,-2008,0,2255x182,alignmentX=0.0,alignmentY=0.0,border=,flags=50332008,maximumSize=,minimumSize=,preferredSize=,fixedCellHeight=-1,fixedCellWidth=-1,horizontalScrollIncrement=-1,selectionBackground=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],selectionForeground=sun.swing.PrintColorUIResource[r=51,g=51,b=51],visibleRowCount=8,layoutOrientation=0]
I believe addElement method should be called on an instance of class DefaultListModel.
If you previously has added a DefaultListModel instance as the model for your orderList, you should use following code to add the element to your orderList.
Object selectedValue = courseList.getSelectedValue();
DefaultListModle listModel = (DefaultListModle)orderList.getModel();
listModel.addElement(selectedValue);
If you haven't set any instance of class which implements ListModel, you should initialize your orderList in this way:
DefaultListModel listModel = new DefaultListModel();
orderList = new JList(listModel);
// or
orderList.setModel(listModel);
Take a look at How to Use Lists from Java Tutorials.
What you are seeing in your list is not an error, but the toString() value for your chosenList object. Perhaps you mean to do the following instead:
orderList.addElement(selectedValue);
Instead of:
orderList.addElement(chosenList);

how to update comboBox while using glazedList..evenlist

alright.,ive already tried every trick off my sleeves..but couldnt figure out how to update the comboBox w/glazedList..if the input is coming from other class..ive tried passing the value to the methods,declaring it first to a string..and such..but none has work..tho it does work if the new item will just gonna come from same class..via click of a button..
so far ive got this code..
values = GlazedLists.eventListOf(auto);//auto is an array..
AutoCompleteSupport.install(comboSearch,values);//comboSearch is the comboBox
//"x" is the value coming from another class.
public void updateCombo(String x){
List<String> item = new ArrayList<>();
item.add(x)
value.addAll(item);
}
i hope this codes are enough to interpret what im trying to ask..
It's not possible to see how you've created your combobox and your eventlist. Therefore I'll just create a simple example application from scratch that shows you the essentials.
Just in case you're not familiar the general concepts the main take home points are:
Try and avoid using standard Java collections (eg ArrayList, Vector) and use the EventList class as soon as possible. All the goodness that comes with sorting/filtering/auto-complete relies on the EventList foundation so set one up asap and then simply manipulate (add/remove/etc) and then the GlazedLists plumbing will take care of the rest.
Once you've got your collection of objects in an EventList and you want to leverage a swing component then look in the ca.odell.glazedlists.swing module which contains everything you need. In this instance you can use an EventListComboBoxModel - pass in your eventlist, and then set your JComboBox model to use the newly created EventListComboBoxModel and from that point GlazedLists will take care of ensuring your list data structure and combobox stay in sync.
So in my example I create an empty combobox and an button. Clicking the button will add an item per click into the combobox. The magic is simply the creation of the EventList and the use of EventListComboBoxModel to link the list to the combobox.
Please note that the code below was only tested against GlazedLists 1.8. But I'm pretty sure it'll work fine with 1.9 or 1.7 too.
public class UpdateComboBox {
private JFrame mainFrame;
private JComboBox cboItems;
private EventList<String> itemsList = new BasicEventList<String>();
public UpdateComboBox() {
createGUI();
}
private void createGUI() {
mainFrame = new JFrame("GlazedLists Update Combobox Example");
mainFrame.setSize(600, 400);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton addButton = new JButton("Add Item");
addButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
itemsList.add("Item " + (itemsList.size()+1));
}
});
// Use a GlazedLists EventComboBoxModel to connect the JComboBox with an EventList.
EventComboBoxModel<String> model = new EventComboBoxModel<String>(itemsList);
cboItems = new JComboBox(model);
JPanel panel = new JPanel(new BorderLayout());
panel.add(cboItems, BorderLayout.NORTH);
panel.add(addButton, BorderLayout.SOUTH);
mainFrame.getContentPane().add(panel);
mainFrame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new UpdateComboBox();
}
});
}
}

Getting selected Items from Jlist

I have seen many posts & tried different ways to solve this problem but still I dont get my list of selected items. Here's the code which I use.
public List<String> getSelectedDeviceList()
{
return list;
}
/**
* Create the frame.
*/
public JLogicDesign(Frame frame, List<String> listDevices) {
super();
setTitle("Device Names");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 331, 316);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
jlistModel = new DefaultListModel();
for(String s: listDevices)
{
jlistModel.addElement(s);
}
final JList jlist = new JList(jlistModel);
jlist.setVisibleRowCount(5);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
btnOk = new JButton("OK");
btnOk.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
list = new ArrayList<String>();
Object[] values = jlist.getSelectedValues();
for(Object o: values)
{
list.add(o.toString());
}
dispose();
}
});
The JList is being properly populated. When I try to get the selected Items, I get a NPE.
This is another class where I'm calling the above class
JLogicDesign jld = new JLogicDesign(f,listOfDevices);
devices = new ArrayList<String>();
devices = jld.getSelectedDeviceList();
Thanks in advance !!
You get NPE at this line:
JLogicDesign jld = new JLogicDesign(f,listOfDevices);
devices = new ArrayList<String>();
devices = jld.getSelectedDeviceList(); // NPE here
Because list variable in JLogicDesign is only initialized when btnOk is pressed. So the pointed line is executed before this button is pressed and that's why it throws NPE.
To avoid NPE you shoud initialize list in JLogicDesign. However it doesn't solve the problem. You wont get NPE but you'll get an empty list. This is because JLogicDesign is not modal and even if these sentences are being executed on the Event Dispatch Thread jld.getSelectedDeviceList() will return the list before btnOk is pressed.
If you need the selected devices before continue then consider use a modal JDialog.

How to refresh JScrollPane

My main frame contains JScrollPane which lists some objects. Through menu (pop up frame) I create new object and I want to list this object in the JScrollPane (which is created in a constructor of DemoFrame class). How can I do it?
Part of my constructor in DemoFrame
ArrayList<Item> i = g.getAllItems();
Vector allItemsVector = new Vector(i);
JList items = new JList(allItemsVector);
panel.add( new JScrollPane( items ))
In pop up frame I add new object to 'g' object in that case. Have I designed it wrong?
A lot depends on information that you haven't told us, for instance just what is the JScrollPane holding? A JTable? A JList? The key will be to update the component being held by the JScrollPane and then revalidate and repaint this component.
Edit
You need to have a reference to the JList, so it should be declared outside of your constructor. For instance:
// GUI class
public class GuiClass {
private JList items; // declare this in the *class*
// class's constructor
public GuiClass() {
ArrayList<Item> i = g.getAllItems();
Vector allItemsVector = new Vector(i);
// JList items = new JList(allItemsVector); // don't re-declare in constructor
items = new JList(allItemsVector);
panel.add( new JScrollPane( items ))
}
Then later in your menu's listener code you can add an item to the items JList as needed.
This was a problem for me as well. A quick workaround is remove the JScrollPane from the panel, make your changes then readd it. Many may deem it inefficient, but it works with no significant change to runtime
JPanel panel = new Jpanel();
JList list = new JList({"this", "is", "a test", "list"});
JScrollPane sPane = new JScrollPane();
public void actionPerformed(ActionEvent e) {
if (resultsPane!=null){
panel.remove(sPane);
}
sPane = updatePane(list);
panel.add(sPane);
}
public void updatePane(String[] newListItems) {
DefaultListModel model = new DefaultListModel();
for(int i = 0; i < newListItems.length; i++) {
model.addElement(newListItems[i]);
}
JList aList = new JList(model);
JScrollPane aPane = new JScrollPane(aList);
}
Assuming I understood the question correctly:
You have a JFrame with a JScrollPane. And the JScrollPane has a JList.
The JList has a set of strings in it and this shows fine, but later you want to update the list and have it update in the JFrame view, but when you do update the list nothing happens to visualisation?
I had the same problem and how I got it to work was to set the content of the JList using a DefaultListModel. Instead of updating the contents of the JList, I update the contents in the DefaultListModel and then set the JList content to the model content when everything has been added. Then call the JScrollPane repaint function
//Declare list and pane variables up here so that we have a reference
JList<String> list;
JScrollPane pane;
//Set up the frame content
void SetupFrame() {
//instantiate the list
list = new JList();
//sets up the scroll pane to take the list
pane = new JScrollPane();
pane.setViewportView(list);
pane.setBounds(10, 10, 200, 80);
//adds the scrollpane to the frame
add(pane);
//update the list of strings
UpdateList();
}
//Updates the contents of the list (call this whenever you want to update the list)
void UpdateList() {
//model used to update the list
DefaultListModel model = new DefaultListModel();
//Update the contents of the model
for (int i = 0; i < 10; i++)
model.addElement("Test value");
//update the list using the contents of the model
connectionLabels.setModel(model);
//repaint the scrollpane to show the new list content
pane.repaint();
}

Adding and Removing a Button in JList

I want to add/remove buttons in JList. How can I do so?
Alternatively, consider a button-friendly JToolBar, as shown in How to Use Tool Bars.
#rohit I wonder here, what would you need them in a JList? If you want to lay them out vertically you should use some layout manager, e.g. BoxLayout or (better) GridLayout.
There is really no reason why you should have buttons in a JList, where having them in a panel will have the same result.
Seriously try to reconsider your design and go with a more flexible and easier one which uses a layout manager.
All the best, Boro.
Take a look at the Oracle Swing tutorial about how to use lists:
http://download.oracle.com/javase/tutorial/uiswing/components/list.html
JList.addElement() and JList.removeElement can be used to add en remove elements to and from JLists.
I Used this code. try it
class PanelRenderer implements ListCellRenderer {
#Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
JButton renderer = (JButton) value;
renderer.setBackground(isSelected ? Color.red : list.getBackground());
return renderer;
}
}
public void ShowItemList(List<JButton> buttonList, JPanel container) {
DefaultListModel model = new DefaultListModel();
for (JButton b:buttonList) {
model.addElement(b);
}
final JList list = new JList(model);
list.setFixedCellHeight(40);
list.setSelectedIndex(-1);
list.setCellRenderer(new JPanelToJList.PanelRenderer());
JScrollPane scroll1 = new JScrollPane(list);
final JScrollBar scrollBar = scroll1.getVerticalScrollBar();
scrollBar.addAdjustmentListener(new AdjustmentListener() {
#Override
public void adjustmentValueChanged(AdjustmentEvent e) {
System.out.println("JScrollBar's current value = " + scrollBar.getValue());
}
});
container.removeAll();
container.add(scroll1);
}
If you want to add a JButton add it to the list. If want to remove, remove it from the list and run the method again.

Categories

Resources