basically what i am trying to do is, i have a JList which contain a list of available drive, if one of that drive selected by user then i will show all html files which located in selected drive in a JTable, so i put an event listener for my JList and then i create a JTable and put all data there and show it in the container. the code look like this:
static class HtmlListing implements ListSelectionListener
{
public void valueChanged(ListSelectionEvent event)
{
if (!event.getValueIsAdjusting())
{ //trying to remove and re-add controls in container.
EastCont.removeAll();
globarr = new ArrayList<File>(); // global variable
FileListing fl = new FileListing();
fl.walk(fileList1.getSelectedValue() + "work\\airasia\\html", 500, 0);
//if(globarr.size() > 0)
//{
Object[][] data = new Object[globarr.size()][globarr.size()];
for(int i = 0; i < globarr.size(); i++)
{
if(globarr.get(i).isFile())
{
String filename = globarr.get(i).getName().toString();
String date = sdf.format(globarr.get(i).lastModified());
Object[] obj = new Object[] {filename, filename.substring(filename.lastIndexOf(".") + 1), date, globarr.get(i).getAbsolutePath()};
data[i] = obj;
}
}
Object[] column = new Object[]{"name ", "type", "date modified", "path"};
DefaultTableModel model = new DefaultTableModel(data, column);
model.fireTableDataChanged();
table = new JTable(model)
{
private static final long serialVersionUID = 1L;
public boolean isCellEditable(int row, int column)
{
return false;
};
};
table.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
if (e.getClickCount() == 2)
{
int rowIdx = table.getSelectedRow(); // path to your new file
TableModel tm = table.getModel();
String path = tm.getValueAt(rowIdx, 3).toString();
File htmlFile = new File(path);
try // open the default web browser for the HTML page
{
Desktop.getDesktop().browse(htmlFile.toURI());
//Desktop.getDesktop().open(htmlFile);
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
});
table.removeColumn(table.getColumnModel().getColumn(3)); //hide column path from display
table.setFillsViewportHeight(true);
table.setIntercellSpacing(new Dimension(0, 5));
table.setShowGrid(false);
scrollPane = new JScrollPane(table);
EastCont = new JPanel();
EastCont.setLayout(new BorderLayout());
EastCont.add(scrollPane);
EastCont.setPreferredSize(new Dimension(1050, 1000));
//EastCont.repaint();
//EastCont.revalidate();
gui.add(EastCont, BorderLayout.EAST);
gui.revalidate();
gui.repaint();
// }
// else
// {
// EastCont.remove(table);
// gui.remove(EastCont);
// gui.revalidate();
// gui.repaint();
// }
}
this code work only for first time, but does not working for second time and so on, so what i miss here? any help would be great. thank you.
DefaultTableModel model = new DefaultTableModel(data, column);
//model.fireTableDataChanged();
//table = new JTable(model)
table.setModel( model );
Don't create a new table change reset the model of your current table. The rest of the code in that method is not necessary either since you are not creating any new GUI components.
Also, never invoke a fireXXX method. That is the responsibility of the TableModel.
Related
I made a GUI using JTable(tableModel) and a JPanel where the user can add data through JTextFields to an Arraylist, but for some reason when I click the add JButton, the adding fails and points to the line where I want to add the arraylist row to the tableModel.
public final static ArrayList<Members> adat = new ArrayList<>();
DefaultTableModel tableModel;
String[][] dummy = new String[][]{{"001", "Jack Black", "London", "20"}};
String[] header = new String[]{"id", "Name", "City", "Age"};
tableModel = new DefaultTableModel(dummy, header);
JTable t = new JTable();
t.setModel(tableModel);
panel1.add(new JScrollPane(t));
frame.add(panel1);
JPanel jp = new EditPanel();
frame.add(jp);
public static void newData() { // the "add" button function
Members newMember = null;
try {
newMember = new Members(
Integer.parseInt(EditPanel.idEdit.getText()),
EditPanel.nameEdit.getText(),
EditPanel.cityEdit.getText(),
Integer.parseInt(EditPanel.ageEdit.getText())
);
adat.add(newMember);
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "Error in modification", ERROR_MESSAGE);
}
toTable();
}
and the method toTable() gets the members data from the arraylist to the JTable
static void toTable() { // adding the users data to the table
if (adat.size() > 0) {
for (int i = 0; i < adat.size(); i++) {
int id = adat.get(i).id;
String name = adat.get(i).name;
String city = adat.get(i).city;
int age = adat.get(i).age;
Object[] data = new Object[4];
data[0] = id;
data[1] = name;
data[2] = city;
data[3] = age;
tableModel.addRow(data); // this is the line where the error points
}
}
}
You're encountering an error at tableModel.addRow(data); because tableModel does not have a method called addRow (docs).
You probably mixed up the DefaultTableModel tableModel with the actual JTable t.
It should be t.addRow(data), although you need to make t global first!
I have this code to which it can display data from database. It's working well but I want it to have checkbox at last column. I've found some codes here but It's only for pre-defined not values and not from database. (How to add checkboxes to JTABLE swing)
Screenshot:
Code:
public print() {
initComponents();
try{
conn = (Connection) db_connect.connectDB();
}
catch(ClassNotFoundException | SQLException ex){
JOptionPane.showMessageDialog(null, ex);
}
update_table("select name, section, student_number, gender from students");
}
public void update_table(String q){
try{
st= conn.createStatement();
st.executeQuery(q);
ResultSet rs = st.executeQuery(q);
users_list.setModel(DbUtils.resultSetToTableModel(rs));
users_list.getColumnModel().getColumn(0).setPreferredWidth(250);
users_list.getColumnModel().getColumn(0).setPreferredWidth(250);
users_list.getColumnModel().getColumn(1).setPreferredWidth(150);
users_list.getColumnModel().getColumn(2).setPreferredWidth(120);
users_list.getColumnModel().getColumn(3).setPreferredWidth(100);
int count= users_list.getModel().getRowCount();
if(count==0){
no_results_found.setVisible(true);
}
else{
no_results_found.setVisible(false);
}
}
catch(SQLException ex){
JOptionPane.showMessageDialog(null,ex);
}
}
You can try something like this:
public class JTableWithCheckBox {
private JFrame mainFrame;
private JTable studentTable;
private JScrollPane scrollPaneTable;
private DefaultTableModel model = new DefaultTableModel(new Object[][] {
{ "Ramesh", "Male" }, { "Sheela", "Female" },
{ "Amithabh", "Male" }, { "Katrina", "Female" } }, new Object[] {
"Name", "Gender" });
public static void main(String[] args) {
final JTableWithCheckBox ui = new JTableWithCheckBox();
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ui.initGUI();
}
});
}
private void initGUI() {
mainFrame = new JFrame("View");
mainFrame.getContentPane().setLayout(new BorderLayout());
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setSize(300, 200);
mainFrame.setVisible(true);
mainFrame.setLocationRelativeTo(null);
studentTable = new JTable(model);
studentTable.getColumnModel().getColumn(1)
.setCellRenderer(new MFCheckBox());
scrollPaneTable = new JScrollPane(studentTable);
mainFrame.add(scrollPaneTable, BorderLayout.NORTH);
}
private class MFCheckBox implements TableCellRenderer {
#Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row,
int column) {
JPanel cbPanel = new JPanel();
JCheckBox maleBox = new JCheckBox("Male");
JCheckBox femaleBox = new JCheckBox("Female");
cbPanel.setLayout(new BorderLayout());
cbPanel.add(maleBox, BorderLayout.WEST);
cbPanel.add(femaleBox, BorderLayout.EAST);
if (value != null) {
if (value instanceof String) {
String valStr = (String) value;
switch (valStr) {
case "Male":
maleBox.setSelected(true);
femaleBox.setSelected(false);
break;
case "Female":
maleBox.setSelected(false);
femaleBox.setSelected(true);
break;
default:
maleBox.setSelected(false);
femaleBox.setSelected(false);
break;
}
}
}
return cbPanel;
}
}
}
If you also want checkbox editable, you will have to set TableCellEditor as well.
The easiest way is to NOT use DBUtils and to load the data from the ResultSet into the TableModel` yourself.
The code is not difficult and you can use the Table From Database Example found in Table From Database as the starting point.
The code just loads the data from the ResultSet into Vectors, so you can then manually add another column to contain Boolean data.
The changes to the code would be something like:
// Get column names
for (int i = 1; i <= columns; i++)
{
columnNames.addElement( md.getColumnName(i) );
}
columnName.addElement( "Check Mark" ); // added
// Get row data
while (rs.next())
{
Vector<Object> row = new Vector<Object>(columns);
for (int i = 1; i <= columns; i++)
{
row.addElement( rs.getObject(i) );
}
row.addElement( Boolean.FALSE ); // added
data.addElement( row );
}
The other option is to create a "wrapper" TableModel that wraps a Boolean column with your DBUtils TableModel. Check out How to add checkbox in Jtable populated using rs2xml for an example of this approach.
That answer places the check box column at the start of the table, so you would need to modify the code to place the check box at the end.
I have a jtable functioning normally. The table lists tasks, and each task you an associated status.
I want every status is associated with an image.
So the image would appear in the table as show below.
------Code for jTable----------
DefaultTableModel tmSubTask = new DefaultTableModel(null, new String[]{"Status", "Priority", "Task", "SubTask", "Desc", "Prevision Begin", "Time", "Prevision Duration", "Prevision hour", "Begin", "Hour Begin","End Date" ,"End Hour", "Duration"});
List<SubTask> subTask;
ListSelectionModel lsmSubTask;
Connection conexao = null;
PreparedStatement pst= null;
ResultSet rs = null;
private void showSubTask(List<SubTask> subTask) {
while (tmSubTask.getRowCount() > 0) {
tmSubTask.removeRow(0);
}
if (subTask.size() == 0) {
JOptionPane.showMessageDialog(null, "showSubTask");
} else {
String[] line = new String[]{null, null, null};
for (int i = 0; i < SubTask.size(); i++) {
tmSubTask.addRow(linha);
tmSubTask.setValueAt(subTask.get(i).getStatus(), i, 0);
tmSubTask.setValueAt(subTask.get(i).getIdPriority(), i, 1);
tmSubTask.setValueAt(subTask.get(i).getIdTask(), i, 2);
tmSubTask.setValueAt(subTask.get(i).getIdSubTask(), i, 3);
tmSubTask.setValueAt(subTask.get(i).getDescSubTask(), i, 4);
tmSubTask.setValueAt(subTask.get(i).getDateBegin(), i, 5);
tmSubTask.setValueAt(subTask.get(i).getTerm(), i, 6);
tmSubTask.setValueAt(subTask.get(i).getDuration(), i, 7);
tmSubTask.setValueAt(subTask.get(i).gethourBeginP(), i, 8);
tmSubTask.setValueAt(subTask.get(i).getDateBegin(), i, 9);
tmSubTask.setValueAt(subTask.get(i).getHourBegin(), i, 10);
tmSubTask.setValueAt(subTask.get(i).getDateEnd(), i, 11);
tmSubTask.setValueAt(subTask.get(i).getHourEnd(), i, 12);
tmSubTask.setValueAt(subTask.get(i).getDuration(), i, 13);
}
}
}
---------------jTable--------------
---------------What I want---------
Imagine if Status like Delay in jTable show image red.
I honestly don't even know where to start.
I apologize if I did not make myself clear.
Thank all any help you can give me.
Greetings.
Any questions I will try to explain as best as possible.
Add an ImageIcon to the table and override the getColumnClass(...) method of the JTable to return Icon.class and the table will use an appropriate renderer to display the Icon. Something like:
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
public class TableIcon extends JFrame
{
public TableIcon()
{
Icon aboutIcon = new ImageIcon("about16.gif");
Icon addIcon = new ImageIcon("add16.gif");
Icon copyIcon = new ImageIcon("copy16.gif");
String[] columnNames = {"Picture", "Description"};
Object[][] data =
{
{aboutIcon, "About"},
{addIcon, "Add"},
{copyIcon, "Copy"},
};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
JTable table = new JTable( model )
{
// Returning the Class of each column will allow different
// renderers to be used based on Class
public Class getColumnClass(int column)
{
return getValueAt(0, column).getClass();
}
};
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane( table );
getContentPane().add( scrollPane );
new TableRowResizer(table);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
TableColumnAdjuster tca = new TableColumnAdjuster(table);
tca.adjustColumns();
}
public static void main(String[] args)
{
TableIcon frame = new TableIcon();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
}
}
I've 2 panels. One where the user inserts the data and the other with a JTable where the results will be shown.
My problem is when the user press's the ok (in my case apply) JButton the data is computed but is not shown on the JTable, nothing changes in the JTable.
For my JTable I'm using the Bean Table Model from tips4Java (http://tips4java.wordpress.com/2008/11/27/bean-table-model/).
One weird thing is if I send data (lets call this data 'A') to the table when the program starts it is shown on the table and if later on I try to update the table, the table does not update. But when I don't send data to the table at start up but try to update/send the table with data 'A' it does not update.
So my question is, why is not the JTable showing whatever data I send to?
Here's my code:
JButton listenere that starts the processing and sends the data to the table:
crashForm.setFormListener(new FormListener() {
#Override
public void formEvent(OptionsFormEvent oe) {
String readTable = oe.getReadFromTable();
int access = oe.getAccess();
int transition = oe.getTransition();
boolean smooth = oe.isTrainCrash();
ArrayList<String> allTrains = new ArrayList<>();
List crashedTrainList = new ArrayList<>();
try {
allTrains = controller.getUniqueTrains(controller.connectServer(), readTable, "trainid");
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "An error occured while getting trains data\n"
+ "Error description: " + ex.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
}
try {
for (int i = 0; i < allTrains.size(); i++)
{
ArrayList<Train> trainDataList = new ArrayList<>();
ArrayList<Train> crashedProccessedData = new ArrayList<>();
String query = "the sql query...";
trainDataList = controller.getTrainData(controller.connectServer(), readTable, query);
crashedProccessedData = controller.detectCrash(access, transition, trainDataList);
crashedTrainList.addAll(crashedProccessedData);
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "An error occured while detecting a crash.\n"
+ "Error description: " + ex.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
}
System.out.println("Total crashes detected:" + crashedTrainList.size());
tablePanel.createTable(Train.class, crashedTrainList, true, false, tableLabels);
tablePanel.fireTableDataChanged();
}
});
}
And here's my tablePanel class:
public TablePanel() {
}
public void createTable(Class c, List data, boolean toolBarUp,
boolean toolBarBottom, ArrayList<String> labelsCheckBox) {
beanTableModel = new BeanTableModel(c, data);
columnModel = new XTableColumnModel();
table = new JTable(beanTableModel);
table.setColumnModel(columnModel);
table.createDefaultColumnsFromModel();
if(toolBarUp == true)
{
final JToolBar toolBarTop = new JToolBar();
// Create the Show ALL
JButton reset = new JButton("Reset");
reset.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for(Component c : toolBarTop.getComponents()){
if(c instanceof JCheckBox){
JCheckBox checkBox = (JCheckBox) c;
checkBox.setSelected(false);
columnModel.setAllColumnsVisible();
}
}
int numberOfColumn = columnModel.getColumnCount();
for(int aux = 0; aux < numberOfColumn; aux++)
{
int num = columnModel.getColumnCount();
TableColumn column = columnModel.getColumnByModelIndex(aux);
columnModel.setColumnVisible(column, true);
}
}
});
toolBarTop.add(reset);
// Create a JCheckBox for each column
for(int i = 0; i < labelsCheckBox.size(); i++)
{
final int index = i;
toolBarTop.add(new JCheckBox(new AbstractAction(labelsCheckBox.get(i)) {
#Override
public void actionPerformed(ActionEvent e) {
TableColumn column = columnModel.getColumnByModelIndex(index);
boolean visible = columnModel.isColumnVisible(column);
columnModel.setColumnVisible(column, !visible);
}
}));
}
setLayout(new BorderLayout());
add(toolBarTop, BorderLayout.NORTH);
add(new JScrollPane(table), BorderLayout.CENTER);
// add(toolBarDown, BorderLayout.SOUTH);
}
final JToolBar toolBarDown = new JToolBar();
toolBarDown.add(new JButton(new AbstractAction("Save Table") {
#Override
public void actionPerformed(ActionEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
}));
}
public void createTable(Class c, Class cAncestor) {
beanTableModel = new BeanTableModel(c, cAncestor);
table = new JTable(beanTableModel);
setLayout(new BorderLayout());
add(new JScrollPane(table), BorderLayout.CENTER);
}
public void createTable(Class c, Class cAncestor, List data) {
beanTableModel = new BeanTableModel(c, cAncestor, data);
table = new JTable(beanTableModel);
setLayout(new BorderLayout());
add(new JScrollPane(table), BorderLayout.CENTER);
beanTableModel.fireTableDataChanged();
}
public void createTable(Class c) {
beanTableModel = new BeanTableModel(c);
table = new JTable(beanTableModel);
setLayout(new BorderLayout());
add(new JScrollPane(table), BorderLayout.CENTER);
}
public void createTable(Class c, List data)
{
beanTableModel = new BeanTableModel(c, data);
table = new JTable(beanTableModel);
setLayout(new BorderLayout());
add(new JScrollPane(table), BorderLayout.CENTER);
}
//to refresh the table everytime there is an update
public void fireTableDataChanged()
{
beanTableModel.fireTableDataChanged();
}
So again, my question is: Isn't my JTable not updated with the new results every time I send new data to it?
You should never invoke fireTableDataChanged manually. Only the TableModel is responsible for invoking this event.
From your code it looks like you are creating a new TableModel, JTable and JScrollPane every time you make a change. Any time you add a component to a visible GUI the basic code should be:
panel.add(....);
panel.revalidate();
panel.repaint();
By default all components have a size of zero so since you don't invoke revalidate() then never get a proper size and there is nothing to paint. Also, it is never a good idea to simply keep adding components to the CENTER of your panel since the old component are still part of the container.
However, there is a better solution. There is no need to keep creating new components. All you need to do is create an new TableModel and then use:
table.setModel( newlyCreatedModel );
and the model will be added to the table and the table will repaint itself automatically.
I have 2 Jcombo Boxs: which is combo1 and combo2
I choose combo1 and I can get information for combo2 but The problem is I can get informatiob for combo2 but it is not updated. I also try to use updata.UI() but it doesn't help.
This is the code in side
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox)e.getSource();
String uname1 = (String)cb.getSelectedItem();
combo2 = update(uname1);
combo2.updateUI();
}
This is code inside update
protected JComboBox update(String name) {
JComboBox tmp = new JComboBox();
//Read Content from XML file (University is bigger than Year)
NodeList nList = doc.getElementsByTagName("University");
System.out.println("Inside Fn " + name);
for(int i = 0 ; i < nList.getLength();i++) {
Element el = (Element)nList.item(i);
if(name.contentEquals(el.getAttributeNode("name").getNodeValue()))
{
NodeList tmpyList = el.getElementsByTagName("Year");
for(int j = 0 ; j < tmpyList.getLength();j++)
{
Element yl = (Element)tmpyList.item(j);
System.out.println(yl.getAttribute("yr"));
tmp.addItem(yl.getAttribute("yr"));
}
}
}
return tmp; //Return ComboBox to combo2
}
Thank you for your kindness, I try to use your code but it is not work (It still not update), please help me
This is my constructor
public JFrameExample() {
String[] comboboxdefault = { "Select" };
JComboBox combo1 = Universitylist();
JComboBox combo2 = new JComboBox(comboboxdefault);
JComboBox combo3 = new JComboBox(comboboxdefault);
uList.addActionListener(this);
yList.addActionListener(this);
dList.addActionListener(this);
JPanel student_information = new JPanel(new GridLayout(0,1));
uList.setName("University List");
yList.setName("Year List");
// University List
student_information.add(combo1);
// Database Year List
student_information.add(combo2);
// Programme List
student_information.add(combo3);
//Add Components to this container, using the default FlowLayout.
add(student_information);
}
This is the combo2 Update it is return String Array
protected String[] updateyList(String name)
{
String[] tmp = null;
//Read from XML file
for(int i = 0 ; i < nList.getLength();i++) {
Element el = (Element)nList.item(i);
if(name.contentEquals(el.getAttributeNode("name").getNodeValue()))
{
NodeList tmpyList = el.getElementsByTagName("Year");
tmp = new String[tmpyList.getLength()];
for(int j = 0 ; j < tmpyList.getLength();j++)
{
Element yl = (Element)tmpyList.item(j);
//Add to String Array
tmp[j] = yl.getAttribute("yr");
}
}
}
return tmp;
}
In the Action Perform
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox)e.getSource();
String uname1 = (String)cb.getSelectedItem();
System.out.println(cb.getName()); // To make sure I got the combo1.
try {
//I change to the model method
DefaultComboBoxModel model = new DefaultComboBoxModel( updateyList(uname1) );
System.out.println(model.getSize());
combo2 = new JComboBox(); // If I don't have this line it will throw error Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
combo2.setModel(model);
} catch (ParserConfigurationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SAXException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
And this is for creating GUI function
private static void createAndShowLoginGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Login");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
JFrameExample newContentPane = new JFrameExample();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
This is main function
public static void main(String[] args)
{
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowLoginGUI();
}
});
}
I think I did something wrong but I don't know where
There is no need to use the updateUI() method.
If you want to change the data in the second combo box then you should change the model (DON'T create a new combo box):
comboBox2.setModel(...);
It will repaint itself automaitcally. You can create a DefaultComboBoxModel and add the data directly to it.
Edit:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class ComboBoxTwo extends JFrame implements ActionListener
{
private JComboBox mainComboBox;
private JComboBox subComboBox;
private Hashtable subItems = new Hashtable();
public ComboBoxTwo()
{
String[] items = { "Select Item", "Color", "Shape", "Fruit" };
mainComboBox = new JComboBox( items );
mainComboBox.addActionListener( this );
// prevent action events from being fired when the up/down arrow keys are used
mainComboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
getContentPane().add( mainComboBox, BorderLayout.WEST );
// Create sub combo box with multiple models
subComboBox = new JComboBox();
subComboBox.setPrototypeDisplayValue("XXXXXXXXXX"); // JDK1.4
getContentPane().add( subComboBox, BorderLayout.EAST );
String[] subItems1 = { "Select Color", "Red", "Blue", "Green" };
subItems.put(items[1], subItems1);
String[] subItems2 = { "Select Shape", "Circle", "Square", "Triangle" };
subItems.put(items[2], subItems2);
String[] subItems3 = { "Select Fruit", "Apple", "Orange", "Banana" };
subItems.put(items[3], subItems3);
// mainComboBox.setSelectedIndex(1);
}
public void actionPerformed(ActionEvent e)
{
String item = (String)mainComboBox.getSelectedItem();
Object o = subItems.get( item );
if (o == null)
{
subComboBox.setModel( new DefaultComboBoxModel() );
}
else
{
subComboBox.setModel( new DefaultComboBoxModel( (String[])o ) );
}
}
public static void main(String[] args)
{
JFrame frame = new ComboBoxTwo();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
}
As you do now, you recreate the combo box every time (by returning the tmp in update method). This as it seems is not reflecting in the UI and maybe others will post the reason. But if you can change to update the combo values (changing the model or deleting the current values and adding the new ones) instead of recreating, then the following post can help you Dynamically change JComboBox