I am using Inner class for the first. I am trying to access a variable table which is declared in outer class, in the inner class MyTableModel. But netbeans is showing the error-Cannot find symbol
This is the complete code.
Import Statements
public class TableDemo extends JPanel {
private boolean DEBUG = true;
public TableDemo() {
super(new GridLayout(1,0));
JTable table = new JTable(new MyTableModel());
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);
}
class MyTableModel extends AbstractTableModel {
private String[] columnNames = {"First Name","Last Name","Sport","# of Years","Dada","Vegiterian"};
private Object[][] data = {
{"Kathy", "Smith",
"Snowboarding", new Integer(5), new Boolean(false),new Boolean(false)},
};
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
return data.length;
}
public String getColumnName(int col) {
return columnNames[col];
}
public Object getValueAt(int row, int col) {
return data[row][col];
}
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
public boolean isCellEditable(int row, int col) {
if (col < 2) {
return false;
} else {
return true;
}
}
public void setValueAt(Object value, int row, int col) {
}
private void printDebugData() {
TableColumn column = null;
for (int i = 0; i < 5; i++) {
column = table.getColumnModel().getColumn(i);
if (i == 2) {
column.setPreferredWidth(100); //third column is bigger
} else {
column.setPreferredWidth(50);
}
}
int numRows = getRowCount();
int numCols = getColumnCount();
for (int i=0; i < numRows; i++) {
System.out.print(" row " + i + ":");
for (int j=0; j < numCols; j++) {
System.out.print(" " + data[i][j]);
}
System.out.println();
}
System.out.println("--------------------------");
}
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("TableDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TableDemo newContentPane = new TableDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
and this is the code in which I am getting the error -
for (int i = 0; i < 5; i++) {
column = table.getColumnModel().getColumn(i);
if (i == 2) {
column.setPreferredWidth(100); //third column is bigger
} else {
column.setPreferredWidth(50);
}
int the line - column = table.getColumnModel().getColumn(i); I am getting the error like - variable table is not found
Please help.
You define the variable in the constructor and not as an instance member. After the constructor code ends, the variable is out of scope. You need to do it like this:
public class TableDemo extends JPanel {
private boolean DEBUG = true;
private JTable table;
public TableDemo() {
super(new GridLayout(1,0));
table = new JTable(new MyTableModel());
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);
}
// Rest of code
You are declaring variable only locally in the constructor. After the constructor is gone (out of scope), the variable is gone. To do it properly, you should define it in a field:
public class TableDemo extends JPanel {
private boolean DEBUG = true;
private JTable table; //define here
public TableDemo() {
super(new GridLayout(1,0));
table = new JTable(new MyTableModel()); //remove Type here
You need an instance variable to access it from an inner class. Your variable has only local scope to the constructor therefore nothing outside the constructor could find it.
Change your code to:
public class TableDemo extends JPanel {
private JTable table;
public TableDemo() {
table = new JTable(new MyTableModel());
//more code
}
// more code
}
Related
This code changes the color of all the column, I need to change the single cell color at time. This code creates a table and installs a TableCellRenderer that modify the column color. It has two buttons that perform this action. The code speaks alone.
import java.awt.*;
import java.util.Random;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.event.*;
public class Board extends JPanel {
private static final long serialVersionUID = 1L;
int boardHeight = 20;
int boardWidth = 10;
JTable table;
Random random = new Random();
public Board() {
setLayout(new BorderLayout()); // !!
DefaultTableModel model = new
DefaultTableModel(boardHeight, boardWidth) {
#Override
public Class<?> getColumnClass(int columnIndex) {
return String.class;
}
};
// !! table = new JTable(this.boardHeight, this.boardWidth);
table = new JTable(model);
for (int row = 0; row < model.getRowCount(); row++) {
for (int col = 0; col < model.getColumnCount(); col++) {
String s = random.nextBoolean() ? "red" : "yellow";
model.setValueAt(s, row, col);
}
}
//table.setDefaultRenderer(String.class, new BoardTableCellRenderer());
BoardTableCellRenderer mcr = new BoardTableCellRenderer();
table.setFocusable(true);
table.setShowGrid(false);
table.setRowMargin(0);
table.setIntercellSpacing(new Dimension(0, 0));
table.setRowSelectionAllowed(false);
table.setFillsViewportHeight(true);
table.setVisible(true);
//this.add(table);
this.setPreferredSize(new Dimension(table.getPreferredSize().width,
(table.getPreferredSize().height + 85)));
javax.swing.JButton b = new javax.swing.JButton("bottone");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//table.setDefaultRenderer(String.class, new BoardTableCellRenderer());
table.getColumnModel().getColumn(table.getSelectedColumn()).setCellRenderer(mcr);
table.revalidate(); table.repaint();
}
});
javax.swing.JButton b1 = new javax.swing.JButton("bottone default");
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
table.setDefaultRenderer(String.class, new DefaultTableCellRenderer());
table.revalidate(); table.repaint();
}
});
/*for (int columnIndex = 0; columnIndex < table.getColumnCount(); columnIndex ++) {
table.getColumnModel().getColumn(columnIndex).setCellRenderer(mcr);
}*/
//JScrollPane p1 = new JScrollPane();
//p1.add(table);
add(b, BorderLayout.SOUTH); // e.g. for the button
add(b1, BorderLayout.NORTH); // e.g. for the button
add(table, BorderLayout.CENTER); // e.g. for the button
}
private static void createAndShowUI() {
JFrame frame = new JFrame("Board");
frame.getContentPane().add(new Board());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
class BoardTableCellRenderer extends DefaultTableCellRenderer {
private static final long serialVersionUID = 1L;
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected, boolean hasFocus, int row, int col) {
Component c = super.getTableCellRendererComponent(table, value,
isSelected, hasFocus, row, col);
TableModel t = table.getModel();
Object valueAt = table.getModel().getValueAt(row, col);
String s = "";
if (valueAt != null) {
s = valueAt.toString();
}
//if (isSelected) {
// System.out.println("row: "+row+" "+"col: "+col);
if (col == 0 && row == 0) {
c.setForeground(Color.YELLOW);
c.setBackground(Color.gray);
}
//}
/* if (s.equalsIgnoreCase("yellow")) {
c.setForeground(Color.YELLOW);
c.setBackground(Color.gray);
} else {
c.setForeground(Color.black);
c.setBackground(Color.WHITE);
}
*/
return c;
}
}
This code changes the color of all the column,
The same renderer is used by all cells in the column.
So you need code something like:
if (!isSelected)
{
if (your special condition)
{
c.setBackground(...);
}
else // reset background to the default
{
c.setBackground(table.getBackground();
}
}
I'm trying to put a JLabel inside my Swing JTable but what I get is apparently the name of the object instead:
This is the class I used to load the JLabel into my table:
/**
* Main Class.
*/
public class Test extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private MyTable tableDest;
private MyTable tableSource;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
Test frame = new Test();
frame.setVisible(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
* #throws Exception
*/
public Test() throws Exception {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JSplitPane splitPane = new JSplitPane();
splitPane.setResizeWeight(0.5);
contentPane.add(splitPane, BorderLayout.CENTER);
tableSource = new MyTable(true);
splitPane.setRightComponent(tableSource);
tableDest = new MyTable(false);
splitPane.setLeftComponent(tableDest);
TransferHandler transferHandler = new MyTransferHandler();
tableSource.setDragEnabled(true);
tableSource.setTransferHandler(transferHandler);
tableSource.setDropMode(DropMode.ON);
tableDest.setDragEnabled(true);
tableDest.setTransferHandler(transferHandler);
tableDest.setDropMode(DropMode.ON);
}
}
/**
* Class for The Table
*/
class MyTable extends JTable {
private static final long serialVersionUID = 1L;
public MyTable(boolean withData) throws Exception {
this( new MyTableModel(withData));
}
public MyTable(MyTableModel tableModel) {
super(tableModel);
setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
#Override
public MyTableModel getModel() {
return (MyTableModel)super.getModel();
}
}
/**
* Class for The JPanel import into The table
*/
class MyTableModel extends AbstractTableModel {
private static final long serialVersionUID = 1L;
private JLabel[] dataSource = new JLabel[16];
public MyTableModel(boolean fill) {
if(fill) {
for(int i = 0; i < dataSource.length; i++) {
dataSource[i] = new JLabel("<html>Text color: <font color='red'>red</font></html>");
}
}
}
#Override
public int getRowCount() {
return 4;
}
#Override
public int getColumnCount() {
return 4;
}
#Override
public Object getValueAt(int row, int col) {
int index = getIndex(row, col);
return dataSource[index];
}
#Override
public void setValueAt(Object aValue, int row, int col) {
int index = getIndex(row, col);
dataSource[index] = (JLabel)aValue;
}
#Override
public Class<?> getColumnClass(int col) {
return JLabel.class;
}
public void removeAt(int row, int col) {
int index = getIndex(row, col);
dataSource[index] = null;
fireTableCellUpdated(row, col);
}
private int getIndex(int row, int col) {
return row*4 + col;
}
}
/**
* Class for the drag'n drop Stuff
*/
class MyTransferHandler extends TransferHandler {
private static final long serialVersionUID = 1L;
#Override
public int getSourceActions(JComponent comp) {
return MOVE;
}
int selectedRow;
int selectedCol;
#Override
public Transferable createTransferable(JComponent comp) {
System.out.println("createTransferable");
MyTable table = (MyTable)comp;
selectedRow = table.getSelectedRow();
selectedCol = table.getSelectedColumn();
String text = (String) table.getValueAt(selectedRow, selectedCol);
System.out.println("DND init for: " + text);
return new StringSelection(text);
}
#Override
public void exportDone(JComponent comp, Transferable trans, int action) {
System.out.println("exportDone");
if (action == MOVE) {
MyTable table = (MyTable)comp;
table.getModel().removeAt(selectedRow, selectedCol);
}
}
#Override
public boolean canImport(TransferSupport support) {
//System.out.println("canImport");
return support.isDrop();
}
#Override
public boolean importData(TransferSupport support) {
System.out.println("importData");
if(canImport(support)) { //to prevent from paste's
DropLocation dl = support.getDropLocation();
Point dropPoint = dl.getDropPoint();
String data;
try {
data = (String)support.getTransferable().getTransferData(DataFlavor.stringFlavor);
System.out.println("DND received: " + data);
} catch (UnsupportedFlavorException | IOException e) {
return false;
}
MyTable table = (MyTable)support.getComponent();
int row = table.rowAtPoint(dropPoint);
int col = table.columnAtPoint(dropPoint);
MyTableModel model = table.getModel();
Object currentValue = model.getValueAt(row, col);
if(currentValue == null) { //if there's currently no value on that cell
model.setValueAt(data, row, col);
model.fireTableCellUpdated(row, col);
return true;
}
}
return false;
}
}
What am I doing wrong? It's not supposed to display a JPanel instead of this text.
I'm trying to put a JLabel inside my Swing Table but what I get is apparentely the Name of the object instead.
JLabel is the default component for a cell in a JTable. I assume you added a JLabel to the default one, which caused its toString method to be invoked and displayed in the default label.
Here I created a new JTable and put your String in all the cells:
public class Test extends JFrame {
static String data = "<html>Text color: <font color='red'>red</font></html>";
static int size = 4;
public Test() {
JTable table = new JTable(size, size);
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
table.getModel().setValueAt(data, i, j);
}
}
add(table);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public static void main(String[] args) {
new Test();
}
}
I need to edit table when user double clicks on row, with new values. I tried with setValuesAt method but it didn't do anything.
This is what I got so far but I don't know how to set new values to Jtable.
public class Table extends JFrame {
private JTable table;
private JScrollPane jsPane;
private DefaultTableModel model;
private JPanel dialogPanel;
private JTextField tf[];
private JLabel lbl[];
private JPanel panel;
Object[] columns = new Object[]{"Name", "Last Name", "ID", "Email"};
Object[][] inData ;
public void prepareAndShowGUI() {
setTitle("Overview");
model = new DefaultTableModel() {
#Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
model.setColumnIdentifiers(columns);
table = new JTable(model);
for (int i = 1; i <= 10; i++) {
model.addRow(new Object[]{"a", "s", "w", "e"});
}
jsPane = new JScrollPane(table);
table.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
int x = e.getX();
int y = e.getY();
int row = table.rowAtPoint(new Point(x, y));
int col = table.columnAtPoint(new Point(x, y));
String array[] = new String[table.getColumnCount()];
for (int i = 0; i < array.length; i++) {
array[i] = (String) table.getValueAt(row, i);
}
populateTextField(array);
JOptionPane.showMessageDialog(null, dialogPanel, "Information", JOptionPane.INFORMATION_MESSAGE);
String[] values = new String[tf.length];
for (int i = 0; i < tf.length; i++) {
values[i] = tf[i].getText();
}
model.setValueAt(values, row, row);
}
}
});
panel = new JPanel(new BorderLayout());
JPanel panel1 = new JPanel();
panel1.setLayout(new BoxLayout(panel1, BoxLayout.X_AXIS));
panel.add(panel1, BorderLayout.NORTH);
panel.add(jsPane, BorderLayout.CENTER);
getContentPane().add(panel);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
prepareDialogPanel();
setVisible(true);
}
private void prepareDialogPanel() {
dialogPanel = new JPanel();
int col = table.getColumnCount();
dialogPanel.setLayout(new GridLayout(col, 1));
tf = new JTextField[col];
lbl = new JLabel[col];
for (int i = 0; i < col; i++) {
lbl[i] = new JLabel(table.getColumnName(i));
tf[i] = new JTextField(10);
dialogPanel.add(lbl[i]);
dialogPanel.add(tf[i]);
}
}
private void populateTextField(String[] s) {
for (int i = 0; i < s.length; i++) {
tf[i].setText(s[i]);
}
}
}
public static void main(String st[])
{
SwingUtilities.invokeLater( new Runnable()
{
#Override
public void run()
{
Table td = new Table();
td.prepareAndShowGUI();
}
});
}
For starters, you should make your model editable, so change this line:
model = new DefaultTableModel() {
#Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
To:
model = new DefaultTableModel() {
#Override
public boolean isCellEditable(int row, int column) {
return true; //use the row and col to determine which
//cells are editable. If you want all, have this return true.
}
};
This will invoke the JTable's DefaultCellEditor, which will then call on the model's setValueAt method, when the user has made the change on the edit.
All of these components can be replaced with custom components to perform different actions.
Here's the official Oracle documentation on JTables:
https://docs.oracle.com/javase/tutorial/uiswing/components/table.html
If you're trying to get your dialog to work, the problem is in these line:
String[] values = new String[tf.length];
for (int i = 0; i < tf.length; i++) {
values[i] = tf[i].getText();
}
model.setValueAt(values, row, row);
Basically the setValueAt only works on a cell by cell basis. You can't update a whole row like this. Instead try:
for(int i=0;i<tf.length;i++)
{
model.setValueAt(tf[i].getText(), row, i);
}
I'm working on jTable and I intend on deleting specific rows as part of the data manipulation to be conducted on the table. Essentially I've been able to successfully delete a row which the user would specify but I what I really want to do is to delete several rows based on boolean states or check boxes that are selected as part one of the four columns of the table.
I've attached a screenshot as to the current result of running the code and would like to be able to delete the rows based on the selected boolean states or check boxes.
Below is my code including my table model code which extends the AbstractTableModel:
package com.TableRowSelectProgramatically;
import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;
#SuppressWarnings("serial")
public class JTableRowSelectProgramatically extends JPanel {
public MyTableModel MyTableModel;
public String Cell1 = "ABCD";
public JTableRowSelectProgramatically() {
initializePanel();
}
private void initializePanel() {
setLayout(null);
setPreferredSize(new Dimension(1250, 700));
// Table model
MyTableModel = new MyTableModel();
// Table
final JTable table = new JTable(MyTableModel);
table.setFillsViewportHeight(true);
// Row data
Object[] values = {Cell1, "EFGH", "IJKL", new Boolean(false)};
Object[] values2 = {"UVWX","QRST","MNOP", new Boolean(false)};
Object[] values3 = {"ABCD","YZAB","CDEF", new Boolean(false)};
final Object[] values4 = {"QWERTY","YTREWQ","QWERTY", new Boolean(false)};
// Insert row data
MyTableModel CustomTableModel = (MyTableModel) table.getModel();
CustomTableModel.insertData(values);
CustomTableModel.insertData(values2);
CustomTableModel.insertData(values3);
CustomTableModel.insertData(values);
CustomTableModel.insertData(values2);
CustomTableModel.insertData(values3);
CustomTableModel.insertData(values);
CustomTableModel.insertData(values2);
CustomTableModel.insertData(values3);
// Create edit menu label
JLabel labelEditMenu = new JLabel("EDIT MENU:\n");
// Create add row btn
JButton addRow = new JButton("Add Row");
// Attach listener for add row btn
addRow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
MyTableModel.insertData(values4);
}
});
// Create delete row btn
JButton deleteRow = new JButton("Delete Row");
// Attach listener for delete btn
deleteRow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
MyTableModel.removeRow(1);
}
});
// Create scroll pane
JScrollPane pane = new JScrollPane(table);
pane.setBounds(30, 30, 500, 500);
//
JTextField AgentIDTextField = new JTextField();
// Populate the JPanel
JPanel dataEntryPanel = new JPanel(new FlowLayout());
//dataEntryPanel.setBackground(Color.orange);
dataEntryPanel.setBounds(540, 30, 500, 50);
//dataEntryPanel.add(AgentIDTextField);
dataEntryPanel.add(labelEditMenu);
dataEntryPanel.add(addRow);
dataEntryPanel.add(deleteRow);
// Join up GUI
add(pane);
add(dataEntryPanel);
}
// Enable visibity of frame
public static void showFrame() {
JPanel panel = new JTableRowSelectProgramatically();
JFrame frame = new JFrame("Test table");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
}
// Launch prog
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JTableRowSelectProgramatically.showFrame();
}
});
}
// Create custom table model for data entry
class MyTableModel extends AbstractTableModel {
private String[] columnNames = {"COLUMN 0", "COLUMN 1", "COLUMN 2", "COLUMN 3"};
private Vector data = new Vector();
#Override
public int getRowCount() {
return data.size();
}
#Override
public int getColumnCount() {
return columnNames.length;
}
#SuppressWarnings("rawtypes")
#Override
public Object getValueAt(int row, int col) {
return ((Vector) data.get(row)).get(col);
}
public String getColumnName(int col){
return columnNames[col];
}
public Class getColumnClass(int c){
return getValueAt(0,c).getClass();
}
public void setValueAt(Object value, int row, int col){
((Vector) data.get(row)).setElementAt(value, col);
fireTableCellUpdated(row,col);
}
public boolean isCellEditable(int row, int col){
if (3 == col){
return true;
}
else {
return false;
}
}
public void insertData(Object[] values){
data.add(new Vector());
for(int i =0; i<values.length; i++){
System.out.println("data.size is: " + data.size());
((Vector) data.get(data.size()-1)).add(values[i]);
}
fireTableDataChanged();
}
public void removeRow(int row){
data.removeElementAt(row);
fireTableDataChanged();
}
}
}
New attempt at deleting rows of a JTable:
public void deleteRow() {
for (int i = 0; i < getRowCount(); i++) {
Object columnState = getValueAt(i, 3);
System.out.println("STEP 6 - In row " + i + " boolean value is: " + columnState);
boolean columnStateAsBoolean = (Boolean) columnState;
System.out.println("STEP 6 - In row " + i + " Column State As Boolean is: " + columnStateAsBoolean);
if(columnStateAsBoolean == true) {
removeRow(i);
}
System.out.println("-------------------------------------");
}
}
I really want to do is to delete several rows based on boolean states or check boxes
create a loop that starts on the last row and counts down to 0.
Then for every row you use the table.getValueAt(...) method to get the Boolean value of the column.
If the value is true then delete the row.
//Try something like this
int rowCount=table.getSelectedRowCount();//get selected row's count
int row;
if(rowCount>0)
{
while((row=table.getSelectedRow())!=-1)
(DefaultTableModel)table.getModel().removeRow(table.convertRowIndexToModel(row));
}
For initialization:
Vector<Vector> rowdata = new Vector<Vector>();
Vector columnname = new Vector();
JTabel result = new JTable(rowdata, columnname);
JScrollPane sqlresult = new JScrollPane(result);
In the later part, I assign values in rowdata and columnname vector. How to show new values in JTable on GUI?
In addition..
result.repaint();
..and..
((DefaultTableModel)result.getModel()).fireTabelDataChanged()
..seem to do nothing.
1) use DefaultTableModel for JTable
2) define Column Class
3) add row(s) DefaultTableModel.addRow(myVector);
for example
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
public class DefaultTableModelDemo {
public static final String[] COLUMN_NAMES = {
"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"
};
private DefaultTableModel model = new DefaultTableModel(COLUMN_NAMES, 0);
private JTable table = new JTable(model);
private JPanel mainPanel = new JPanel(new BorderLayout());
private Random random = new Random();
public DefaultTableModelDemo() {
JButton addDataButton = new JButton("Add Data");
JPanel buttonPanel = new JPanel();
buttonPanel.add(addDataButton);
addDataButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
addDataActionPerformed();
}
});
model = new DefaultTableModel(COLUMN_NAMES, 0) {
private static final long serialVersionUID = 1L;
#Override
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
};
table = new JTable(model) {
private static final long serialVersionUID = 1L;
#Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
Component c = super.prepareRenderer(renderer, row, column);
if (isRowSelected(row) && isColumnSelected(column)) {
((JComponent) c).setBorder(new LineBorder(Color.red));
}
return c;
}
};
mainPanel.add(new JScrollPane(table), BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
}
private void addDataActionPerformed() {
for (int i = 0; i < 5; i++) {
Object[] row = new Object[COLUMN_NAMES.length];
for (int j = 0; j < row.length; j++) {
row[j] = random.nextInt(5);
}
model.addRow(row);
}
}
public JComponent getComponent() {
return mainPanel;
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("DefaultTableModelDemo");
frame.getContentPane().add(new DefaultTableModelDemo().getComponent());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
rowdata and columnname are used for the initialization of JTable, after the component JTable exists you need to use JTable.getColumnModel() and JTable.getModel() to add columns or rows.
Or JTable.addColumn(TableColumn aColumn) if you only wants to add a column.
Look here if you want to know how to add a row following an example.