JTable header not showing - java

JTable header not showing...
My JTable header wont show even if add it into a container like JScrollPane...tell me why is it happen and how can i fix it or debug it.. I search through internet and all they saying is add container to your jtable, i did but still my header are not showing.
public void table(){
try{
rs = stat.executeQuery("SELECT * FROM payments;");
Vector<String> header = new Vector<String>();
header.add("PAYMENT");
header.add("AMOUNT");
header.add("MODIFIER");
header.add("DATE MODIFIED");
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while(rs.next()) {
Vector<Object> row = new Vector<Object>();
row.add(rs.getString("description"));
row.add(rs.getString("amount"));
row.add(rs.getString("remarks"));
row.add(rs.getString("date"));
data.add(row);
} // loop
table = new JTable(data, header);
JScrollPane scrollPane = new JScrollPane(table);
panel.add(table);
panel.add(table.getTableHeader());
//panel.removeAll();
//scroll.add(table);
validate();
}catch(Exception e){
System.out.println("Error in table: "+e);
}//try and catch
}

Start by removing
panel.add(table.getTableHeader());
The JTable is designed to add it's header to the JScrollPane. An instance of a component can only belong to a one parent/container, the above line is removing it from the scrollpane
Also, change this...
panel.add(table);
To
panel.add(scrollPane);

Same problem I have face
You have to add the JTable to the JScrollPane then add JscrollPane to JFrame
e.g.
JTable table = new JTable();
JScrollPane scrollPane= new JScrollPane(table);
frame.add(scrollPane);

Best JTable Example (Working smoothly just paste in editor and execute as Java application) with dynamic data :
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class TableTest {
private JFrame frame;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TableTest window = new TableTest();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public TableTest() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
table = new JTable();
DefaultTableModel daDefaultTableModel = new DefaultTableModel(0, 0);
String[] columnNames = new String[] {"Column Header1", "Column Header2", "Column Header3"};
daDefaultTableModel.setColumnIdentifiers(columnNames);
//Dummy data for Table
daDefaultTableModel.addRow(new Object[] {"Test1","Test2","Test3"});
daDefaultTableModel.addRow(new Object[] {"Test2","Test2","Test3"});
daDefaultTableModel.addRow(new Object[] {"Test3","Test2","Test3"});
daDefaultTableModel.addRow(new Object[] {"Test4","Test2","Test3"});
daDefaultTableModel.addRow(new Object[] {"Test5","Test2","Test3"});
daDefaultTableModel.addRow(new Object[] {"Test6","Test2","Test3"});
daDefaultTableModel.addRow(new Object[] {"Test7","Test2","Test3"});
daDefaultTableModel.addRow(new Object[] {"Test8","Test2","Test3"});
daDefaultTableModel.addRow(new Object[] {"Test9","Test2","Test3"});
daDefaultTableModel.addRow(new Object[] {"Test10","Test2","Test3"});
daDefaultTableModel.addRow(new Object[] {"Test11","Test2","Test3"});
daDefaultTableModel.addRow(new Object[] {"Test12","Test2","Test3"});
daDefaultTableModel.addRow(new Object[] {"Test13","Test2","Test3"});
daDefaultTableModel.addRow(new Object[] {"Test14","Test2","Test3"});
daDefaultTableModel.addRow(new Object[] {"Test15","Test2","Test3"});
daDefaultTableModel.addRow(new Object[] {"Test16","Test2","Test3"});
daDefaultTableModel.addRow(new Object[] {"Test17","Test2","Test3"});
daDefaultTableModel.addRow(new Object[] {"Test18","Test2","Test3"});
daDefaultTableModel.addRow(new Object[] {"Test19","Test2","Test3"});
table.setModel(daDefaultTableModel);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBounds(10, 38, 414, 212);
frame.getContentPane().add(scrollPane);
}
}

Related

Use JTable in another class

The code below takes data from a text file delimited by "|" and displays it in a JTable. When I run it on the JFrame itself it does work. However I cannot figure out how to move it to another class for itself and make it become a method such as public void viewUser(){}, then call it from the frame on click of a button.
public void viewUser(){
File file = new File("user.dat");
try {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
Object[] lines = br.lines().toArray();
for (Object line : lines) {
String[] row = line.toString().split("\\|");
model.addRow(row);
}
} catch (IOException ex) {
Logger.getLogger(UserManagement.class.getName()).log(Level.SEVERE, null, ex);
}
You are getting this wrong conceptually: a model by itself is meaningless. It needs to be connected to a table in order to show its content.
The code you are showing is creating and filling a new table model. Then that model and all the information is thrown away. Reading data into an object is pointless, when that object isn't made available for further usage!
You might simply change the return type from void to DefaultTableModel and return the model object in the end. And then you can use that pre-filled model for any JTable!
Run this mcve and see if it mocks what you want to do:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class TablePane extends JPanel {
private final JTable table;
public TablePane() {
super(new GridLayout(1,0));
String[] columnNames = {"Name", "Age" };
Object[][] data = {
{"Kathy", new Integer(35)},
{"John", new Integer(63)},
{"Sue", new Integer(28)},
{"Joe", new Integer(70)}
};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
table = new JTable(model);
table.setPreferredScrollableViewportSize(new Dimension(300, 100));
table.setFillsViewportHeight(true);
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);
}
void refresh() {
new Updater(table).getNewData();
}
private static void createAndShowGUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TablePane tablePane = new TablePane();
frame.add(tablePane);
JButton button = new JButton("Change data");
button.addActionListener(e -> tablePane.refresh());
frame.add(button, BorderLayout.NORTH);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
}
class Updater {
private DefaultTableModel model;
Object[][] testData = {
{"Bon", new Integer(15)},
{"Anna", new Integer(31)},
{"Dan", new Integer(82)},
{"Jane", new Integer(20)},
};
public Updater(JTable table) {
model = (DefaultTableModel)table.getModel();
}
void getNewData(){
//if you want to clear data : model.getDataVector().clear();
for (Object[] row : testData) {
model.addRow(row);
}
}
}
As commented by Andrew Thomson mcve with hard coded data is essential.

Removing combobox as the cell editor of a jtable cell

I have made a combobox as cell editor of a column. I want when i create a new row the cell in that column should not have the combobox as the cell editor and should retain JTextField as the cell editor. Here is what i have done so far.
addRow(mainWindow.salesTable);
final TableColumn items = mainWindow.salesTable.getColumnModel().getColumn(0);
final JTextField tfield = new JTextField();
DefaultCellEditor editorqty = new DefaultCellEditor(tfield);
items.setCellEditor(editorqty);
private static void addRow(JTable table) {
DefaultTableModel model = (DefaultTableModel) table.getModel();
Vector row = new Vector();
row.add("");
row.add("");
row.add("");
row.add("");
row.add("");
row.add("");
row.add("");
row.add("");
model.addRow(row);
}
Overriding the getCellEditor(...) method of JTble is one approach:
import java.awt.*;
import java.util.List;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;
public class TableComboBoxByRow extends JPanel
{
List<String[]> editorData = new ArrayList<String[]>(3);
public TableComboBoxByRow()
{
setLayout( new BorderLayout() );
// Create the editorData to be used for each row
editorData.add( new String[]{ "Red", "Blue", "Green" } );
editorData.add( new String[]{ "Circle", "Square", "Triangle" } );
editorData.add( new String[]{ "Apple", "Orange", "Banana" } );
// Create the table with default data
Object[][] data =
{
{"Color", "Red"},
{"Shape", "Square"},
{"Fruit", "Banana"},
{"Plain", "Text"}
};
String[] columnNames = {"Type","Value"};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
JTable table = new JTable(model)
{
// Determine editor to be used by row
public TableCellEditor getCellEditor(int row, int column)
{
int modelColumn = convertColumnIndexToModel( column );
if (modelColumn == 1 && row < 3)
{
JComboBox<String> comboBox1 = new JComboBox<String>( editorData.get(row));
return new DefaultCellEditor( comboBox1 );
}
else
return super.getCellEditor(row, column);
}
};
JScrollPane scrollPane = new JScrollPane( table );
add( scrollPane );
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("Table Combo Box by Row");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new TableComboBoxByRow() );
frame.setSize(200, 200);
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}

JTable, JComboBox - problems in showing JComboBox in second column

I have written this simple program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class JcomboboxJtableDemo extends JPanel
implements ActionListener {
private DefaultTableModel tableModel;
JTable table = new JTable (tableModel);
private JScrollPane scrollpaneTable = new JScrollPane( table );
private JPanel PaneBottoniTabella = new JPanel( );
public JcomboboxJtableDemo() {
super(new BorderLayout());
String[] petStrings = { "Bird", "Cat", "Dog", "Rabbit", "Pig" };
JComboBox comboBox = new JComboBox(petStrings);
comboBox.setSelectedIndex(4);
tableModel = CreateTableModel();
tableModel.insertRow( 0, new Object[] {"Header col1", ""} );
tableModel.insertRow( 0, new Object[] {petStrings[0], ""} );
tableModel.insertRow( 0, new Object[] {petStrings[1], ""} );
tableModel.insertRow( 0, new Object[] {petStrings[2], ""} );
tableModel.insertRow( 0, new Object[] {petStrings[3], ""} );
tableModel.setValueAt("Header col2", 0, 1);
DefaultCellEditor editor = new DefaultCellEditor(comboBox);
table.getColumnModel().getColumn(0).setCellEditor(editor);
table.getColumnModel().getColumn(1).setCellEditor(editor);
//Lay out the demo.
add(comboBox, BorderLayout.PAGE_START);
add(table, BorderLayout.PAGE_END);
setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
}
private final DefaultTableModel CreateTableModel () {
DefaultTableModel modello = new DefaultTableModel( new Object[] { "Col1","Col2" }, 0 ) {
#Override
public boolean isCellEditable(int row, int column) {
return true;
}
};
table.setModel(modello);
return modello;
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("ComboBoxDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
JComponent newContentPane = new JcomboboxJtableDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
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() {
createAndShowGUI();
}
});
}
}
I you try to run it you will see that there is a problem in showing correctly the JComboBox components in the second column, in the first column the are correctly shown and you can see each selected item as set in the code, instead in the second column there are some problems: none on the relative cell.
Could you tell me why? How can I solve the problem?
Thanks
You're using the same JComboBox component for both ColumnModel columns which in turn share the same ComboBoxModel. Any change in the selected item from one column will be reflected in the other column. Create a second combobox
JComboBox comboBox2 = new JComboBox(petStrings);
...
table.getColumnModel().getColumn(1).setCellEditor(editor2);
so that any changes can occur independently in either column.

How to update jtable in runtime?

I am new to JTable.
I want to update the jtable data at runtime in button press event.
Here is my code.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;
import javax.swing.*;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class SetEditableTableCell extends JPanel {
JPanel top = new JPanel();
JPanel bottom = new JPanel();
JButton update = new JButton("Update");
JTable table;
Vector<String> rowOne;
Vector<String> rowTwo;
DefaultTableModel tablemodel;
public SetEditableTableCell() {
this.setLayout(new BorderLayout());
rowOne = new Vector<String>();
rowOne.addElement("Row1-1");
rowOne.addElement("Row1-2");
rowOne.addElement("Row1-3");
rowTwo = new Vector<String>();
rowTwo.addElement("Row2-2");
rowTwo.addElement("Row2-3");
rowTwo.addElement("Row2-4");
Vector<Vector> rowData = new Vector<Vector>();
rowData.addElement(rowOne);
rowData.addElement(rowTwo);
Vector<String> columnNames = new Vector<String>();
columnNames.addElement("Column One");
columnNames.addElement("Column Two");
columnNames.addElement("Column Three");
tablemodel = new DefaultTableModel(rowData, columnNames);
table = new JTable(tablemodel);
// table.setValueAt("aa", 0, 0);
update.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
updatedata();
}
private void updatedata() {
rowOne = new Vector<String>();
rowOne.addElement("updated Row1-1");
rowOne.addElement("updated Row1-2");
rowOne.addElement("updated Row1-3");
rowTwo = new Vector<String>();
rowTwo.addElement("updated Row2-2");
rowTwo.addElement("updated Row2-3");
rowTwo.addElement("updated Row2-4");
// tablemodel.addRow(rowTwo);
tablemodel.fireTableDataChanged();
table.setModel(tablemodel);
System.out.println("button pressed");
// table.setValueAt("aa", 0, 0);
}
});
JScrollPane scrollPane = new JScrollPane(table);
top.add(scrollPane);
bottom.add(update);
add(top, BorderLayout.NORTH);
add(bottom, BorderLayout.SOUTH);
}
public static void main(String args[]) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SetEditableTableCell obj = new SetEditableTableCell();
frame.add(obj);
//frame.setSize(400, 300);
frame.pack();
frame.setVisible(true);
}
}
But it is not updating after pressing update button.
Can anybody solve my problem?
Thanks in advance..
It is not updated because you do not modify the values in your TableModel. By assigning a new Vector to rowOne and rowTwo in your updateData method, you are altering other Vector instances then the ones your TableModel knows about.
A possible solution is to reconstruct the data vector and use the setDataVector method
Construct your own table model using the AbstractTableModel and use it's "event" triggers to notify the JTable of changes to the underlying model

JTable adding new row

I have a JTable with 5 rows at the time of design. Now i have to add more rows as i go dynamically. I am getting array out of bound exception error when i add more rows. How do i solve this issue ?
item_list = new javax.swing.JTable();
item_list.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null},
{null, null, null},
{null, null, null},
{null, null, null}
},
new String [] {
"No.", "Description", "Cost"
}
) {
Class[] types = new Class [] {
java.lang.Integer.class, java.lang.String.class, java.lang.Float.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
item_list.getColumnModel().getColumn(0).setPreferredWidth(30);
item_list.getColumnModel().getColumn(1).setPreferredWidth(100);
item_list.getColumnModel().getColumn(2).setPreferredWidth(50);
jScrollPane2.setViewportView(item_list);
this works for me
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
public class Grow extends JFrame {
private static final Object[][] rowData = {{"Hello", "World"}};
private static final Object[] columnNames = {"A", "B"};
private JTable table;
private DefaultTableModel model;
public Grow() {
Container c = getContentPane();
c.setLayout(new BorderLayout());
model = new DefaultTableModel(rowData, columnNames);
table = new JTable();
table.setModel(model);
c.add(new JScrollPane(table), BorderLayout.CENTER);
JButton add = new JButton("Add");
c.add(add, BorderLayout.SOUTH);
add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
model.addRow(rowData[0]);
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
public static void main(String[] args) {
Grow g = new Grow();
g.setLocationRelativeTo(null);
g.setVisible(true);
}
}
I assume You have a table with six column.
Follow this code ,it will append a new row to already existing table
DefaultTableModel defaultModel = (DefaultTableModel) table.getModel();
Vector newRow = new Vector();
newRow.add("Total Amount Spend");
newRow.add(TotalAmt);
newRow.add(Apaid);
newRow.add(Bpaid);
newRow.add(Cpaid);
newRow.add(Dpaid);
defaultModel.addRow(newRow);
Where JTable table = new JTable(data, columnNames);
The DefaultTableModel has an addRow(...) method that you should be using.
If you need more help then post your SSCCE that demonstrates the problem.

Categories

Resources