Proglem with JTable column width
Hi Friends,
I'm using jtable. For that table, i want to set the column width. But it is not working. Here is my code...
class ProcessTable extends JTable {
ProcessTable(){
getTableHeader().setResizingAllowed(true);
setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
TableColumn col = getColumnModel().getColumn(0);
col.setPreferredWidth(100);
col = getColumnModel().getColumn(1);
col.setPreferredWidth(130);
}
Either don't change the TableModel or make sure you don't call fireTableStructureChanged() but fireTableDataChanged() (meaning loading the data doesn't change the columns, just the rows).
Or you can use JTable.setAutoCreateColumnsfromModel(false) and create the TableColumnModel yourself.
Similar Messages
-
Hi,
I'm trying to resize my JTable columns with this code, but it's not working. What I am doing wrong?
for (int i = 0; i < table.getColumnModel().getColumnCount(); i++) {
TableColumn tc = table.getColumnModel().getColumn(i);
int width = (i == 0)? 10 : table.getWidth()/2 - 10; // three columns
tc.setPreferredWidth(width);
Thanks,
Andr�Now my problem is that using either of these methods
is they don't carry the user's selected column width
through updates.It sounds like the change event your table model is firing is causing the entire table to be rebuilt. I would guess that you are firing fireTableStructureChanged() which would cause the entire table to be rebuilt (columns, cell values, etc.) Just fire a change event for the minimum necessary. If you can't identify what data in your table has changed (to fire cell or row change events), but the structure (columns) of the table hasn't changed, just fire fireTableDataChanged(). This will cause the cells to be redrawn with the new values, but shouldn't cause the columns to be rebuilt and resized. -
What method should be used for resizing the particular JTable Column width
I have a four table. Only one table which are on top have a table header. I want that when user resize the topmost table with a mouse other table colume also be resized automatically. So I want to know that what method should be used for resizing the particular JTable Column width.
Thanks
Lalitmaybe you can implement a interface ComponentListener as well as ComponentAdapter with your topmost Table.
for example:
toptable.addComponentListener(
new ComponentAdapter(){
public void componentResized(ComponentEvent e){
table1.setSize(....);
table2.setSize(....);
/*Optionally, you must also call function revalidate
anywhere;*/
); -
Hi,
I have a JTable and I am having problems with the column widths. Currently, I place my JTable in a JScrollPane, and that's it. What I want is this:
1. When the table is initially displayed, I want all the columns to be of equal width and use the entire width of the table (so no empty space at the end of the table)
2. When I resize a column I want the other columns to maintain their size, and just have the scroll bars appear.
3. When I resize the frame/browser that my app is running in, I want the scroll bars to appear.
I tried the different autoResizeModes but I cant get the entire result which I need..any suggestions? Below is a code example...
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class Test1 extends JPanel {
JScrollPane scroller;
JTable table;
String[][] rowData = new String[][] {
{"John", "18"},
{"Bill", "20"},
{"Alex", "17"}
String[] columns = new String[] {
"Name", "Age"
public Test1() {
table = new JTable(rowData, columns);
scroller = new JScrollPane(table);
setLayout(new BorderLayout());
add(scroller, BorderLayout.CENTER);
public static void main(String[] args) {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Test1 t = new Test1();
f.getContentPane().add(t);
f.setSize(600, 600);
f.setVisible(true);
}Forget about my last post. The following code works but I guess you'll have to work on it to make it more elegant.import java.awt.BorderLayout;
import javax.swing.*;
public class Test1 extends JPanel {
String[][] rowData = new String[][]{{"John", "18"}, {"Bill", "20"}, {"Alex", "17"}};
String[] columns = new String[]{"Name", "Age"};
JTable table;
JScrollPane scrollPane;
public Test1() {
super(new BorderLayout());
table = new JTable(rowData, columns);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
scrollPane = new JScrollPane(table);
add(scrollPane, BorderLayout.CENTER);
public void pack() {
System.out.println("pack");
int columnCount = table.getColumnCount();
if (columnCount == 0) {
System.out.println("columnCount = 0");
return;
int width = scrollPane.getViewport().getSize().width;
System.out.println("width = " + width);
if (width == 0) return;
int columnWidth = width / columnCount;
System.out.println("columnWidth = " + columnWidth);
for (int i = 0; i < columnCount; i++) {
table.getColumnModel().getColumn(i).setPreferredWidth(columnWidth);
table.revalidate();
table.repaint();
public static void main(String[] args) {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final Test1 t = new Test1();
f.setContentPane(t);
f.setSize(600, 600);
f.setVisible(true);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
t.pack();
} -
Hi,
I would like to set the column width of JTable.
========================================
JTable table;
DefaultTableModel tableModel;
tableModel = new DefaultTableModel();
table = new JTable( tableModel);
JScrollPane scrollPane = new JScrollPane(table);
for(int i = 0; i < heading.length; i++)
tableModel.addColumn( heading[ i ]);
========================================Did you run the tutorial code? Did it work?
Now compare the tutorial code with your code to determine what is different.
We can't tell you what is different based on the one line of code you posted:
colModel.getColumn(i).setPreferredWidth(100); -
Is there a jtable column width minimum?
Hi,
I try to set the column width in a JTable to 3 or 5, but it seems that there is a hard minimum width of 15.
I use
table.getColumnModel().getColumn(0).setMaxWidth(3);
Just afterwards I get with
System.out.println("width: "+table.getColumnModel().getColumn(0).getWidth());
width: 15
I tried to set autoresize false, validate, repaint, .... Nothing helps. I have no table header. It doesn't matter if I use a custom cell renderer or the default. If I set the width to e.g. 30, it works. But no way to get below 15.
Thanks, Ulrich>
table.getColumnModel().getColumn(0).setMaxWidth(3);
Try this instead
table.getColumnModel().getColumn(0).setPreferredW
dth(3);ICE
The default minimum is 15, there is a setMinWidth function.
table.getColumnModel().getColumn(0).setMinWidth(3);then I would try setting the preferred width. -
JTable Column Width Settings ??
Hello!
Using netbeans IDE 3.6 , I created a jTable with 12 columns with the form builder ...
... Question : I want to set the widths (all of which are different) of the columns when the Table loads.
.... can this be done in Preferences API ?
Thanks!... Thanks!
.... but i just now see how its done ...
AddRFSwitchMain.jTable1.getColumnModel().getColumn(1).setPreferredWidth(100); -
One of the things I don't seem to be able to do cleanly is programatically sizing column widths. What I'm trying to do, presently, is to try and set column widths on numeric columns according to class.
This is what I'm trying:
public static void tweakColumns(JTable table) {
TableColumnModel tcm = table.getColumnModel();
TableModel data = table.getModel();
table.createDefaultColumnsFromModel();
for(int i = 0; i < tcm.getColumnCount(); i++) {
TableColumn col = tcm.getColumn(i);
Class cls = data.getColumnClass(i);
if(cls.equals(Percentage.class))
col.setPreferredWidth(44);
else if(cls.equals(Money.class))
col.setPreferredWidth(60);
else if(cls.equals(Integer.class))
col.setPreferredWidth(20);
table.revalidate();
}I've tried calling this when I set the table up, I've tried defering it with invokeLater. The problem appears to be when there's plenty of space the additional space is applied indiscrimitely, smothering my settings, whereas I want the extra to be applied to the columns I don't set preferences for (typically text fields).
I don't want to impose a maximum column width if the user choses to resize columns. I want to control the distribution of space when it's done by swing.I think your only solution is to set the Preferred sizes of all the columns, even the textfields.
I have done similar thing and it works but only when all the preferred sizes of all the columns are set.
If you record the total width available to all columns before you start setting the preferred sizes of the Percentage, Money and Integer columns you can subtract the sizes of these columns as you set them. When you come out of the loop you will have a value that is what is left of the width. You can then set all the remaining unset columns to values based on this remaining width.
i.e. you have 700 pixels total width the the initial loop you have fields that result in 340 pixels being allocated. You have 360 pixels left over. If you have 3 remaining unset fields then you then set their preferred sizes to be 120 pixels. This, I think, will force swing to allocate in the way you want.
I've never tried it but you might find setting the textfields to unrealistically large Preferred sizes will make swing attempt to do its best and end up with what you want. -
Spark DataGrid with Dynamic Column Width
Lets suppose I have a Spark Datagrid with no explicit typicalItem. When the Datagrid is initialized, the column widths are calcualted correctly based on the contents of the dataprovider. However if I add/remove an item from the dataprovider, or modify the one of the objects in the dataprovider, the column widths never update to reflect the change. Is the the correct behavior for a DataGrid? If so, is there any method I can call to force the DataGrid to recalculate and redraw the column widths?
When Spark DataGrid doesn't have a typicalItem, it uses the first dataProvider item as the typicalItem. If you change that, the DataGrid won't pick it up immediately. You can invalidate the current typicalItem using dataGrid.invalidateTypicalItem().
-
How to set jtable column width
Hello..
I 'm using a simple jtable with the default model. I just want to set each column size to make table smaller Is this possible?
Thanks
Ferasnewdeveloper wrote:
Hello..
I 'm using a simple jtable with the default model. I just want to set each column size to make table smaller Is this possible?
Thanks
FerasI think that your problem probably has more to do with the Layout you're using (or not using) than it does with individual column sizes. What layout are you using?
What happens when you set the size (or preferredSize, minimumSize, and maximumSize) on the whole JTable?
You might also be looking for JTable.[getColumnModel()|http://download-llnw.oracle.com/javase/6/docs/api/javax/swing/JTable.html#getColumnModel%28%29].[getColumn()|http://download-llnw.oracle.com/javase/6/docs/api/javax/swing/table/TableColumnModel.html#getColumn%28int%29].[setPreferredWidth()|http://download-llnw.oracle.com/javase/6/docs/api/javax/swing/table/TableColumn.html#setPreferredWidth%28int%29].
If none of those approaches work, post an SSCCE that demonstrates the problem.
PS- Swing questions belong in the Swing forum. -
Setting the jTable column width
Coming from VB6 to Java is hard for me. Syntax is so much different.
Below is what I am doing to populate the jTable and the values are coming from MySQL. My problem is setting the column width but I am having difficult understanding how to do it. I looked on the website and downloaded some examples and clearly because I am new and I simply do not understand it. I was wonder if someone is willing to modify the codes below on how I should do it. Thanks
private void populate_grid(){
Vector dataVector = new Vector();
Vector columnVector = new Vector();
columnVector.add("ID#");
columnVector.add("Account Description");
columnVector.add("Contact");
columnVector.add("State");
while (myResult.next()) {
Vector rowVector = new Vector();
System.out.println(myResult.getString("acct_name"));
rowVector.add(myResult.getString("cust_id"));
rowVector.add(myResult.getString("acct_name"));
rowVector.add(myResult.getString("main_contact"));
rowVector.add(myResult.getString("main_state"));
dataVector.add(rowVector);
jTable1.setModel(new javax.swing.table.DefaultTableModel(dataVector, columnVector));int rows = 3;
int cols = 3;
JTable table = new JTable(rows, cols);
// Disable auto resizing
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
// Set the first visible column to 100 pixels wide
int vColIndex = 0;
TableColumn col = table.getColumnModel().getColumn(vColIndex);
int width = 100;
col.setPreferredWidth(width); -
Setting exact jtable column width
I need to set each column width in table 200. Columns are added dynamically. And after one column added the previous one width is become small(about 75).
There is test code. Please, help, here is last place I can find the answer.
package visual.jtable;
import javax.swing.*;
import javax.swing.filechooser.FileSystemView;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import com.sun.java.swing.plaf.windows.WindowsLookAndFeel;
public class TestFrame extends JFrame
public JTable table;
public TestFrame()
super("Test frame");
createGUI();
public void createGUI()
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
table = new JTable();
table.setBounds(400, 400, 700, 300);
JScrollPane pane = new JScrollPane(table);
System.out.println(pane.getLayout().getClass().toString());
pane.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
pane.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
panel.add(pane, BorderLayout.CENTER);
getContentPane().add(panel);
static int lastCol = -1;
static int lastRow = -1;
static int visibleRows = 13;
public static void addFile(JTable table, File file)
DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
if (lastRow == visibleRows - 1 || lastCol == -1)
TableColumnModel cm = table.getColumnModel();
table.getTableHeader().setResizingAllowed(false);
table.setAutoscrolls(true);
table.setMaximumSize(new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE));
tableModel.addColumn(String.valueOf(lastCol + 1), new File[visibleRows]);
int index = tableModel.findColumn(String.valueOf(lastCol + 1));
cm.getColumn(index).setMinWidth(200);
cm.getColumn(index).setMaxWidth(200);
cm.getColumn(index).setWidth(200);
cm.getColumn(index).setPreferredWidth(200);
cm.getColumn(index).setResizable(false);
System.out.println("width = " + cm.getColumn(index).getWidth());
System.out.println(table.getAutoResizeMode());
lastCol++;
lastRow = -1;
lastRow++;
tableModel.setValueAt(file, lastRow, lastCol);
public static void main(String[] args) throws Exception
JFrame.setDefaultLookAndFeelDecorated(true);
try
UIManager.setLookAndFeel(new WindowsLookAndFeel());
catch (Exception e)
TestFrame frame = new TestFrame();
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
List<File> f = Arrays.asList(FileSystemView.getFileSystemView().getFiles(new File("C:\\Documents and Settings\\Admin\\Рабочий стол"), false));
for (File file : f)
addFile(frame.table, file);
Thread.sleep(100);
addFile(frame.table, file);
Thread.sleep(100);
addFile(frame.table, file);
Thread.sleep(100);
addFile(frame.table, file);
Thread.sleep(100);
addFile(frame.table, file);
Thread.sleep(100);
addFile(frame.table, file);
Thread.sleep(100);
addFile(frame.table, file);
Thread.sleep(100);
class ListViewTableCellRenderer2 extends DefaultTableCellRenderer
// public ListViewTableCellRenderer(){}
// implements javax.swing.table.TableCellRenderer
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
Component component = super.getTableCellRendererComponent(
table, value, isSelected, hasFocus, row, column);
File file = (File) value;
JLabel label = (JLabel) component;
label.setMinimumSize(new Dimension(200, label.getHeight()));
label.setMaximumSize(new Dimension(200, label.getHeight()));
label.setPreferredSize(new Dimension(200, label.getHeight()));
label.setSize(200, label.getHeight());
label.setMinimumSize(new Dimension(200, label.getHeight()));
label.setText("<table width=\"200\">" +
" <tr>" +
" <td>Month</td>" +
" </tr>" +
"</table>");
if(file == null)
label.setIcon(null);
return label;
//label.setIcon(ViewManager.getCachedIcon(file));
label.setIcon(FileSystemView.getFileSystemView().getSystemIcon(file));
if(file.isHidden())
label.setText("<html><font color = \"red\">" + file.getName() + "</font></html>");
label.setText(file.getName());
label.setText("<table width=\"200\">" +
" <tr>" +
" <td>Month</th>" +
" </tr>" +
"</table>");
return label;
}And after one column added the previous one width is become small(about 75).The model.addColumn() method causes a fireTableStructureChanged event to be generated which causes the TableColumns to be recreated and therefore they default back to their default sizes.
So you need to prevent the columns from being recreated. You do this by adding:
JTable table = new JTable(....);
table.setAutoCreateColumnsFromModel(false);But now you are responsible for adding table columns to the table manually. So your code would be something like;
int index = model.getColumnCount();
model.addColumn(...);
TableColumn tc = new TableColumn(index);
tc.setHeaderValue("" + index);
table.addColumn( tc ); -
I am having trouble initializing column widths in my JTable.... after I create the table I use JColumn.setWidth(int) to set the width of every column. It doesn't work! the table sets
default equal widths. Am trying like this :
if(e.getSource()==column)
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
for(int i=0;i<table.getColumnCount();i++)
table.getColumnModel().getColumn(i).setPreferredWidth(Integer.parseInt(column.getText()));
modelTable.fireTableStructureChanged();
}Instead of setPreferredWidth(..), try setMaxWidth(..)
table.getColumnModel().getColumn(i).setMaxWidth(Integer.parseInt(column.getText()));
I does the trick for me. -
Hi,
I have a JTable that it's columns are in AUTO_RESIZE_OFF mode. The table is in a JScrollPane that it's scrolls are shown when needed. The problem is that the table columns don't fill the scroll pane (horizontally) and because I'm using a layout I don't know that scroll size until the component appears. I need to set the column widths before the table appears.
Is there a solution for this problem?
Thanks,
ShaiTo fill all the scrollpane you must use AUTO_RESIZE_ALL_COLUMNS or another mode different from AUTO_RESIZE_OFF. But in this case, rhe horizontal scrollbar won't appear.
I found a workaround to show the scrollbar when the viewport width is smaller than the preferred width of the JTable.
Denis -
Hi Folks,
I have a grid in which I want to prevent the user to move the set column widths, because this grid has a separate graphik on top of it which would then cease to correspond with the grid columns.
My question: is there any means of difining a grid with <u><b>non-resizeble columns</b>?</u>
Thanks & Regards
Fouad
Message was edited by: Fouad SebbaneHi
In the below structure ,set bold field as 'X' for columns u wish to keep fixed.
Fieldcat
types: begin of slis_fieldcat_main0,
row_pos like sy-curow, " output in row
col_pos like sy-cucol, " position of col
fieldname type slis_fieldname,
tabname type slis_tabname,
currency(5) type c,
cfieldname type slis_fieldname, " currency
ctabname type slis_tabname, " and table
ifieldname type slis_fieldname, " initialcol
quantity(3) type c,
qfieldname type slis_fieldname, " qty
qtabname type slis_tabname, " and table
round type i," round in write statement
exponent(3) type c, " exponent for floats
key(1) type c, " column with key-color
icon(1) type c, " as icon
symbol(1) type c, " as symbol
checkbox(1) type c, " as checkbox
just(1) type c, " (R)ight (L)eft (C)ent.
lzero(1) type c, " leading zero
no_sign(1) type c, " write no-sign
no_zero(1) type c, " write no-zero
no_convext(1) type c,
edit_mask type slis_edit_mask,
emphasize(4) type c, " emphasize
<b>fix_column</b>(1) type c, " Spalte fixieren
do_sum(1) type c, " sum up
no_out(1) type c, " (O)blig.(X)no out
tech(1) type c, " technical field
outputlen like dd03p-outputlen,
offset type dd03p-outputlen, "offset
seltext_l like dd03p-scrtext_l, " long key
seltext_m like dd03p-scrtext_m, " middle
seltext_s like dd03p-scrtext_s, " short
ddictxt(1) type c, " (S)hort (M)
rollname like dd03p-rollname,
datatype like dd03p-datatype,
inttype like dd03p-inttype,
intlen like dd03p-intlen,
lowercase like dd03p-lowercase,
end of slis_fieldcat_main0.
Regards,
Raj
Maybe you are looking for
-
No service for system YYYYY client ZZZ in Integration Directory
We recently applied SP12 to our XI 3 on SR1. When we try to send an IDoc from SAP R/3 system to SQL database (IDoc and JDBC Adapters) we are getting error messag in SM58 (R/3 System) as "No service for system SAPIDS, client 800 in Integration Directi
-
[REQUEST] UEFI GOP VBIOS for R9 270X Gaming 2G
Never mind... Card already has UEFI BIOS... Could not Ultra Fast boot because HD was not GPT formatted... I'm looking for a UEFI GOP VBIOS for my video card. Details of the card: Serial Number: 602-V303-13SB1312019428 Current ROM: www . filedropper .
-
Hi, Does anyone know how to solve this issue. I have looked at the support tips on apple, and both devices are fully up to date. However, AirPlay does not show up anywhere on my iPad, and there does not seem to be any way of connecting it to my apple
-
I want to create a formula for telephone numbers in the formula editor
Is there a way to create a formula for telephone numbers in the "custom" editor in the inspector IE if I enter 2123456789 into a cell it automatically formats it to look like this (212) 345-6789
-
Crash running Photoshop Elements 12
I just installed PE12 (PE12 + Premiere Elements 12 downloaded from the Adobe site). I have also mantained in my PC the previous version PE11. During the installation all run fine. Once installed the program as a first step I run the catalog conversio