Remove JTable row and column in one event
Hello,
I 've using matrix table in one application.
i need to remove both column and row in single event.
For this i construct
JTable(data[][], header[]);
because dynamically increase data's and header's
What can i do for this?
Create a method that does:
DefaultTableModel model = (DefaultTableModel)table.getModel();
model.removeRow(...)
model.setRowCount(...)
Read the DefaultTableModel API for more information.
Similar Messages
-
Remove specific row and column from 2d array
Hi,
I would like to know how to remove the specific row and column from 2d array.
for example, I have the original 4x4 array as below
2 -1 -1 0
-1 2 0 -1
-1 -1 2 0
-1 -1 -1 3
let say that i want to remove row 2(bold) and column 2(bold), and the new 2d array should get as below
2 -1 0
-1 2 -1
-1 -1 3
Thanks.You can't remove elements of an array, it's fixed at a certain size once created. What you can do however is make a new array and only copy the things you want. Something like:public static void main(String[] args) {
Integer[][] bar = new Integer[5][5];
for (int i = 0; i < bar.length; i++) {
Integer[] baz = bar;
Arrays.fill(baz, i);
System.out.println(Arrays.toString(baz));
Integer[][] muu = new Integer[5][4];
removeColumn(3, bar, muu);
for (Integer[] mee : muu) {
System.out.println(Arrays.toString(mee));
Integer[][] smuu = new Integer[4][5];
removeRow(3, bar, smuu);
for (Integer[] mee : smuu) {
System.out.println(Arrays.toString(mee));
public static <T> void removeRow(int row, T[][] a, T[][] result) {
if (row >= a.length) {
throw new IllegalArgumentException("no row at " + row);
for (int a_r = 0, result_r = 0; a_r < a.length; a_r++) {
if (a_r == row) {
continue;
System.arraycopy(a[a_r], 0, result[result_r], 0, a[a_r].length);
result_r++;
public static <T> void removeColumn(int col, T[][] a, T[][] result) {
for (int i = 0; i < a.length; i++) {
if (col >= a[i].length) {
throw new IllegalArgumentException("no column at [" + i + ", " + col + "]");
for (int a_i = 0, r_i = 0; a_i < a[i].length; a_i++) {
if (a_i == col) {
continue;
result[i][r_i] = a[i][a_i];
r_i++; -
Retreiving Point location with JTable row and column
If I have the row and column in a JTable (in a JPanel), how do I get the Point location offset from the location Point of the JTable or JPanel ?
I think that this may do it.
Point objPoint = new Point( objTable_.getLocation() );
int intRow = objTable_.getSelectedRow();
int intColumn = objTable_.getSelectedColumn();
int intColumnWidth = objTable_.getColumnModel().getColumn( intColumn ).getWidth();
int intColumnMargin = objTable_.getColumnModel().getColumnMargin();
int x = (int) objPoint.getX() + ( (intColumn+1) * intColumnWidth) );
// perhaps * (intColumnWidth + intColumnMargin)
int y = (int) objPoint.getY() + ( (intRow+1) * objTable_.getRowHeight());
// perhaps * (objTable_.getRowHeight() + objTable_.getRowMargin()) -
I have created a JTable that displays the results from a query. My question is how can I get the JTable to display only a given number of rows and columns and have a scrollbar to see the rest of the cells?
Thank youan easy way would be to use setSize()
-
Mapping of JTable Rows and columns and paint it to the JPanel
Hi,
I am using JTable and graphics object to draw the JTable on JPanel. But due to some lack of measurement I am not able to draw table cells correctly.
Apart from this on changing the fontSize I have to redraw it according to the requirement. But when the data size increases it draws absurdly.
I am using jTable.getCellRect() api to get the row width and height. Please help to redraw a JTable cell row and height on JPanel.
I am also attaching a sample code with this mail.
Thanks,
Ajay
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.*;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.table.*;
import java.util.*;
import java.awt.*;
public class SimpleTableDemo extends JPanel {
private boolean DEBUG = false;
private int spacing = 6;
private Map columnSizes = new HashMap();
String[] columnNames = {"First Name",
"Last Name",
"Sport",
"# of Years",
"Vegetarian"};
Object[][] data = {
{"Kathy", "Smith",
"SnowboardingXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", new Integer(5), new Boolean(false)},
{"John", "Doe",
"Rowing", new Integer(3), new Boolean(true)},
{"Sue", "Black",
"Knitting", new Integer(2), new Boolean(false)},
{"Jane", "White",
"Speed reading", new Integer(20), new Boolean(true)},
{"Joe", "Brown",
"Pool", new Integer(10), new Boolean(false)}
final JTable table = new JTable(data, columnNames);
Panel1 panel;
public SimpleTableDemo() {
super(new GridLayout(3,0));
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
//table.setFillsViewportHeight(true);
if (DEBUG) {
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
printDebugData(table);
//Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);
//Add the scroll pane to this panel.
add(scrollPane);
panel = new Panel1();
Rectangle rect = table.getCellRect(0,0,true);
panel.setX(table.getWidth());
panel.setY(0);
panel.setWidth(rect.width);
panel.setHeight(rect.height);
panel.setStr(table.getModel().getValueAt(0,0).toString());
panel.setModel(table);
add(panel);
final JComboBox jNumberComboBoxSize = new JComboBox();
jNumberComboBoxSize.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "11", "12", "14", "16", "18", "20", "24", "30", "36", "48", "72" }));
jNumberComboBoxSize.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jNumberComboBoxSizeActionPerformed(jNumberComboBoxSize);
JPanel panel2 = new JPanel();
panel2.add(jNumberComboBoxSize);
add(panel2);
adjustColumns();
private void jNumberComboBoxSizeActionPerformed(JComboBox jNumberComboBoxSize)
int fontSize = Integer.parseInt(jNumberComboBoxSize.getSelectedItem().toString());
table.setRowHeight(fontSize);
table.setFont(new Font("Serif", Font.BOLD, fontSize));
Rectangle rect = table.getCellRect(0,0,true);
panel.setX(0);
panel.setY(0);
// panel.setWidth(rect.width);
panel.setHeight(rect.height);
panel.setStr(table.getModel().getValueAt(0,0).toString());
panel.setModel(table);
panel.repaint();
table.revalidate();
private void printDebugData(JTable table) {
int numRows = table.getRowCount();
int numCols = table.getColumnCount();
javax.swing.table.TableModel model = table.getModel();
System.out.println("Value of data: ");
for (int i=0; i < numRows; i++) {
System.out.print(" row " + i + ":");
for (int j=0; j < numCols; j++) {
System.out.print(" " + model.getValueAt(i, j));
System.out.println();
System.out.println("--------------------------");
* Adjust the widths of all the columns in the table
public void adjustColumns()
TableColumnModel tcm = table.getColumnModel();
for (int i = 0; i < tcm.getColumnCount(); i++)
adjustColumn(i);
* Adjust the width of the specified column in the table
public void adjustColumn(final int column)
TableColumn tableColumn = table.getColumnModel().getColumn(column);
if (! tableColumn.getResizable()) return;
int columnHeaderWidth = getColumnHeaderWidth( column );
int columnDataWidth = getColumnDataWidth( column );
int preferredWidth = Math.max(columnHeaderWidth, columnDataWidth);
panel.setWidth(preferredWidth);
updateTableColumn(column, preferredWidth);
* Calculated the width based on the column name
private int getColumnHeaderWidth(int column)
TableColumn tableColumn = table.getColumnModel().getColumn(column);
Object value = tableColumn.getHeaderValue();
TableCellRenderer renderer = tableColumn.getHeaderRenderer();
if (renderer == null)
renderer = table.getTableHeader().getDefaultRenderer();
Component c = renderer.getTableCellRendererComponent(table, value, false, false, -1, column);
return c.getPreferredSize().width;
* Calculate the width based on the widest cell renderer for the
* given column.
private int getColumnDataWidth(int column)
int preferredWidth = 0;
int maxWidth = table.getColumnModel().getColumn(column).getMaxWidth();
for (int row = 0; row < table.getRowCount(); row++)
preferredWidth = Math.max(preferredWidth, getCellDataWidth(row, column));
// We've exceeded the maximum width, no need to check other rows
if (preferredWidth >= maxWidth)
break;
return preferredWidth;
* Get the preferred width for the specified cell
private int getCellDataWidth(int row, int column)
// Inovke the renderer for the cell to calculate the preferred width
TableCellRenderer cellRenderer = table.getCellRenderer(row, column);
Component c = table.prepareRenderer(cellRenderer, row, column);
int width = c.getPreferredSize().width + table.getIntercellSpacing().width;
return width;
* Update the TableColumn with the newly calculated width
private void updateTableColumn(int column, int width)
final TableColumn tableColumn = table.getColumnModel().getColumn(column);
if (! tableColumn.getResizable()) return;
width += spacing;
// Don't shrink the column width
width = Math.max(width, tableColumn.getPreferredWidth());
columnSizes.put(tableColumn, new Integer(tableColumn.getWidth()));
table.getTableHeader().setResizingColumn(tableColumn);
tableColumn.setWidth(width);
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("SimpleTableDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
SimpleTableDemo newContentPane = new SimpleTableDemo();
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();
class Panel1 extends JPanel
int x;
int y;
int width;
int height;
String str;
JTable model;
public void setModel(JTable model)
this.model = model;
public void setX(int x)
this.x = x;
public void setY(int y)
this.y = y;
public void setWidth(int w)
this.width = w;
public void setHeight(int h)
this.height = h;
public void setStr(String s)
this.str = s;
public void paint(Graphics g)
super.paint(g);
int initX= 0;
for(int row=0;row < 5; ++row)
initX = x;
for (int col=0;col < 5;++col)
g.drawRect(x,y,width,height);
g.drawString(model.getModel().getValueAt(row,col).toString(),x + 10,y + 10);
x = x + width;
x = initX;
y = y + height;
};an easy way would be to use setSize()
-
How to set the Selected row and Column in JTable
Hi,
i have a problem like the JTable having one Method getSelectedRow() and getSelectedColumn to know the Selected row and Column but if i want to explicitly set the Selected Row and Column,then there is no such type of Methods.If anybody has any solution then i will be thankful to him/her.
Praveen K SaxenaIs that what you're looking for? :myTable.getSelectionModel().setSelectionInterval(row, row);
myTable.getColumnModel().getSelectionModel().setSelectionInterval(column, column); -
JTable fixed Row and Column in the same window
Hi
Could anyone tip me how to make fixed row and column in the same table(s).
I know how to make column fixed and row, tried to combine them but it didnt look pretty.
Can anyone give me a tip?
Thanks! :)Got it to work!
heres the kod.. nothing beautiful, didnt clean it up.
* NewClass.java
* Created on den 29 november 2007, 12:51
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
package tablevectortest;
* @author Sockan
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
public class FixedRowCol extends JFrame {
Object[][] data;
Object[] column;
JTable fixedTable,table,fixedColTable,fixedTopmodelTable;
private int FIXED_NUM = 16;
public FixedRowCol() {
super( "Fixed Row Example" );
data = new Object[][]{
{ "","A","A","A","",""},
{ "a","b","","","",""},
{ "a","","c","","",""},
{ "","","","d","",""},
{ "","","","","e",""},
{ "","","","","","f"},
{ "","b","","","",""},
{ "","","c","","",""},
{ "","","","d","",""},
{ "","","","","e",""},
{ "","b","","","",""},
{ "","","c","","",""},
{ "","","","d","",""},
{ "","","","","e",""},
{ "","","","","","f"},
{ "I","","W","G","A",""}};
column = new Object[]{"A","B","C","D","E","F"};
AbstractTableModel fixedColModel = new AbstractTableModel() {
public int getColumnCount() {
return 1;
public int getRowCount() {
return data.length;
public String getColumnName(int col) {
return (String) column[col];
public Object getValueAt(int row, int col) {
return data[row][col];
public boolean CellEditable(int row, int col) {
return true;
AbstractTableModel model = new AbstractTableModel() {
public int getColumnCount() { return column.length-2; }
public int getRowCount() { return data.length - FIXED_NUM; }
public String getColumnName(int col) {
return (String)column[col+1];
public Object getValueAt(int row, int col) {
return data[row][col+1];
public void setValueAt(Object obj, int row, int col) {
data[row][col+1] = obj;
public boolean CellEditable(int row, int col) {
return true;
AbstractTableModel fixedTopModel = new AbstractTableModel() {
public int getColumnCount() { return 1; }
public int getRowCount() { return data.length - FIXED_NUM; }
public String getColumnName(int col) {
return (String)column[col];
public Object getValueAt(int row, int col) {
return data[row][col];
public void setValueAt(Object obj, int row, int col) {
data[row][col] = obj;
public boolean CellEditable(int row, int col) {
return true;
AbstractTableModel fixedModel = new AbstractTableModel() {
public int getColumnCount() { return column.length-2; }
public int getRowCount() { return FIXED_NUM; }
public Object getValueAt(int row, int col) {
return data[row + (data.length - FIXED_NUM)][col+1];
table = new JTable( model );
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
fixedTable = new JTable( fixedModel );
fixedTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
fixedTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
fixedColTable= new JTable(fixedColModel);
fixedColTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
fixedColTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
fixedTopmodelTable = new JTable(fixedTopModel);
fixedTopmodelTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
fixedTopmodelTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scroll = new JScrollPane( table );
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JScrollPane fixedScroll = new JScrollPane( fixedTable ) {
public void setColumnHeaderView(Component view) {}
fixedScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
fixedScroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
JScrollBar bar = scroll.getVerticalScrollBar();
JScrollBar dummyBar = new JScrollBar() {
public void paint(Graphics g) {}
dummyBar.setPreferredSize(bar.getPreferredSize());
scroll.setVerticalScrollBar(dummyBar);
final JScrollBar bar1 = scroll.getHorizontalScrollBar();
JScrollBar bar2 = fixedScroll.getHorizontalScrollBar();
bar2.addAdjustmentListener(new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
bar1.setValue(e.getValue());
JViewport viewport = new JViewport();
viewport.setView(fixedColTable);
viewport.setPreferredSize(fixedColTable.getPreferredSize());
fixedScroll.setRowHeaderView(viewport);
fixedScroll.setCorner(JScrollPane.UPPER_LEFT_CORNER, fixedColTable
.getTableHeader());
JViewport viewport2 = new JViewport();
viewport2.setView(fixedTopmodelTable);
viewport2.setPreferredSize(fixedTopmodelTable.getPreferredSize());
scroll.setRowHeaderView(viewport2);
scroll.setCorner(JScrollPane.UPPER_LEFT_CORNER, fixedTopmodelTable
.getTableHeader());
scroll.setPreferredSize(new Dimension(600, 19));
fixedScroll.setPreferredSize(new Dimension(600, 100));
getContentPane().add( scroll, BorderLayout.NORTH);
getContentPane().add(fixedScroll, BorderLayout.CENTER);
public static void main(String[] args) {
FixedRowCol frame = new FixedRowCol();
frame.addWindowListener( new WindowAdapter() {
public void windowClosing( WindowEvent e ) {
System.exit(0);
frame.pack();
frame.setVisible(true);
} -
How to freeze row and column in JTable
Hi,
I need to freeze first two rows and columns in a large JTable. I found ways to freeze either a row or a column, but not both at the same time.
Can any of you help ?
Found this code which allows freezing a col. Similar method can be used to freeze column
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JViewport;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableModel;
public class FrozenTablePane extends JScrollPane{
public FrozenTablePane(JTable table, int colsToFreeze){
super(table);
TableModel model = table.getModel();
//create a frozen model
TableModel frozenModel = new DefaultTableModel(
model.getRowCount(),
colsToFreeze);
//populate the frozen model
for (int i = 0; i < model.getRowCount(); i++) {
for (int j = 0; j < colsToFreeze; j++) {
String value = (String) model.getValueAt(i, j);
frozenModel.setValueAt(value, i, j);
//create frozen table
JTable frozenTable = new JTable(frozenModel);
//remove the frozen columns from the original table
for (int j = 0; j < colsToFreeze; j++) {
table.removeColumn(table.getColumnModel().getColumn(0));
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
//format the frozen table
JTableHeader header = table.getTableHeader();
frozenTable.setBackground(header.getBackground());
frozenTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
frozenTable.setEnabled(false);
//set frozen table as row header view
JViewport viewport = new JViewport();
viewport.setView(frozenTable);
viewport.setPreferredSize(frozenTable.getPreferredSize());
setRowHeaderView(viewport);
setCorner(JScrollPane.UPPER_LEFT_CORNER, frozenTable.getTableHeader());
}Hi,
I need to freeze first two rows and columns in a large JTable. I found ways to freeze either a row or a column, but not both at the same time.
Can any of you help ?
Found this code which allows freezing a col. Similar method can be used to freeze column
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JViewport;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableModel;
public class FrozenTablePane extends JScrollPane{
public FrozenTablePane(JTable table, int colsToFreeze){
super(table);
TableModel model = table.getModel();
//create a frozen model
TableModel frozenModel = new DefaultTableModel(
model.getRowCount(),
colsToFreeze);
//populate the frozen model
for (int i = 0; i < model.getRowCount(); i++) {
for (int j = 0; j < colsToFreeze; j++) {
String value = (String) model.getValueAt(i, j);
frozenModel.setValueAt(value, i, j);
//create frozen table
JTable frozenTable = new JTable(frozenModel);
//remove the frozen columns from the original table
for (int j = 0; j < colsToFreeze; j++) {
table.removeColumn(table.getColumnModel().getColumn(0));
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
//format the frozen table
JTableHeader header = table.getTableHeader();
frozenTable.setBackground(header.getBackground());
frozenTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
frozenTable.setEnabled(false);
//set frozen table as row header view
JViewport viewport = new JViewport();
viewport.setView(frozenTable);
viewport.setPreferredSize(frozenTable.getPreferredSize());
setRowHeaderView(viewport);
setCorner(JScrollPane.UPPER_LEFT_CORNER, frozenTable.getTableHeader());
} -
thx guys.....i have a progress now in LV
But now i have new trouble here. Ok i attached my LV file (LV 7.0.1/7.1) and excel form. I just could'nt calculate more than one input value. I want a different result for each value that i enter ... and store it into different rows and column. But it just store at one row.
Attachments:
My Project.vi 31 KB
rumus motor bakar.xls 14 KBduplicate post
-
Select row and column from header in jtable
hello i have a problem to select row and column from header in jtable..
can somebody give me an idea on how to write the program on it.Hi Vicky Liu,
Thank you for your reply. I'm sorry for not clear question.
Answer for your question:
1. First value of Open is item fiels in Dataset2 and this value only for first month (january). But for other month Open value get from Close in previous month.
* I have 2 Dataset , Dataset1 is all data for show in my report. Dataset2 is only first Open for first month
2. the picture for detail of my report
Detail for Red number:
1. tb_Open -> tb_Close in previous month but first month from item field in Dataset2
espression =FormatNumber(Code.GetOpening(Fields!month.Value,First(Fields!open.Value, "Dataset2")))
2. tb_TOTAL1 group on item_part = 1
expression =FormatNumber(Sum(CDbl(Fields!budget.Value)))
3. tb_TOTAL2 group on item_part = 3 or item_part = 4
expression =FormatNumber(Sum(CDbl(Fields!budget.Value)) + ReportItems!tb_TOTAL1.Value )
4. tb_TOTAL3 group on item_part = 2
expression =FormatNumber(Sum(CDbl(Fields!budget.Value)) - ReportItems!tb_TOTAL2 .Value)
5. tb_Close -> calculate from tb_TOTAL3 - tb_Open
expression =FormatNumber(Code.GetClosing(ReportItems!tb_TOTAL3.Value,ReportItems!tb_Open.Value))
I want to calculate the value of tb_Open and tb_Close. I try to use custom code for calculate them. tb_close is correct but tb_Open is not correct that show value = 0 .
My custom code:
Dim Shared prev_close As Double
Dim Shared now_close As Double
Dim Shared now_open As Double
Public Function GetClosing(TOTAL3 as Double,NowOpening as Double)
now_close = TOTAL3 + NowOpening
prev_close = now_close
Return now_close
End Function
Public Function GetOpening(Month as String,NowOpen as Double)
If Month = "1" Then
now_open = NowOpen
Else
now_open = prev_close
End If
Return now_open
End Function
Thanks alot for your help!
Regards
Panda A -
How to save data from JTable multiple rows and columns
Hi Y_Not thanks for your help before...
But what should I do if I want to get/save many data from many column and rows??i don't quite understand your (repeated) question. what is the problem with "multiple rows and columns". Y_NOT and i have shown you ways to access them.
all you need are 2 loops: one around your number of rows and one around the number of columns or vice versa depending in which order you want to save things:
for (int col = 0; col < data.size(); col++) {
for (int row = 0 ; row < data[col].size(); row++) {
// save your data
saveData(data[col].getElementAt(row));
// or use yourtable.getValueAt(row, col);
}this is not a problem of Swing/Java but of simple algorithm...
thomas -
JTable - Swapping the Rows and Columns
This issue was raised in the Java Programming forum. Received initially as a weird requirement, it now seems that it is more common than you might think. Under it's original title it was "JTable - Limitation or Not?"
I introduced the topic here so that the thread perspective can include more experienced Swing developers.
The JTable in it's default layout is intended to hold database tables with records in rows. But what if you want records in columns?
Some have said why? Just accept the row layout. Others have said use a customised form. Both reasonable views. Despite this, others report that the inherrited power of the JTable is worth leveraging and they have been doing it for years. Albeit with messy code in certain cases.
This is a clear candidate for a popular derived component. If the existing JTable were renamed as a JTableRecordPerRow I am describing a JTableRecordPerColumn. The corresponding Table Model must naturally have a getRowClass method and no getColumnClass method.
Java is good at seperating data from display issues so essentially this is only a display issue. The data representation is unaffected.
While this may be so, the TableModel for a JTable makes the link from the display to the data so it must have knowledge about cell type to trigger the correct cell editor for example.
I think it is fair to say that the standard JTable has not be designed with alternative row/column or column/row displays in mind. Hence a single getColumnClass method. However implementing a Table model which exchanges columns for rows is a good start. This leaves a few loose ends where editting is concerned.
While this may not be an ideal topic for anyone just learning Swing I have been encouraged to consider the general case within the limitations of the cell types normally supported by the default Table model.
I would have a guess that this is an established component in many private Java libraries already.
Views and experience on this topic extremely welcome.It appears to me that while interchanging the rows and columns of a JTable is not trivial it is still worthwhile as a workhorse component.
Perhaps the original design could have allowed for an aternative layout manager of somekind but this could easily have made description of records/rows and fields/columns confusing.
I will probably get this summary wrong but I aill attempt to collate the neatest approach as I see it. Criticisms or shorter steps welcome. My thanks to the original contributors traceable from this thread.
In the descriptions below a distinction is made between the normal internal data model representation of a row, called "mrow", and the displayed form "row".
Only the TableModel need be changed.
1 Use row 0 to show the headers by a)disabling the normal TableHeader renderer b)setting the cell renderer for column 0 to the default renderer used by the TableHeader and c)using the getValueAt method to return mcol header values for the row entries.
2 For other row, col values to getValueAt return the value at mcol, mrow where mcol==row-1 & mrow==col.
3 Create a new getCellClass(col,row) method to return the class where mrow==0 and mcol==row-1. Note that I am only trying to immitate the common use of of a database record per mrow here.
4 Override a)getCellRenderer and b)getCellEditor to use getCellClass
Four steps with seven parts seems worth it to me.
The power of Swing!
Many thanks to all. -
I have a Windows server app that generates Excel workbooks to be emailed to political campaign volunteers to be loaded into Numbers on an iPad, edited, then emailed back to be posted to the server database. There are two problems encountered:
1. The Excel workbook has the first row (column headings) and first column (route identifier) of cells locked, so that they will not scroll off the screen, but Numbers doesn't respect the locks, so when the user scrolls horizontally or vertically, the column headings and/or the route identifier scroll off the screen.
2. The Excel workbook has pop-up "tool-tip" type comments in certain column headings in order to provide the user with the acceptable entries for those columns, but Numbers does not respect those. When the user touches any of the commented column heading cells, a context menu appears instead of the comment.
What must I do in the Excel workbook sheets, or what settings can be made in Numbers to correct the above?I imported a Numbers '09 file into Numbers on the iPad. All comments were removed during import. Frozen header row and column were retained.
Thank you for your responses I must ask, however, when you refer to "importing" the Excel file, are you referring to a two step process whereby the Excel file is first converted by some other process into Numbers format, then opened in the Numbers application - which is what I have to do in my PC application to generate the Excel file, and reverse that process to convert the Excel back into my database format - or are you simply referring to opening the file in Numbers as "importing" it? And please excuse any ignorance, as I'm not at all familiar with Apple's terminologies. In fact, I don't own an iPad myself, but rather I have to depend on one of my clients to do the testing for me.
I imported an XLSX file into Numbers on the iPad. The file used "freeze panes" to "freeze" the first column and row. Only warning on import was that it changed fonts. It imported without the first row and column frozen and with no comments. Nothing I can do about the missing comments but it was a simple matter to turn the first column & row into headers and freeze them.
Unfortunately this would not be an efficient solution, since the end users are, for the most part, elderly political campaign volunteers who are fairly computer illiterate. These workbooks are actually canvassing lists - known as walklists. Their purpose is for the volunteers to interview voters, record the results of the interviews, and post the results to a database, which provides the campaigns with valuable strategizing capabilities. Also, these workbooks have multiple pages - as many as 10 or more. and from what I infer from the above, the setting changes would have to be made on each page.
My whole intent in developing this iPad/Tablet methodology was to significantly reduce volunteer's work - which is a recruitment benefit - and eliminate paper. While the latter would be accomplished, the former would not, and in fact would tend to increase it. It's necessary to keep the first row - column headings - and the first column - the route identifier - from scrolling off the page, so that the volunteer won't have to keep scrolling up and down and right and left to know what the data are.
Conclusion: Comments are not supported on the iPad version of Numbers. Frozen headers are not imported from Excel but can be recreated easily.
I was previously directed to the Apple website http://www.apple.com/ipad/from-the-app-store/apps-by-apple/numbers.html which extols the wonders of the Numbers application. About halfway down the page there's a section regarding, "Sliders steppers and pop-ups". The web page states that pop-ups can be set up but, being a marketing site, gives no indication whatsoever as to how it's done. I was hoping someone could tell my if there's any way to carry them over from an Excel file. -
Method to locate row and column in TableView
In a TableView.setOnMouseClicked ()
How to capture that row and column were clicked?I am having problem in populating data from a table in one screen to a Text Field in the other screen. I have two classes FirstClass containing a textbox and a button. On pressing a button a second window is opened containing a Table of values. As the user double clicks a row the value of the second column of the row should be inserted into the textbox of the FirstClass. Code of both the classes is attached. Thanking you in anticipation.
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class FirstClass extends Application {
public static void main(String[] args) {
launch(args);
@Override
public void start(final Stage primaryStage) {
primaryStage.setTitle("First Class");
GridPane gridpane = new GridPane();
gridpane.setPadding(new Insets(5));
gridpane.setHgap(5);
gridpane.setVgap(5);
final TextField userNameFld = new TextField();
gridpane.add(userNameFld, 1, 1);
Button btn = new Button();
btn.setText("Show Table");
gridpane.add(btn, 1, 3);
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
String a = TableClass.showDialog(primaryStage, true, "Table Window" );
userNameFld.setText(a);
StackPane root = new StackPane();
Scene scene =new Scene(root, 300, 250);
root.getChildren().addAll(gridpane);
primaryStage.setScene(scene);
primaryStage.show();
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.StackPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
public class TableClass extends Stage {
private static TableClass dialog;
private static String value = "";
public static class Person {
private final SimpleStringProperty firstName;
private final SimpleStringProperty lastName;
private Person(String fName, String lName) {
this.firstName = new SimpleStringProperty(fName);
this.lastName = new SimpleStringProperty(lName);
public String getFirstName() {
return firstName.get();
public void setFirstName(String fName) {
firstName.set(fName);
public String getLastName() {
return lastName.get();
public void setLastName(String fName) {
lastName.set(fName);
private TableView<Person> table = new TableView<Person>();
private final ObservableList<Person> data =
FXCollections.observableArrayList(
new Person("JACK", "BROWN"),
new Person("JOHN", "VIANNEYS"),
new Person("MICHAEL", "NELSON"),
new Person("WILLIAM", " CAREY")
public TableClass(Stage owner, boolean modality, String title) {
super();
initOwner(owner);
Modality m = modality ? Modality.APPLICATION_MODAL : Modality.NONE;
initModality(m);
setOpacity(1);
setTitle(title);
StackPane root = new StackPane();
Scene scene = new Scene(root, 750, 750);
setScene(scene);
GridPane gridpane = new GridPane();
gridpane.setPadding(new Insets(5));
gridpane.setHgap(5);
gridpane.setVgap(5);
TableColumn firstNameCol = new TableColumn("First Name");
firstNameCol.setMinWidth(100);
firstNameCol.setCellValueFactory(
new PropertyValueFactory<Person,String>("firstName")
TableColumn lastNameCol = new TableColumn("Last Name");
lastNameCol.setMinWidth(200);
lastNameCol.setCellValueFactory(
new PropertyValueFactory<Person,String>("lastName")
table.setItems(data);
table.getColumns().addAll(firstNameCol, lastNameCol);
table.setOnMouseClicked(new EventHandler<MouseEvent>() {
public void handle(MouseEvent me) {
if (me.getClickCount() >= 2) {
String srr = table.getItems().get(table.getSelectionModel().getSelectedIndex()).getLastName();
value = srr;
dialog.hide();
gridpane.add(table, 1, 5,1,20 );
root.getChildren().add(gridpane);
public static String showDialog(Stage stg, Boolean a , String title){
dialog = new TableClass( stg,a, title);
dialog.show();
return value;
} -
Programmactic Access DataGrid Rows and Columns
Hello,
I am new to ActionScript. Can you tell me how can I access
the rows and columns of a data grid?
What I want to do is that when the application load, I will
populate the datagrid with the Xml returned from the webservice.
After that, webservice will be called periodically (using timer)
and the information in the datagrid needs to be updated. The cells
which are updated need to be highlighted.
The datagrid actually contains the stock market data (symbol
name and its other attributes). So once the datagrid has been
populated on application creation, it contains all the symbols in
the market. After that, only attributes of the symbols will change,
like price, volume etc. What I want is that once the datagrid is
populated, i can access the row by using the value of symbol code
and then update the appropriate columns of that symbol. (Xml from
next time will contain only symbols whose values change from last
time).
Below is the code that I have written so far.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="
http://www.adobe.com/2006/mxml"
layout="absolute"
creationComplete="OnAppCreationComplete()" width="100%"
height="100%">
<mx:Script>
<![CDATA[
import mx.rpc.events.ResultEvent;
private var count:uint = 0;
private var messageFramXmlList:XMLList;
private var marketSnapshotTimer:Timer = new Timer(1000);
private function OnAppCreationComplete() : void
this.ajaxServiceInvokerProxy.addEventListener(ResultEvent.RESULT,
this.OnWebServiceResultArrived);
this.ajaxServiceInvokerProxy.InvokeService.send();
this.marketSnapshotTimer.addEventListener(TimerEvent.TIMER,
this.OnSnapshotTimerTick);
this.marketSnapshotTimer.start();
private function
OnWebServiceResultArrived(event:ResultEvent) : void
var marketSnapshotXml:XML = new XML(event.result);
this.messageFramXmlList =
marketSnapshotXml.child("MarketSnapshot").child("MessageFrameList")[0].child("MessageFram e");
this.dgTopPosts.dataProvider = this.messageFramXmlList;
this.btnCounter.label = this.count.toString();
private function OnSnapshotTimerTick(event:TimerEvent) :
void
this.count++;
this.ajaxServiceInvokerProxy.InvokeService.send();
]]>
</mx:Script>
<mx:WebService id="ajaxServiceInvokerProxy"
wsdl="
http://jehanzeb/ajaxserviceinvoker/ajaxserviceinvoker.asmx?wsdl"
useProxy="false">
<mx:operation name="InvokeService">
<mx:request>
<serviceWithComonentName>DetailedSnapshotComponent.MarketSnapshot@TADAWUL</serviceWithCom onentName>
<parametersXml><![CDATA[ <Parameters/>
]]></parametersXml>
</mx:request>
</mx:operation>
</mx:WebService>
<mx:Panel x="10" y="10" width="100%" height="100%"
layout="absolute" title="Market View">
<mx:RichTextEditor id="txtMarketViewResult" x="10" y="10"
width="612" height="194" />
<mx:DataGrid x="10" y="223" id="dgTopPosts" width="100%"
height="303">
<mx:columns>
<mx:DataGridColumn headerText="Symbol Code"
dataField="SymbolID" />
<mx:DataGridColumn headerText="Last Time"
dataField="LastTime" />
<mx:DataGridColumn headerText="Net Change"
dataField="NetChange" width="75"
/>
<mx:DataGridColumn headerText="Percent Change"
dataField="PercentChange" width="75" />
<mx:DataGridColumn headerText="Previous Closed"
dataField="PreviousClosed" width="75"/>
<mx:DataGridColumn headerText="Close" dataField="Close"
width="75"/>
<mx:DataGridColumn headerText="Direction"
dataField="Direction" width="75"/>
<mx:DataGridColumn headerText="BidPrice"
dataField="BidPrice" width="75"/>
<mx:DataGridColumn headerText="AskPrice"
dataField="AskPrice" width="75"/>
<mx:DataGridColumn headerText="BidVolume"
dataField="BidVolume" width="75"/>
<mx:DataGridColumn headerText="AskVolume"
dataField="AskVolume" width="75"/>
</mx:columns>
</mx:DataGrid>
<mx:LinkButton id="btnCounter" x="10" y="528" width="306"
textAlign="left" label="" />
</mx:Panel>
</mx:Application>To achieve what you want, I would have two functions:
* One populates the DataGrid for the first time, i.e. the
inital load
* The other does the 'update' on each interval, since there's
logic required
To update the DataGrid with only the rows that have changed,
you're going to have to compare
the incoming XML to the existing XML in the dataProvider of
the DataGrid, then selectively update the dataProvider.
You can use the
getItemAt() and
setItemAt() methods of the data provider to check each row
against the incoming data. So, some example code:
// This is the function which handles the result of your
'updated data only' webservice
private function handleUpdateInvoke (event:ResultEvent) :
void {
var incoming:XML = new XML(event.result);
var someList:XMLList = incoming.somePattern;
// For each data provider item, check the key and if it
matches
// one of the incoming keys, update it at that index
var numRows = this.dgTopPosts.dataProvider.length;
var existingDataRow:*
for (var i:Number = 0; i < numRows; i++) {
existingDataRow = this.dgTopPosts.dataProvider.getItemAt(i);
for each (var newDataRow:* in someList) {
if (existingDataRow.SymbolID == newDataRow.SymbolID) {
this.dgTopPosts.dataProvider.setItemAt(newDataRow, i);
}
Maybe you are looking for
-
PDF (created in Indesign CS4) separates in CMYK, in stead of PMS
I have sent a PDF, created in Indesign CS4, to the printer. I need the design to be printed in PMS colors, but the printer says the PDF color separates in CMYK, not PMS colors. I'm at my wits end trying to find where I went wrong (I should add I'm a
-
Purchased Photoshop Elements 13 and it won't download. Says it's not a supported file type or the file is damaged. What do I do???
-
OSB - Handling multiRef responses?
I have to connect to an Axis webservice which forces multiRef. Does anyone have suggestions for working with the response? Is there any Oracle tools which will help here so I can properly use XPath? (I've also noticed behavior difference between Serv
-
RH9 and Framesets not displaying properly in IE8
I have just a few framsets built in RH9. They are designed to create a 3-panel view for my end-user. TOC is first panel on the right, then a base procedure, then a 3rd panel should appear when certain links are clicked within the base procedure. It h
-
Disc drive doesn't read discs but says it's working properly
I have a Pavilion dv6000 with vista. I can put in any cd and the disc drive will start spinning but will not read the disc. For example, i put the game "Empire Earth" into the drive and i can here the disc spinning but it will not start. The drive