I'm trying to use an empty column as a divider between pairs of columns in a JTable. Here's a picture and code for what I have so far. I know I can change the look using a custom TableCellRenderer. Before I go down that road, is there a better way to do this? Any ideas appreciated.
import javax.swing.*;
import javax.swing.table.*;
public class TablePanel extends JPanel {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame f = new JFrame("TablePanel");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.add(new TablePanel());
f.pack();
f.setVisible(true);
}
});
}
public TablePanel() {
TableModel dataModel = new MyModel();
JTable table = new JTable(dataModel);
table.getColumnModel().getColumn(MyModel.DIVIDER).setMaxWidth(0);
JScrollPane jsp = new JScrollPane(table);
jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
this.add(jsp);
}
private static class MyModel extends AbstractTableModel {
private static final int DIVIDER = 2;
private final String[] names = { "A1", "A2", "", "B1", "B2" };
#Override
public int getRowCount() {
return 32;
}
#Override
public int getColumnCount() {
return names.length;
}
#Override
public String getColumnName(int col) {
if (col == DIVIDER) return "";
return names[col];
}
#Override
public Object getValueAt(int row, int col) {
if (col == DIVIDER) return "";
return (row + 1) / 10.0;
}
#Override
public Class<?> getColumnClass(int col) {
if (col == DIVIDER) return String.class;
return Number.class;
}
}
}
On problem with this approach it that the user will need to "tab over" the divider column. You could use the Table Tabbing suggestion to make it more user friendly.
Or if tabbing between the two tables isn't important, then maybe you can use use two tables and put whatever divider you want betweeen the two. The selection model can shared if required.
Edit:
As I suggested above sharing models is easier than writing custom listeners. To keep the scrolling in sync the code would be:
jspa.getVerticalScrollBar().setModel( jspb.getVerticalScrollBar().getModel() );
You can also do the same with the selection model so that highlighting of rows is in sync.
I kind of combined both answers: I used two tables that share one's scrollbar. This works with sorting, and it actually makes the model simpler. Tabbing doesn't matter, but comparing "A" and "B" does. I think I was trying to solve a "view" problem in the "model". I made this a separate answer, because I'd appreciate any critical comments.
public TablePanel() {
this.setLayout(new GridLayout(1, 0, 8, 0));
JTable tableA = new JTable(new MyModel("A"));
tableA.setPreferredScrollableViewportSize(new Dimension(200, 400));
final JScrollPane jspA = new JScrollPane(tableA);
jspA.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
this.add(jspA);
JTable tableB = new JTable(new MyModel("B"));
tableB.setPreferredScrollableViewportSize(new Dimension(200, 400));
final JScrollPane jspB = new JScrollPane(tableB);
jspB.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
this.add(jspB);
tableA.setSelectionModel(tableB.getSelectionModel());
jspA.getVerticalScrollBar().setModel(jspB.getVerticalScrollBar().getModel());
}
Without knowing what do you want to show in this table it's hard to tell whether you've selected good solution or not.
Regarding this solution. This column does not seem like a divider. Paint it with gray/another color, or paint divider header cell in white.
But anyway I'd prefer JScrollPane + two tables inside it instead of this solution.
Please have a look at the answer of this question, some nice new suggestion was given there: Column dividers in JTable or JXTable
Related
How can I obtain a multiline JTable header where the header column correctly enlarges to fit some text and then wraps to a new line?
Something like shown below:
Currently searching for the above requirements returns a lot of solutions of which none really solves the problem:
http://www.javarichclient.com/multiline-column-header/
Creating multi-line header for JTable
Java JTable header word wrap
The above solutions all propose using HTML code, for instance:
String[] columnNames = {
"<html><center>Closing<br>Date</html>",
"<html><center>Open<br>Price</html>",
"<html>Third<br>column</html>"
};
That solution is not elegant for a couple of reasons, mainly because in the case of variable columns names I need to pass the string to a function which strips spaces and subtitutes them with <br> symbols, however if the column text contains very short text that appears in a line of its own.
I would need to decide a minimum and a maximum length of a column and then be able to make text centering possible, the above solution quickly becomes overengineered and unmanageable.
http://www.java2s.com/Code/Java/Swing-Components/MultiLineHeaderTable.htm
http://www.java2s.com/Code/Java/Swing-Components/MultiLineHeaderExample.htm
Above solutions require manually creating a header array with words already correctly split up as in:
public static Object[][] tableHeaders = new Object[][] {
new String[] { "Currency" },
new String[] { "Yesterday's", "Rate" },
new String[] { "Today's", "Rate" },
new String[] { "Rate", "Change" } };
-or-
DefaultTableModel dm = new DefaultTableModel();
dm.setDataVector(
new Object[][] { { "a", "b", "c" }, { "A", "B", "C" } },
new Object[] { "1st\nalpha", "2nd\nbeta", "3rd\ngamma" });
Still not elegant because variable text in the column names would not be feasible.
How to change JTable header height?
Manually setting the header height as in the above solutions is only half of what I want to do, because then text would still not correctly wrap and deciding the height is still not feasible.
Currently all I was able was to create a custom TableCellRenderer but yet no solution:
import java.awt.Component;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import javax.swing.*;
import javax.swing.table.*;
/**
* #version 1.0 11/09/98
*/
public class MultiLineHeaderExample extends JFrame
{
MultiLineHeaderExample()
{
super("Multi-Line Header Example");
DefaultTableModel dm = new DefaultTableModel();
dm.setDataVector(new Object[][]
{
{
"a", "b", "c"
},
{
"A", "B", "C"
}
},
new Object[]
{
"My First Column, Very Long But Space Separated", "short col", "VeryLongNoSpaceSoShouldSomeHowWrap"
});
JTable table = new JTable(dm);
MultiLineHeaderRenderer renderer = new MultiLineHeaderRenderer();
Enumeration enumK = table.getColumnModel().getColumns();
while (enumK.hasMoreElements())
{
((TableColumn) enumK.nextElement()).setHeaderRenderer(renderer);
}
JScrollPane scroll = new JScrollPane(table);
getContentPane().add(scroll);
setSize(400, 110);
setVisible(true);
}
public static void main(String[] args)
{
MultiLineHeaderExample frame = new MultiLineHeaderExample();
frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
}
class MultiLineHeaderRenderer extends JList implements TableCellRenderer
{
public MultiLineHeaderRenderer()
{
ListCellRenderer renderer = getCellRenderer();
((JLabel) renderer).setHorizontalAlignment(JLabel.CENTER);
setCellRenderer(renderer);
}
#Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column)
{
setFont(table.getFont());
String str = (value == null) ? "" : value.toString();
BufferedReader br = new BufferedReader(new StringReader(str));
String line;
Vector v = new Vector();
try
{
while ((line = br.readLine()) != null)
{
v.addElement(line);
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
setListData(v);
return this;
}
}
This here also uses JTextArea and also resizes the header height when the table is resized. The key to the correct calculation of the table header height is setSize(width, getPreferredSize().height);
class MultiLineTableHeaderRenderer extends JTextArea implements TableCellRenderer
{
public MultiLineTableHeaderRenderer() {
setEditable(false);
setLineWrap(true);
setOpaque(false);
setFocusable(false);
setWrapStyleWord(true);
LookAndFeel.installBorder(this, "TableHeader.cellBorder");
}
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
int width = table.getColumnModel().getColumn(column).getWidth();
setText((String)value);
setSize(width, getPreferredSize().height);
return this;
}
}
you need a Conponent that is able to wordwrap its content like JTextArea.
I changed the cell renderer from your SSCCE so that is works initially, but it has a nasty resize behavior.
class MultiLineHeaderRenderer extends JTextArea implements TableCellRenderer {
public MultiLineHeaderRenderer()
{
setAlignmentY(JLabel.CENTER);
setLineWrap(true);
setWrapStyleWord(true);
setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(Color.BLACK),
BorderFactory.createEmptyBorder(3,3,3,3)
));
}
#Override
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
setFont(table.getFont());
String str = (value == null) ? "" : value.toString();
setText(str);
int columnWidth= getColumnWidth();
setRows(str.length()/columnWidth);
return this;
}
}
Here is another approach. This solution has the following advantages:
You need not manually break the column names.
The columns dynamically word-wrap as you resize the columns and/or window.
The header appearance will automatically be consistent with the installed look-and-feel.
Unlike other solutions I have seen, this works even if the first column doesn't wrap (as in the example below).
It has the following disadvantage, however: It creates an unused JTableHeader object for each column, so it's a bit inelegant and probably not suitable if you have many columns.
The basic idea is that you wrap the column names in an <html> tags, and, crucially, every TableColumn gets its own TableCellRenderer object.
I came to this solution after debugging deep into the guts of the Swing table header layout plumbing. Without getting too much into the weeds, the problem is that if the TableColumns don't have a headerRenderer defined, the same default renderer is used for every column header cell. The layout code used for JTableHeader only bothers to ask the renderer of the first column header for its preferred size (see feature 4. above), and because the renderer is re-used, the call to its setText() method triggers the creation of a new View for the label, which, for reasons I'm too tired to even think about explaining, causes the header renderer to always report its preferred unwrapped height.
Here is a quick-and-dirty proof-of-concept:
package scratch;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
#SuppressWarnings("serial")
public class WordWrappingTableHeaderDemo extends JFrame {
class DemoTableModel extends AbstractTableModel {
private ArrayList<String> wrappedColumnNames = new ArrayList<String>();
private int numRows;
DemoTableModel(List<String> columnNames, int numRows) {
for (String name: columnNames)
wrappedColumnNames.add("<html>" + name + "</html>");
this.numRows = numRows;
}
public int getRowCount() {
return numRows;
}
public int getColumnCount() {
return wrappedColumnNames.size();
}
public Object getValueAt(int rowIndex, int columnIndex) {
return Integer.valueOf(10000 + (rowIndex + 1)*(columnIndex + 1));
}
public String getColumnName(int column) {
return wrappedColumnNames.get(column);
}
public Class<?> getColumnClass(int columnIndex) {
return Integer.class;
}
}
public WordWrappingTableHeaderDemo() {
DefaultTableColumnModel tableColumnModel = new DefaultTableColumnModel() {
public void addColumn(TableColumn column) {
// This works, but is a bit kludgey as it creates an unused JTableHeader object for each column:
column.setHeaderRenderer(new JTableHeader().getDefaultRenderer());
super.addColumn(column);
}
};
JTable table = new JTable();
table.setFillsViewportHeight(true);;
table.setColumnModel(tableColumnModel);
table.setModel(
new DemoTableModel(Arrays.asList("Name", "The Second Column Name is Very Long", "Column Three"), 20));
getContentPane().add(new JScrollPane(table));
}
public static void createAndShowGUI() {
WordWrappingTableHeaderDemo app = new WordWrappingTableHeaderDemo();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setLocationByPlatform(true);
app.pack();
app.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {createAndShowGUI();});
}
}
How can I obtain a multiline JTable header where the header column correctly enlarges to fit some text and then wraps to a new line?
Something like shown below:
Currently searching for the above requirements returns a lot of solutions of which none really solves the problem:
http://www.javarichclient.com/multiline-column-header/
Creating multi-line header for JTable
Java JTable header word wrap
The above solutions all propose using HTML code, for instance:
String[] columnNames = {
"<html><center>Closing<br>Date</html>",
"<html><center>Open<br>Price</html>",
"<html>Third<br>column</html>"
};
That solution is not elegant for a couple of reasons, mainly because in the case of variable columns names I need to pass the string to a function which strips spaces and subtitutes them with <br> symbols, however if the column text contains very short text that appears in a line of its own.
I would need to decide a minimum and a maximum length of a column and then be able to make text centering possible, the above solution quickly becomes overengineered and unmanageable.
http://www.java2s.com/Code/Java/Swing-Components/MultiLineHeaderTable.htm
http://www.java2s.com/Code/Java/Swing-Components/MultiLineHeaderExample.htm
Above solutions require manually creating a header array with words already correctly split up as in:
public static Object[][] tableHeaders = new Object[][] {
new String[] { "Currency" },
new String[] { "Yesterday's", "Rate" },
new String[] { "Today's", "Rate" },
new String[] { "Rate", "Change" } };
-or-
DefaultTableModel dm = new DefaultTableModel();
dm.setDataVector(
new Object[][] { { "a", "b", "c" }, { "A", "B", "C" } },
new Object[] { "1st\nalpha", "2nd\nbeta", "3rd\ngamma" });
Still not elegant because variable text in the column names would not be feasible.
How to change JTable header height?
Manually setting the header height as in the above solutions is only half of what I want to do, because then text would still not correctly wrap and deciding the height is still not feasible.
Currently all I was able was to create a custom TableCellRenderer but yet no solution:
import java.awt.Component;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import javax.swing.*;
import javax.swing.table.*;
/**
* #version 1.0 11/09/98
*/
public class MultiLineHeaderExample extends JFrame
{
MultiLineHeaderExample()
{
super("Multi-Line Header Example");
DefaultTableModel dm = new DefaultTableModel();
dm.setDataVector(new Object[][]
{
{
"a", "b", "c"
},
{
"A", "B", "C"
}
},
new Object[]
{
"My First Column, Very Long But Space Separated", "short col", "VeryLongNoSpaceSoShouldSomeHowWrap"
});
JTable table = new JTable(dm);
MultiLineHeaderRenderer renderer = new MultiLineHeaderRenderer();
Enumeration enumK = table.getColumnModel().getColumns();
while (enumK.hasMoreElements())
{
((TableColumn) enumK.nextElement()).setHeaderRenderer(renderer);
}
JScrollPane scroll = new JScrollPane(table);
getContentPane().add(scroll);
setSize(400, 110);
setVisible(true);
}
public static void main(String[] args)
{
MultiLineHeaderExample frame = new MultiLineHeaderExample();
frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
}
class MultiLineHeaderRenderer extends JList implements TableCellRenderer
{
public MultiLineHeaderRenderer()
{
ListCellRenderer renderer = getCellRenderer();
((JLabel) renderer).setHorizontalAlignment(JLabel.CENTER);
setCellRenderer(renderer);
}
#Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column)
{
setFont(table.getFont());
String str = (value == null) ? "" : value.toString();
BufferedReader br = new BufferedReader(new StringReader(str));
String line;
Vector v = new Vector();
try
{
while ((line = br.readLine()) != null)
{
v.addElement(line);
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
setListData(v);
return this;
}
}
This here also uses JTextArea and also resizes the header height when the table is resized. The key to the correct calculation of the table header height is setSize(width, getPreferredSize().height);
class MultiLineTableHeaderRenderer extends JTextArea implements TableCellRenderer
{
public MultiLineTableHeaderRenderer() {
setEditable(false);
setLineWrap(true);
setOpaque(false);
setFocusable(false);
setWrapStyleWord(true);
LookAndFeel.installBorder(this, "TableHeader.cellBorder");
}
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
int width = table.getColumnModel().getColumn(column).getWidth();
setText((String)value);
setSize(width, getPreferredSize().height);
return this;
}
}
you need a Conponent that is able to wordwrap its content like JTextArea.
I changed the cell renderer from your SSCCE so that is works initially, but it has a nasty resize behavior.
class MultiLineHeaderRenderer extends JTextArea implements TableCellRenderer {
public MultiLineHeaderRenderer()
{
setAlignmentY(JLabel.CENTER);
setLineWrap(true);
setWrapStyleWord(true);
setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(Color.BLACK),
BorderFactory.createEmptyBorder(3,3,3,3)
));
}
#Override
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
setFont(table.getFont());
String str = (value == null) ? "" : value.toString();
setText(str);
int columnWidth= getColumnWidth();
setRows(str.length()/columnWidth);
return this;
}
}
Here is another approach. This solution has the following advantages:
You need not manually break the column names.
The columns dynamically word-wrap as you resize the columns and/or window.
The header appearance will automatically be consistent with the installed look-and-feel.
Unlike other solutions I have seen, this works even if the first column doesn't wrap (as in the example below).
It has the following disadvantage, however: It creates an unused JTableHeader object for each column, so it's a bit inelegant and probably not suitable if you have many columns.
The basic idea is that you wrap the column names in an <html> tags, and, crucially, every TableColumn gets its own TableCellRenderer object.
I came to this solution after debugging deep into the guts of the Swing table header layout plumbing. Without getting too much into the weeds, the problem is that if the TableColumns don't have a headerRenderer defined, the same default renderer is used for every column header cell. The layout code used for JTableHeader only bothers to ask the renderer of the first column header for its preferred size (see feature 4. above), and because the renderer is re-used, the call to its setText() method triggers the creation of a new View for the label, which, for reasons I'm too tired to even think about explaining, causes the header renderer to always report its preferred unwrapped height.
Here is a quick-and-dirty proof-of-concept:
package scratch;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
#SuppressWarnings("serial")
public class WordWrappingTableHeaderDemo extends JFrame {
class DemoTableModel extends AbstractTableModel {
private ArrayList<String> wrappedColumnNames = new ArrayList<String>();
private int numRows;
DemoTableModel(List<String> columnNames, int numRows) {
for (String name: columnNames)
wrappedColumnNames.add("<html>" + name + "</html>");
this.numRows = numRows;
}
public int getRowCount() {
return numRows;
}
public int getColumnCount() {
return wrappedColumnNames.size();
}
public Object getValueAt(int rowIndex, int columnIndex) {
return Integer.valueOf(10000 + (rowIndex + 1)*(columnIndex + 1));
}
public String getColumnName(int column) {
return wrappedColumnNames.get(column);
}
public Class<?> getColumnClass(int columnIndex) {
return Integer.class;
}
}
public WordWrappingTableHeaderDemo() {
DefaultTableColumnModel tableColumnModel = new DefaultTableColumnModel() {
public void addColumn(TableColumn column) {
// This works, but is a bit kludgey as it creates an unused JTableHeader object for each column:
column.setHeaderRenderer(new JTableHeader().getDefaultRenderer());
super.addColumn(column);
}
};
JTable table = new JTable();
table.setFillsViewportHeight(true);;
table.setColumnModel(tableColumnModel);
table.setModel(
new DemoTableModel(Arrays.asList("Name", "The Second Column Name is Very Long", "Column Three"), 20));
getContentPane().add(new JScrollPane(table));
}
public static void createAndShowGUI() {
WordWrappingTableHeaderDemo app = new WordWrappingTableHeaderDemo();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setLocationByPlatform(true);
app.pack();
app.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {createAndShowGUI();});
}
}
I´m rather new to Java and programming itself, so excuse me for the question. What I´m trying to do is the following:
I´m making a bookkeeping program. On the column where the income/outcome is displayed, I want it so when the user enters a negative number (eg. -1.150€),
the number turns red( or any color really, but red is what most bookkeeping programs use). only that specific cell on that column only. I have not started with a code yet so I cannot input one here. I also do not need it to be right-aligned since I have already done that.
PS. Sorry if this post/question already exists, I searched but I found nothing that could help me much.
A small example with double values in a single column. This version uses JTable.setDefaultRenderer for Double.class.
You can also set colors
From an override of JTable.prepareRenderer
From a renderer set individually for columns by calling TableColumn.setCellRenderer; TableColumn instances can be retrieved from the TableColumnModel
import java.awt.*;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
#SuppressWarnings("serial")
public class TableWithColors {
protected static JTable createTable() {
Object[][] rows = new Object[][] {{1.23d},{-20.5d},{5.87d},{2.23d},{-7.8d},{-8.99d},{9d},{16.25d},{4.23d},{-26.22d},{-14.14d}};
Object[] cols = new Object[]{"Balance"};
JTable t = new JTable(rows,cols) {
#Override
public Class<?> getColumnClass(int column) {
if(convertColumnIndexToModel(column)==0) return Double.class;
return super.getColumnClass(column);
}
};
t.setDefaultRenderer(Double.class, new DefaultTableCellRenderer(){
#Override
public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column) {
Component c = super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
c.setForeground(((Double) value)>0 ? Color.BLUE : Color.RED);
return c;
}
});
return t;
}
private static JFrame createFrame() {
JFrame f = new JFrame("Table with colors");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new BorderLayout());
f.add(new JScrollPane(createTable()),BorderLayout.CENTER);
f.setSize(new Dimension(60,255));
return f;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createFrame().setVisible(true);
}
});
}
}
Goes like:
I'm working on a small project that involves JTable which requires the user to click a button and add a row to the table (I have named the button as addrow). I have used a custom table model (Mytablemodel) which extends Default table model.
My table is first made up of five rows and 4 columns where afterwards user can click the addrow button to add more rows
Everything in my code works fine except the addrow button which does nothing. I will appreciate any help.
public class AddingNewRows extends JFrame {
JTable mytable;
JButton addrow;
String[] columns={"Admission number","Name","School","Year"};
TableColumn tc;
int defaultrows=5;
int rows=new Mytablemodel().getRowCount(),columnscount=new Mytablemodel().getColumnCount();
List data=new ArrayList();
Mytablemodel mytbm;
//
public AddingNewRows(){
super("adding rows");
for(int initialrows=0; initialrows<5; initialrows++){
String[] items={"1","2","3","4"};
data.add(items);
}
mytbm=new Mytablemodel();
mytable=new JTable(mytbm);
JScrollPane scroll=new JScrollPane(mytable);
addrow=new JButton("ADD ROW");
//
JPanel buttonpanel=new JPanel();
buttonpanel.setLayout(new BoxLayout(buttonpanel,BoxLayout.X_AXIS));
buttonpanel.setAlignmentX(Component.RIGHT_ALIGNMENT);
buttonpanel.add(addrow);
//
add(scroll,BorderLayout.CENTER);
add(buttonpanel,BorderLayout.SOUTH);
addrow.addActionListener(new Myactions());
}
public class Mytablemodel extends DefaultTableModel{
#Override
public String getColumnName(int column) {
return columns[column];
}
#Override
public Object getValueAt(int row, int col){
return ((String[])data.get(row))[col];
}
#Override
public boolean isCellEditable(int row, int col){
return true;
}
#Override
public void setValueAt(Object value,int row, int col){
((Object[])data.get(row))[col]=value;
fireTableCellUpdated(row,col);
}
#Override
public Class getColumnClass(int column){
return getValueAt(0,column).getClass();
}
#Override
public int getColumnCount(){
return columns.length;
}
#Override
public int getRowCount(){
return increaserows;
}
#Override
public void addRow(Object[] mynewdata){
int rownum=data.size();
System.out.println(rownum);
data.add(madata);
fireTableRowsInserted(rownum,rownum);
}
}
//
private class Myactions implements ActionListener{
#Override
public void actionPerformed(ActionEvent event){
if(event.getSource()==addrow){
Object[]newdata={"","","",""};
mytbm.addRow(newdata);
}
}
}
public static void main(String[] args) {
AddingNewRows frame=new AddingNewRows();
frame.setVisible(true);
frame.setSize(400,400);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
}
}
Some notes about your code:
You never should call any of the fireXxx() methods explicitely from the
outside. Those are intended to be called internally by
AbstractTableModel subclasses when needed. Note: IMHO those should
be protected and not public, to avoid use them incorrectly. But for
some reason they made them public.
Your addrow button seems to create a new table model that is not
attached to any JTable so it makes no sense. Your table model should
provide an addRow(...) method in order to add a new row to it. Most
likely you will have to enlarge the two-dimensions array that is the
table model's underlyinig data structure any time a row is added.
As #AndrewThompson already suggested, DefaultTableModel seems a
good match to do what your table model does.
Check rows and columnscount properties initialization. It doesn't
seem right to me.
On the other hand, you say in a comment:
I'm having trouble understanding the fireTableRowsInserted(int,int) method. the parameters themself and
where or when to call the method
This method should be called within the addRow(...) that I've suggested you to create in the second point. This method should enlarge the data structure and notify the TableModelListeners that a new row/s has/have been inserted. The parameters are the first and last indexes respectively. Tipically when you append a new single row to the end of the table model, then both first and last indexes are the same and the new size - 1 of the underlying data structure. Of course, several rows can be inserted and not necessarily at the end of the table model, so you have to figure out the appropriate indexes. See the example shown here which uses a List of custom objects as data structure.
According to your question,You want to add new rows every time the user clicks the addrow button.
Achieve your objective by using DefaultTableModel without creating your own or overriding addrow method.
in my example below,parameters in the DefaultTableModel constructor represents the initial rows(5) and columns(4) that the table will have where after execution, the user can add more rows by clicking the addrow button.
public class AddingNewRows extends JFrame {
DefaultTableModel def;
JTable mytable;
JButton addrow;
//
public AddingNewRows(){
super("adding rows");
def=new DefaultTableModel(5,4);
mytable=new JTable(def);
JScrollPane scroll=new JScrollPane(mytable);
addrow=new JButton("ADD ROW");
//
JPanel buttonpanel=new JPanel();
buttonpanel.setLayout(new BoxLayout(buttonpanel,BoxLayout.X_AXIS));
buttonpanel.add(addrow);
//
add(scroll,BorderLayout.CENTER);
add(buttonpanel,BorderLayout.SOUTH);
addrow.addActionListener(new Myactions());
}
private class Myactions implements ActionListener{
#Override
public void actionPerformed(ActionEvent event){
if(event.getSource()==addrow){
Object[]newdata={"","","",""};
def.addRow(newdata);
}
}
}
public static void main(String[] args) {
AddingNewRows frame=new AddingNewRows();
frame.setVisible(true);
frame.setSize(400,400);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
}
}
Last two days I've been trying to create a data view table in java app with JTable.
Netbeans binding option doesn't work, but nevermind, I managed to create my own TableModel.
Data get shown in the table, but the headers always contain just letters (A, B, C... for each column). At one point everything worked well, but then I wanted to set another model for that particular table and it doesn't show the labels correctly anymore even if I create whole new JPanel and set it up from scratch.
This is my custom TableModel class
public class MyTableModel extends AbstractTableModel{
private ArrayList<Options> list;
String[] headers;
public MyTableModel(ArrayList<Options> list, String[] headers) {
this.list = list;
this.headers = headers;
}
#Override
public int getRowCount() {
return this.list.size();
}
#Override
public int getColumnCount() {
return headers.length;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
if(columnIndex == 0) {
return list.get(rowIndex).getId();
}
if(columnIndex == 1) {
return list.get(rowIndex).getText();
}
else {
return null;
}
} }
And this is part of the code in jframe class(the one which I run)
ArrayList<Options> list;
String[] optionHeaders = {"id", "text"};
public table2frame() {
initComponents();
list = (ArrayList) zadanie_2_app.Zadanie_2_app.findAll();
JTable table2 = new JTable(new MyTableModel(list, optionHeaders));}
AbstractTableModel requires that getColumnName be overridden otherwise placeholder column names are used. Add
#Override
public String getColumnName(int column) {
return headers[column];
}
I wanted to set another model for that particular table and it doesn't show the labels correctly anymore even if I create whole new JPanel and set it up from scratch.
AFAIK understand from this desription, that JTable is container for JTable
put JTable to the JScrollPane, JTable should be placed into JScrollPane, otherwise JTableHeader isn't visible automatically
get JTableHeader from JTable, change LayoutManager for JPanel to BorderLayout, put JTable to CENTER area, JTableHeader to NOTHR area