JTable doesn't add header row - java

I try to add header row to my JTable and next put table on panel.
This is my sample code :
Map <String, Float> tmpCart = new HashMap<String , Float>();
MainPanel.removeAll();
MainPanel.repaint();
tmpCart = cart.GetMap();
DefaultTableModel tab = new DefaultTableModel();
tab.setColumnIdentifiers(new String[] {"Name", "Price"});
for (String key : tmpCart.keySet())
tab.addRow(new Object[] {key, tmpCart.get(key)});
JTable jTab = new JTable(tab);
jTab.setBounds(10, 10, 200, 200);
jTab.setBackground(Color.orange);
jTab.setRowHeight(25);
JScrollPane pan =new JScrollPane(jTab);
MainPanel.add(pan);
// MainPanel.add(jTab);
// pan.repaint();
How do I write it properly?
//answer
I try create JTable dynamically, after push button, I want get data from Hashtable, create table and put this table on panel.
First step is remove all components from panel, and next create JTable using data from Hashmap`
full function:
private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {
Map <String, Float> tmpCart = new HashMap<String , Float>();
MainPanel.removeAll();
MainPanel.repaint();
tmpCart = cart.GetMap();
DefaultTableModel tab = new DefaultTableModel();
tab.setColumnIdentifiers(new String[] {"Name", "Price"});
for (String key : tmpCart.keySet())
tab.addRow(new Object[] {key, tmpCart.get(key)});
JTable jTab = new JTable(tab);
jTab.setBounds(10, 10, 200, 200);
jTab.setBackground(Color.orange);
jTab.setRowHeight(25);
// MainPanel.add(pan);
MainPanel.add(jTab);
}
This code works, create table and put it on panel, but doesn't set first row with column names ( text : "Names" and "Price").

Can't tell exactly what you are doing from the code sample.
If you are trying to dynamically update a table on a visible GUI, then there is not need to create a new table, just reset the TableModel.
table.setModel( model );
If you need more help then post your SSCCE that demonstrates the problem.
Edit:
First step is remove all components from panel,
Why are your removing components from the panel?
If you need to "swap" panels, then use a CardLayout.
If you need to "refresh" existing components, then just reset the model as explained above.
// MainPanel.add(pan);
MainPanel.add(jTab);
The scrollPane should be added to the GUI, not the table.

The table header is another component that only gets added automatically when the table is inside a JScrollPane. Your best bet is to create a JScrollPane via
new JScrollPane(table)
and add that to your MainPanel.
The other option is to added the header directly wherever you want it, and for that you can do:
panel.add(table.getTableHeader())

Try putting it into a JScrollPane.

Related

Saving JTable edits to two dimensional Array

I have a JTable whose cells are editable. However if i edit a cell and refresh the table. The changes are not saved. This is how i have defined the table:
String [] columnNames = {"Application number",
"Name",
"date",
"fileLoc",
"Country"};
//Data for the table
String [][] data = table.tableArray;//tableArray is an array of array of strings.
TableModel model = new DefaultTableModel(data, columnNames);
JTable mainTable = new JTable(model);
model.isCellEditable(data.length,columnNames.length);
contentPane.add(new JScrollPane (mainTable));
I've had a look online but can't seem to find any advice on saving the changes made to a cell. Any help would be very welcome!
I guess i'm not refreshing the table as such. I use frame.dispose()
and then create a new frame with the table in.
then you lost all changes made in the current DefaultTableModel
don't top create a new JFrame with a new DefaultTableModel and a new JTable
all changes from TableCellEditor are changes dispayed in JTables view
JTable (with its model) is prepared for this job, don't to reacreate these Objects on runtime
DefaultTableModel has implemented all notifiers, there no needed to override any others events, nor to fireXxxXxx() programatically, but those events are required for AbstractTableModel
define add this code line for your JTablemainTable.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
DefaultTableModel respesenting your required 2D array

Dynamically adding JTable to JScrollPane

I have a table that I want to populate when the user prompts me to do so. Problem is, I can't anticipate how many rows the table will end up having. In the constructor for my panel where the table will be displayed I have
// add empty scrollPane to JPanel which will later hold table
scrollPane = new JScrollPane();
add(scrollPane);
This class contains a method that will be called when I want to finally display the table
public void displayTable(String[] columnNames, String[][] dataValues)
{
table = new JTable(dataValues, columnNames);
table.setPreferredScrollableViewportSize(new Dimension(300, 80));
table.setFillsViewportHeight(true);
scrollPane.add(table);
this.setVisible(true);
scrollPane.repaint();
}
Problem is, the table never displays. I just see an outline of where the ScrollPane is with no table inside. Why isn't the table displaying and how can I fix it?
You should add component not to JScrollPane but to its JViewport:
scrollPane.getViewport ().add (table);
Instead of adding table to the JScrollPane Create a viewport of scrollpane and then sets its view as table.
using following code instead:
scrollPane.setViewportView(table)
Generally, you create the JTable and the JScrollPane together, even though you have no values yet.
It's better to use a DefaultTableModel, or a TableModel that you extend, for a dynamic table.

Sort a Java JTable by one column [duplicate]

How do i sort jtable column using radio button?
my jtable is defaultTableModel not vectors.
I have already achieve when user press on column header, it will sort, now i have to implement using radio button..
What would be the best way to achieve this?
To do a sort programmatically you add code like the following to your listener:
DefaultRowSorter sorter = ((DefaultRowSorter)table.getRowSorter());
ArrayList list = new ArrayList();
list.add( new RowSorter.SortKey(2, SortOrder.ASCENDING) );
sorter.setSortKeys(list);
sorter.sort();
Add an actionlistener to the radiobutton, sort and set the tableModel.
The Vector argument is an input to defaultTableModel.
final JTable table = new JTable();
JRadioButton button = new JRadioButton();
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//sort your data here
table.setModel(new DefaultTableModel(sortedDate));
table.repaint();// maybe revalidate too
}
});

Display Data in a Jtable upon Row Selection from Another JTable

I have read one of the question in this website. and since I had the same problem with the one who asked the same question as mine, I want to do a follow up question. HOW DO YOU PUT THIS INTO CODE:
Ask the master table what its selected row is (getSelectedRow()).
Convert this view row index to a model row index (convertRowIndexToModel()).
Ask the model for the data at this index, ands extract the ID of the data. The model should be a class that you wrote, extending AbstractTableModel.
Then get the data to display in the three sub-tables from this ID, and change the model (or the data contained in the model) of these three tables.
Thanks in advance. i am quite having a hard time in this part of my program. since i only know about
tablePersonalProperty.setModel(DbUtils.resultSetToTableModel(rs));
when displaying all the items from the table. what i need is to DISPLAY the items with the same id from what i have chosen from the main table...
Before we can help you write code, we need more information.
Do your tables both have exactly the same columns?
Are you using your own custom data model already? If not, then you probably need to try that on your own. I can't write this for you since I don't know what you need to include in your model. If you are using netbeans, then you can use the form designer to help you write the table model. Just look at the properties of the JTable after you add it to the JFrame of JPanel. I ended up creating my own anyway, but the code that Netbeans generated helped get me started.
This sample code will help you to do what you are looking for, it show how to move table row from one table to another in a click event in rows,
public class InsertRows{
public static void main(String[] args) {
new InsertRows();
}
public InsertRows(){
final JTable table, table2;
final DefaultTableModel model, model2;
JFrame frame = new JFrame("Inserting rows in the table!");
String data[][] = {{"Vinod","100"},{"Raju","200"},{"Ranju","300"}};
String col[] = {"Name","code"};
Object[][] selrowData = {};
model = new DefaultTableModel(data,col);
model2 = new DefaultTableModel(selrowData,col);
GridLayout gl = new GridLayout(2,1);
table = new JTable(model);
table2 = new JTable(model2);
//Insert first position
model.insertRow(0,new Object[]{"Ranjan","50"});
//Insert 4 position
model.insertRow(3,new Object[]{"Amar","600"});
//Insert last position
model.insertRow(table.getRowCount(),new Object[]{"Sushil","600"});
ListSelectionModel cellSelectionModel = table.getSelectionModel();
cellSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
cellSelectionModel.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
String selectedData = null;
String selectedData2 = null;
Object[][] val = {};
int selectedRow = table.getSelectedRow();
int selectedColumns = table.getColumnCount();
model2.insertRow(0,new Object[]{(String) table.getValueAt(selectedRow, selectedColumns-selectedColumns),(String) table.getValueAt(selectedRow, selectedColumns-1) });
}
});
frame.setLayout(gl);
frame.add(new JScrollPane(table));
frame.add(new JScrollPane(table2));
frame.setSize(600,600);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Problem with adding JCombobox in JTable in Java?

I have added a combobox in a JTable, the adding code as follows:
Vector<String> header = new Vector<String>();
Vector data = new Vector();
String[] h = new String[]{"Music", "Movie", "Sport"};
header.add("Code");
header.add("Name");
header.add("Salary");
header.add("Hobby");
loadData(); // Add some data to the table
DefaultTableModel tblModel;
tblModel = (DefaultTableModel) this.tblEmp.getModel();
tblModel.setDataVector(data, header);
// Adding combobox to the last column
TableColumn hobbyColumn = tblEmp.getColumnModel().getColumn(3);
hobbyColumn.setCellEditor(new MyComboBoxEditor(h));
Things worked fine until I dynamically add a new row to the table using the code:
Vector v = new Vector();
v.add("E333");
v.add("Peter");
v.add(343);
v.add(""); // This last colum is the combobox so I put it as ""
data.add(v);
tblEmp.updateUI();
Data is added to the table but the combobox in the last column cannot be selected anymore. The combobox is still displayed when I click on the row but cannot select a value.
How can I handle this problem, please?
Never use the updateUI() method. Read the API to see what this method actually does. It has nothing to do with changing the data in a model.
JTable already supports a combo box editor so there is no need to create a custom MyComboBoxEditor. Read the JTable API and follow the link to the Swing tutorial on "How to Use Tables", for a working example of using a combo box as an editor.

Categories