Adding to existing JList - java

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");
//....
}

Related

Updating list with files (Java swing)

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.

JList created in Netbeans won't allow me to addElement

This is the automatically created code when adding the Jlist in Netbeans design mode:
jListResult = new javax.swing.JList();
jListResult.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jScrollPane1.setViewportView(jListResult);
I don't understand why an object of type Jlist would not be able to use the method .addElement How can I fix this?
addElement is provided by the DefaultListModel not the JList itself
DefaultListModel<String> model = new DefaultListModel<>();
JList jListResult = new JList(model);
model.addElement(...);

Row Delete in table

my whole code is this, but my code has one error and not run:
read from file is correctly , but dont delet row.
public class AllUserTable extends AbstractTableModel{
Vector data;
Vector columns;
public AllUserTable() {
String line;
data = new Vector();
columns = new Vector();
try {
FileInputStream fis = new FileInputStream("D:\\AllUserRecords.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
StringTokenizer st1 = new StringTokenizer(br.readLine(), " ");
while (st1.hasMoreTokens())
columns.addElement(st1.nextToken());
while ((line = br.readLine()) != null) {
StringTokenizer st2 = new StringTokenizer(line, " ");
while (st2.hasMoreTokens())
data.addElement(st2.nextToken());
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public int getRowCount() {
return data.size() / getColumnCount();
}
public int getColumnCount() {
return columns.size();
}
public Object getValueAt(int rowIndex, int columnIndex) {
return (String) data.elementAt((rowIndex * getColumnCount())
+ columnIndex);
}
public static void main(String[] args){
final AllUserTable aut1=new AllUserTable();
final JFrame frame1=new JFrame();
final JTable table=new JTable();
final JPanel panel=new JPanel();
JButton button1=new JButton("Delete");
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DefaultTableModel model=new DefaultTableModel(data,columns); //Error!
model.removeRow(table.getSelectedRow());
table.setModel(model);
table.setModel(aut1);
panel.add(table);
}
});
JScrollPane scroolpane=new JScrollPane();
scroolpane.setViewportView(table);
panel.add(scroolpane);
panel.add(button1);
frame1.add(panel);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setBounds(200, 80, 600, 500);
frame1.setVisible(true);
}
}
please repair my code!
This code doesn't compile. You're referencing instance fields (data, columns) from a static method (main). The error message of the compiler should tell you that. And if you don't understand it, googling for the error message should lead you to explanations of the error message.
And even if it did compiler, here's an explanation of each line of the event listener:
DefaultTableModel model=new DefaultTableModel(data,columns);
Create a new table model. Why? Your table already has one. All you need is to modify the existing table model
model.removeRow(table.getSelectedRow());
Remove a row from this new table model. Why modify a new model instead of modifying the existing one?
table.setModel(model);
Replace the old model by a new one. This is very inefficient. The table already has a model. Modify it.
table.setModel(aut1);
Replace the new model by the old one. Why?
panel.add(table);
Add the table to the main panel of the frame. Why? The table is already there and visible. This makes no sense.
You should implement a deleteRow() method in your AbstractTableModel.
Using a List of objects, where each row represents a row, would also be much clearer than using a single list to represent all the rows.
I have the feeling that you're copying and pasting code without understanding at all how it works and what the architecture of Swing is. Read the Swing tutorial. And even before that, read an introductory book about Java, variables and scopes.
Firstly, you never set the table model (aut1) to the table BEFORE your button action.
Secondly, I don't see where data and columns are defined when you construct the new DefaultTableModel in your action handler - the you try and delete a row from this "new" table model and the apply it to the table and then replace to with aut1, which effectively has done....nothing.
When constructing your UI, don't forget to set the table model to the table ... table.setModel(aut1)
Remove the DefaultTableModel from the action handler and use aut1 instead.
Updated with suggestions
You should avoid constructing your UI in the static main method, instead use a class instance instead, it will make you code cleaner and will present less issues into the future
You should only ever construct/manipulate UI/Swing components from within the context of the Event Dispatching Thread, use EventQueue#invokeLater

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]);
}
}

How to load already instantiated JComboBox with data in Java?

I have a Swings GUI which contains a JComboBox and I want to load data into it from the database.
I have retrieved the data from the database in a String Array. Now how can I populate this String array into the JComboBox
EDITED====================================================================
In actual, the JComboBox is already instantiated when the java GUI is shown to the user. So I can't pass the Array as a paramter to the constructor.
How can I populate the already instantiated JComboBox?
The following is the code that is Nebeans generated code.
jComboBox15 = new javax.swing.JComboBox();
jComboBox15.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "12" }));
jComboBox15.setName("jComboBox15");
Can I set another ComboBoxModel to the above jComboBox?
Ah, the combo box is already instantiated.... In that case just clear the contents and add the new array item by item:
comboBox.removeAllItems();
for(String str : strArray) {
comboBox.addItem(str);
}
Make sure this is done from the EDT!
Here's an excellent article about it: How to use Combo Boxes ( The Java Tutorial )
Basically:
String[] dbData = dateFromDb();
JComboBox dbCombo = new JComboBox(dbData);
You'll need to know other things like
Using an Uneditable Combo Box
Handling Events on a Combo Box
Using an Editable Combo Box
Providing a Custom Renderer
The Combo Box API
Examples that Use Combo Boxes
That article contains information about it.
EDIT
Yeap, you can either do what you show in your edited post, or keep a reference to the combo model:
DefaultComboBoxModel dcm = new DefaultComboBoxModel();
combo.setModel( dcm );
....
for( String newRow : dataFetched ) {
dcm.addElement( newRow )
}
new JComboBox(stringArray);
A useful tip - when you know what class you are working with, check its javadoc. It most often contains the information you need.
Edit: after your update, use:
for (String string : stringArray) {
comboBox.addItem(string);
}
(my tip still applies)
I think that what NetBeans does is what you need.
From wherever you want, you can create a DefaultComboBoxModel object and then invoke comboBox.setModel(defaultComboBox);
Here is a very small example of what I think you want to do: when the user clicks the button "Change data" the comboBox is filled with data from an array (method actionPerformed).
public class TestJComboBox extends JFrame {
private JComboBox comboBox = new JComboBox();
public TestJComboBox() {
JButton changeComboBoxData = new JButton("Change data");
changeComboBoxData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DefaultComboBoxModel cbm = new DefaultComboBoxModel(
new String[] { "hola", "adios" });
comboBox.setModel(cbm);
}
});
super.setLayout(new BorderLayout(10, 10));
super.setSize(100, 100);
super.add(changeComboBoxData, BorderLayout.NORTH);
super.add(comboBox, BorderLayout.SOUTH);
}
public static void main(String[] args) {
new TestJComboBox().setVisible(true);
}
}
JComboBox jComboOperator = new JComboBox();
arrOperatorName = new String []{"Visa", "MasterCard", "American Express"};
jComboOperator.setModel(new DefaultComboBoxModel(arrOperatorName));

Categories