Updating list with files (Java swing) - java

So, I have this code in my JFrame, and it doesn't work for some reason:
private void jList1MouseEntered(java.awt.event.MouseEvent evt) {
DefaultListModel jList1Model = (DefaultListModel) jList1.getModel();
File f=new File("/home");
File[] allSubFiles=f.listFiles();
for (File file : allSubFiles) {
jList1Model.addElement(file.getAbsolutePath());
}
}
What am I doing wrong (ignore MouseEntered event, I'll change it)? It doensn't update anything when I hover over the active this list.

because It gives me an exception javax.swing.JList$3 cannot be cast to javax.swing.DefaultListModel
Don't you think that was an important piece of missing information from the question?
So basically that means you need to create your JList with code like:
DefaultListModel<String> model = new DefaultListModel<String>();
JList<String> list = new JList<String)(model);
Now you can dynamically try to add data to the model.

Related

Binding String ArrayList to JList

I have created a client -> server chat room system, and I have a list of currently connected users, which is currently displayed on a button click within a JTextField, this currently works fine and displays the string array. However, I have added another component to my GUI, being a JList. I have been trying to create a method called updateUserList to update the JList with the users that are connected. I have tried to use a DefaultListModel of type String, however this displays nothing in the JList and I am unsure as to why.
Below is the updateUserList method I have created:
public void updateUserList()
{
model = new DefaultListModel<String>();
for(String usernames : users)
model.addElement(usernames);
jl_users = new JList<String>(model);
}
Please note that model, usernames and jl_users are defined globally, therefore I have not included them in the post.
Why are you using DefaultListModel?
If you want a simply List just use it like this
public void updateUserList()
{
jl_users = new JList<String>(users.toArray(new String[users.size()]));
}
or straight forward
jl_users = new JList(users.toArray());

JList value changes when clicked

New to the forum and to Java. I am trying to have my JList respond when double-clicked, which I have accomplished. The JList is being populated by a SQL query which is ran when a button in the GUI is pressed. Based on the SQL query, the JList is populated, this is also working.
The issue comes about if I try to update the JList by clicking the button to query SQL again. When I click that, the change initially shows up in the JList, however when I click on that option in the JList it immediately switches back to what it was initially. When I double-click on what appears to be the incorrect name, the value that I have printing in the console reports correctly. So it has the value correct in the console but the rendering in the JList is not correct.
I appreciate any responses, I have combed the forums without any luck. I am new to Java so I'm sure there is quite a bit that isn't perfect with my code. Code is below please let me know if you need more. Thank you.
public JPanel results(StringBuilder message)
{
StringBuilder[] options = {message};
showOption = new JList(options);
showOption.setLocation(300, 50);
showOption.setSize(140,100);
showOption.setVisibleRowCount(10);
textPanel.add(showOption);
showOption.revalidate();
showOption.repaint();
MouseListener mouseListener = new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
//JList showOption = (JList) mouseEvent.getSource();
if (e.getClickCount() == 2) {
int index = showOption.locationToIndex(e.getPoint());
Object o = showOption.getModel().getElementAt(index);
System.out.println("Double-clicked on: " + o.toString());
}
}
};
showOption.addMouseListener(mouseListener);
return totalGUI;
}
public static void main ( String args[] )
{
//JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("[=] JTextField of Dreams [=]");
GUI_TextField demo = new GUI_TextField();
frame.setContentPane(demo.createContentPane());
//frame.setContentPane(demo.results(message));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(510, 400);
frame.setVisible(true);
}
Three things jump out at me immediately.
You're creating a new JList each time
You're manually setting the size and position of the JList
You're not removing the previous JList
For example...
public JPanel results(StringBuilder message)
{
StringBuilder[] options = {message};
// Create new JList
showOption = new JList(options);
// This is ill advised
showOption.setLocation(300, 50);
showOption.setSize(140,100);
showOption.setVisibleRowCount(10);
// What about the last JList?
textPanel.add(showOption);
This raises a number of possibilities, the likely one is that you are covering over the previous list, which is being brought to the front when textPanel is validated and painted.
Swing follows (loosly) the MVC paradigm (and for more details)
So instead of re-creating the view each time, you should simply re-create the model, for example...
public JPanel results(StringBuilder message)
{
DefaultListModel model = new DefaultListModel();
model.addElement(message);
showOption.setModel(model);
If showOption isn't created initially before this method is called, you should consider putting in a if statement to detect when showOption is null and initialise it appropriately.
You should also avoid using setLocation and setSize. Swing has being designed to operate with the use of layout managers, these make it possible to define workflow and general layout that can be used across multiple platforms.
Take a look at How to use lists and Laying Out Components Within a Container

Adding to existing JList

I need some help about adding items to JList. I work on some "library" kind of project. And I need to add readers to already existing JList. But when I try to add it, JList just resets, removes all the readers and starts adding readers to a new blank JList. But I don't need it to make new list but add it to the already existing one.
I know it's something about creating new model after adding, but i don't know where to fix it.
panelHorni = new JPanel();
listModel = new DefaultListModel();
listCtenaru = new JList(listModel);
FileInputStream fis = new FileInputStream("myjlist.bin");
ObjectInputStream ois = new ObjectInputStream(fis);
listCtenaru = (JList)ois.readObject();
listScroll = new JScrollPane();
listScroll.add(listCtenaru);
listCtenaru.setPreferredSize(new Dimension(350, 417));
listCtenaru.setBackground(new Color(238,238,238));
panelHorni.add(listCtenaru);
listener
public void actionPerformed(ActionEvent e) {
String jmeno = pole1.getText();
String prijmeni = pole2.getText();
listModel.addElement(jmeno +" "+ prijmeni);
listCtenaru.setModel(listModel);
pole1.setText("");
pole2.setText("");
pole1.requestFocus();
listModel.addElement(jmeno +" "+ prijmeni);
//listCtenaru.setModel(listModel);
There is no need to use the setModel() method if you are trying to update the existing model. The fact that you are trying to do this would seen to indicate you are creating a new model instead of updating the existing model.
See the Swing tutorial on How to Use Lists for a working example that updates the existing model.
The default model of JList is ListModel you must firstly change it inside the constructor to DefaultListModel. That solves your problem:
private JList list ;
private DefaultListModel model;
public ListModelTest(){//default constructor
//....
list = new JList();
model = new DefaultListModel();
list.setModel(model);
//....
}
public void actionPerformed(ActionEvent ev){
model.addElement("element");
//....
}

How to setSelectionPaths() for a JIDE CheckBoxTree using the CheckBoxTreeSelectionModel?

I'm using the CheckBoxTree class which is part of the JIDE Common Layer package (http://jidesoft.com/products/oss.htm). What I'd like to be able to do is save and load the state of the CheckBoxTreeSelectionModel which is what tracks what boxes are checked or not. I can save it by just saving selectionModel.getSelectionPaths(), but my problem is with loading it. When I selectionModel.setSelectionPaths() it only checks the boxes for the root and the leaf of the path, but nothing in between. Strangely enough, this also happens when I save the results of getSelectionPaths() then feed it directly into setSelectionPaths().
For the FileSystemModel, I'm using some code I found which likes to use File objects instead of TreeNodes. I have tried different combinations of FileSystemModels and CheckBoxTrees that I've found in various places on the Net, and the results are always the same. I've probably put close to 20 hours in on this issue... which is a bit embarrassing to admit. Any help is appreciated!
My code is as follows. This creates the CheckBoxTree and attempts to load it with "/Documents and Settings/Administrator" which results in "/" and "Administrator" and all it's children being checked, but not "Documents and Settings".
public class CheckBoxTreeFrame {
private FileSystemModel fileSystemModel = null;
private CheckBoxTree checkBoxTree = null;
private JFrame main_frame = null;
private CheckBoxTreeSelectionModel selectionModel = null;
public CheckBoxTreeFrame(){
// create the model
fileSystemModel = new FileSystemModel(new File(File.separator));
// use the model for the Tree
checkBoxTree = new CheckBoxTree(fileSystemModel);
checkBoxTree.setEditable(false);
// model for the checkboxes (not the directory structure)
selectionModel = checkBoxTree.getCheckBoxTreeSelectionModel();
// event listener
checkBoxTree.getCheckBoxTreeSelectionModel().addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
System.out.println(selectionModel.getSelectionPath());
}
});
// setup a little UI window for the tree.
main_frame = new JFrame("Frame Title");
main_frame.add(checkBoxTree);
main_frame.setSize(400, 400);
main_frame.setVisible(true);
// run the loading test
runTest();
}
public void runTest(){
File[] finalPath = new File[3];
finalPath[0] = (File)selectionModel.getModel().getRoot();
finalPath[1] = new File(finalPath[0],"Documents and Settings");
finalPath[2] = new File(finalPath[1],"Administrator");
selectionModel.setSelectionPath(new TreePath(finalPath));
}
}
Thanks!!
The CheckBoxTreeSelectionModel is basically a DefaultTreeSelectionModel (as in Swing). The trick the tree path has to exist in the TreeModel. I don't think the way you create a TreePath in runTest will create the same tree path. It'd better to get the tree path from the tree. Try this, it will work.
checkBoxTree.getCheckBoxTreeSelectionModel().addSelectionPath(checkBoxTree.getPathForRow(2));

Removing an item from the JList using ListModel as model type

I have the JList which is using ListModel and not the DefaultListModel. I don't want to change the type now because I am using this in many places. I want to remove a selected item from the same list. How do i do this? I am using the following code but its not working for me.
made_list.removeSelectionInterval(
made_list.getSelectedIndex(), made_list.getSelectedIndex());
--EDIT--
I am using the following code when I create my list:
made_list = new javax.swing.JList();
made_list.setModel(new DefaultListModel());
And then in the JButton mouseclick event, I am using the following code to remove the selected item from the list when the button is pressed
private void removeActionPerformed(java.awt.event.ActionEvent evt) {
//made_list.removeSelectionInterval(made_list.getSelectedIndex(),
//made_list.getSelectedIndex());
System.out.println(made_list.getModel());
DefaultListModel model = (DefaultListModel)made_list.getModel();
model.remove(1);
}
removeSelectionInterval removes nothing from the model or the list except the selection interval. The list items remain unscathed. I'm afraid that you're either going to have to extend your ListModel and give it a removeItem(...) method as well as listeners and the ability to fire notifiers, etc... a la AbstractListModel -- quite a lot of work! If it were my money, though, I'd go the easy route and simply use a DefaultListModel for my model as it is a lot safer to do it this way, a lot easier, and will take a lot less time. I know you state that you don't want to use these, but I think you'll find it a lot easier than your potential alternatives.
An example of an SSCCE is something like this:
import java.awt.event.*;
import javax.swing.*;
public class Foo1 {
private String[] elements = {"Monday", "Tueday", "Wednesday"};
private javax.swing.JList made_list = new javax.swing.JList();
public Foo1() {
made_list.setModel(new DefaultListModel());
for (String element : elements) {
((DefaultListModel) made_list.getModel()).addElement(element);
}
JButton removeItemBtn = new JButton("Remove Item");
removeItemBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
removeActionPerformed(e);
}
});
JPanel panel = new JPanel();
panel.add(new JScrollPane(made_list));
panel.add(removeItemBtn);
JOptionPane.showMessageDialog(null, panel);
}
private void removeActionPerformed(ActionEvent e) {
System.out.println("made_list's model: " + made_list.getModel());
System.out.println("Model from a fresh JList: " + new JList().getModel());
DefaultListModel model = (DefaultListModel) made_list.getModel();
if (model.size() > 0) {
model.remove(0);
}
}
public static void main(String[] args) {
new Foo1();
}
}
You've been given a link to different sections of the Swing tutorial in the past to help solve problems. This was done for a reason. It helps solve your current problem. It gives you a reference for future problems.
All you need to do is look at the Table of Contents for the Swing tutorial and you will find a section on "How to Use Lists" which has a working example that adds/removes items from a list. Please read the tutorial first.
Or if you can't remember how to find the Swing tutorial then read the JList API where you will find a link to the same tutorial.
//First added item into the list
DefaultListModel dlm1=new DefaultListModel();
listLeft.setModel(dlm1);
dlm1.addElement("A");
dlm1.addElement("B");
dlm1.addElement("C");
// Removeing element from list
Object[] temp=listRight.getSelectedValues();
if(temp.length>0)
{
for(int i=0;i<temp.length;i++)
{
dlm1.removeElement(temp[i]);
}
}

Categories