How to load already instantiated JComboBox with data in Java? - 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));

Related

Dynamically updating jTable

My table will change the entire dataset during runtime.
My current code looks like below,
public class gui_test_form extends JFrame{
private JPanel rootpanel;
private JTable testTable;
private JScrollPane testScrollPane;
private JButton testButton;
private String[] columnNames = {"Name", "Color"};
private Object[][] data = { {"John", "Blue"}, {"Oliver", "Green"}, {"Paul", "Red"} };
public gui_test_form() {
super("GUI TEST");
setContentPane(rootpanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
testButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent actionEvent) { // Button Clicked
//Get new values
data[0][0] = "New Value";
//Update table
testTable.setModel(new DefaultTableModel(data, columnNames));
}
});
}
}
The code works as I expected. But I don't think making a new DefaultTableModel everytime is the best way to go. What should I be doing?
I looked briefly into fireTableChanged() method for AbstractTableModel, but couldn't make it work. I expected it would work since DefaultTableModel is inherited from AbstractTableModel.
Any help is appreciated.
-------Edit-------
Forgive me if I wasn't clearer before, but the problem is that I want to update the whole dataset. Even the Column names and the number of columns and rows are going to change.
For example, in the above code I could do this, and it would still work as you'd expect.
//Get new values
columnNames = new String[]{"Country", "Location", "Latitudes"};
data = new Object[][]{ {"John", "Blue", "1"}, {"Oliver", "Green", "4"}};
//Update table
You should be declaring a single table model at the same level where you create your JTable and making changes to that table model as required, rather than declaring it in the event handler.
private JPanel rootpanel;
private JTable testTable;
private DefaultTableModel tableModel;
private JScrollPane testScrollPane;
private JButton testButton;
tableModel = new DefaultTableModel();
testTable = new JTable(tableModel);
Take a look at the Java Tutorial. Pay attention to the section on listening for table data changes
If you come up with your own table model, you need to be sure to fully implement all overridden methods, particularly setValueAt(), and make sure you keep track of your row count properly. One of the most common mistakes involves forgetting to increment your row count after adding data and thinking that the table model is not receiving data.
Add below code in wherever you want to update the model.
model.addRow(new Object[]{txt_title.getText(), txt_name.getText()});
Before, The model and table must also be predefined globally.
DefaultTableModel model = new DefaultTableModel();

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

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

Categories