I am having a problem on adjusting the height of a jtable whenever I insert rows. I have tried using setsize() and setPreferredScrollableViewportsize() for both table and scrollpane of the table. Could it be a problem in layout manager?
I also tried increasing the size of jpanel too upon inserting each row. BTW, the table lies in a panel and that panel lies in a jDialog. I am using free design in NetBeans for UI building.
Try the following... But make sure you editable option is false!
DefaultTableModel model = (DefaultTableModel)table.getModel();
table.setModel(model);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
final TableColumnModel colModel = table.getColumnModel();
for(int column=0; column<table.getColumnCount();column++){
int width = 15;
for(int row=0; row<table.getRowCount();row++){
TableCellRenderer render = table.getCellRenderer(row, column);
Component component = table.prepareRenderer(render, row, column);
width = Math.max(component.getPreferredSize().width+1, width);
}
if(width>300){
width = 300;
colModel.getColumn(column).setPreferredWidth(width);
}
}
Related
I'm making an application in eclipse with swing and jfreechart and I have the following problem:
As you can see in the screenshot I have a frame with a few components. The problem is about the JTable, which always has the same size, no matter if I resize the window. I want the table to resize the same way other components do, like the ChartPanel at the right, and I don't know how to do it. The contentPane has a BorderLayout with three panels:
The scrollPane for the JTable (WEST)
The ChartPanel (CENTER)
The panel for the buttons (SOUTH)
The code for the JTable creation is this:
private JTable getTasksTable() {
if (tasksTable == null) {
tasksTable = new JTable(new DefaultTableModel(new Object[] { "ID", "Duration", "Due-Date" }, 0) {
private static final long serialVersionUID = 1L;
#Override
public boolean isCellEditable(int row, int column) {
return false;
}
});
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment(SwingConstants.CENTER);
for (int i = 0; i < tasksTable.getColumnModel().getColumnCount(); i++) {
tasksTable.getColumnModel().getColumn(i).setCellRenderer(centerRenderer);
}
tasksTable.getTableHeader().setDefaultRenderer(centerRenderer);
tasksTable.getTableHeader().setBorder(new LineBorder(new Color(0, 0, 0)));
tasksTable.setBorder(new LineBorder(new Color(0, 0, 0)));
tasksTable.setFillsViewportHeight(true);
}
return tasksTable;
}
The scrollPane for the JTable (WEST), The ChartPanel (CENTER), The panel for the buttons (SOUTH)
Well, the way a BorderLayout works is that:
the components in the WEST/EAST are sized at the preferred width of the component.
The component in the CENTER gets the remaining width.
So in your case the scrollpane is a fixed width and the width of the chart panel varies.
If you want both the scrollpane and the chart panel width to change as the frame size changes you need to use a different layout manager.
In this case you could use a panel with a GridBagLayout for the scrollpane and chart components. Then GridBagLayout will assign space at the preferred size of each component. Then you can specify the weightx constraint for each component to specify what percentage of extra space goes to each component as the frame with is increased.
Read the section from the Swing tutorial on How to Use GridBagLayout for more information on the constraints and working examples to get you started.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have a JTable with cells that have variable heights because of there Content. I accomplished this by using a JTextArea in my TableCellRenderer. I want to Color parts of the String in different colors. JTextPane supports HTML tags and text area doesn't but with text pane it is not possible to change the height of the cell.
Any idea how I can use variable cell heights and coloring of the string with JTable?
public class LineWrapCellRenderer extends JTextPane implements TableCellRenderer {
int rowHeight = 0; // current max row height for this scan
final int paddingRight = 4;
final int paddingLeft = 4;
Border padding = BorderFactory.createEmptyBorder(5, paddingLeft, 5, paddingRight);
#Override
public Component getTableCellRendererComponent(
JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column){
setContentType("text/html");
setText(setHTML((String) value));
setSelectionColor(Color.BLUE);
this.setBorder(padding);//Abstände der Zeilen
//markieren fals selektiert
if (isSelected){
setBackground(table.getSelectionBackground());
// setForeground(table.getSelectionForeground());
}
else
{
setBackground(table.getBackground());
// setForeground(table.getForeground());
}
// current table column width in pixels
int colWidth = table.getColumnModel().getColumn(column).getWidth() + table.getIntercellSpacing().width;
// set the text area width (height doesn't matter here)
Dimension dim = new Dimension(colWidth, 1);
setSize(dim);
// get the text area preferred height and add the row margin
int height = getPreferredSize().height + table.getRowMargin();
// ensure the row height fits the cell with most lines
if (height != table.getRowHeight(row)) {
table.setRowHeight(row, height);
}
return this;
}
using this code with JTextPane has no effect on the cell height. using the same code with JTextArea the height is adjusted.
You can set/change the height of each individual row with the following method:
JTable.setRowHeight(int row, int rowHeight);
As for coloring parts of the text displayed in a cell, you can simply use HTML code, e.g.
String value = "<html>Following word is <font color=\"red\">RED</font>.</html>";
The default table cell renderer (DefaultTableCellRenderer) uses/extends JLabel which properly handles/accepts HTML code.
Manual height
See this example:
JFrame f = new JFrame("Test");
JTable t = new JTable();
((DefaultTableModel)t.getModel()).setDataVector(new Object[][]{
{"<html>Next word is <font color=\"red\">RED</font>.</html>", "50px"},
{"<html>Following is <font color=\"blue\">BLUE</font>.<br><br>"
+ "Long lines are automatically wrapped"
+ " as this long line demonstrates it.</html>", "150px"},
}, new Object[]{"Formatted text","Height"});
t.setRowHeight(0, 50);
t.setRowHeight(1, 150);
f.add(new JScrollPane(t));
f.pack();
f.setVisible(true);
Result:
Packing / Authoheight
If you want to "pack" all your rows to have the minimum height the value requires, you can do it like this:
JFrame f = new JFrame("Test");
JTable t = new JTable();
((DefaultTableModel) t.getModel()).setDataVector(new Object[][] {
{"<html>Next word is <font color='red'>RED</font>.</html>", "50px" },
{"<html><body style='width:200px'>Following is"
+ " <font color='blue'>BLUE</font>.<br><br>"
+ "Long lines are automatically wrapped "
+ "as this long line demonstrates it.</body></html>", "150px" }, },
new Object[] {"Formatted text", "Height"});
for (int i = 0; i < t.getRowCount(); i++)
t.setRowHeight(i, t.getCellRenderer(i, 0)
.getTableCellRendererComponent(t, t.getValueAt(i, 0), false, false, i, 0)
.getPreferredSize().height);
f.add(new JScrollPane(t));
f.pack();
f.setVisible(true);
Basically iterate over the rows, and ask the preferred height from the renderer, and set that as the row height.
Note: This required to set width style in HTML values that are auto-wrapped to multiple lines. If you don't do this, the preferred height of an HTML value will be the preferred height without auto-wrapping long lines (manual wrapping like <br> tags will still be considered).
This will result in this:
I have a scrollable JTable inside a JDialog and i wish to autoadjust the row width according to data length.
Any ideas?
Use the combination of JTable.setRowHeight method and a cell renderer based on JTextArea
This depends on what is being rendered and if you know the number if pixels...
Changing the column widths will be effected by the column auto resize policy.
If you want to set the pixel width...
int columnIndex = //... the index of the column
TableColumnModel columnModel = table.getColumnModel();
TableColumn tableColumn = columnModel.getColumn(columnIndex);
tableColumn.setWidth(pixelWidth);
If the column is rendering text and you know the number of characters that the column will display you can get the font metrics for the renderer/table...
// If you're using a cell renderer, you will need to get the cell renderer
// to get th font metrics
FontMerics fm = table.getFontMetrics(table.getFont());
int pixelWidth = fm.stringWidth("M") * characterCount;
If you're not using a text based renderer, you can use the renderer to gain some idea of the width...
TableCellRenderer renderer = table.getCellRenderer(0, columnIndex);
// You can also use table.getDefaultRenderer(Class)
Component component = renderer.getTableCellRendererComponent(table,
prototypeValue, // Some value the best represents the average value
false,
false,
0,
columnIndex);
int width = component.getPreferredWidth().width;
I use JTable with horizontal and vertical scrollbars. My JTable has empty space after rows with data.
When I open panel that is situated down of my table it hides a part of JTable and scrolling appears on JTable. This is normal behavior, but then I close that panel, empty space without data becomes grey instead of white color.
This only happens when I have horizontal scrollbar on my JTable. I suppose I must force JTable to repaint, I tried resizeAndRepaint() on TableHeader and JTable but it didn't work.
Please help! Thanks!
Here is resize() code invoked if any resize action was performed on table
for (int i = 0; i < columsNum; i++){
TableColumn column = this.getColumnModel().getColumn(i);
int preferedSize = //current size
int minimumSize = // min size
if (minimumSize != ColumnSizeCalculator.UNDEFINED_WIDTH)
column.setMinWidth(minimumSize);
column.setPreferredWidth(preferedSize);
}
this.revalidate();
this.repaint();
By default, a JTable does not fill the viewport of a scrollpane in the vertical direction. Try to call
table.setFillsViewportHeight(true);
on your table, then repainting the table should work.
I have a JTable with 3 columns:
- No. #
- Name
- PhoneNumber
I want to make specific width for each column as follows:
and I want the JTable able to update the widths of its columns dynamically if needed (for example, inserting large number in the column #) and keeping same style of the JTable
I solved the first issue, using this code:
myTable.getColumnModel().getColumn(columnNumber).setPreferredWidth(columnWidth);
but I didn't success to make myTable to update the widths dynamically ONLY if the current width of the column doesn't fit its contents. Can you help me solving this issue?
Here I found my answer: http://tips4java.wordpress.com/2008/11/10/table-column-adjuster/
The idea is to check some rows' content length to adjust the column width.
In the article, the author provided a full code in a downloadable java file.
JTable table = new JTable( ... );
table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
for (int column = 0; column < table.getColumnCount(); column++)
{
TableColumn tableColumn = table.getColumnModel().getColumn(column);
int preferredWidth = tableColumn.getMinWidth();
int maxWidth = tableColumn.getMaxWidth();
for (int row = 0; row < table.getRowCount(); row++)
{
TableCellRenderer cellRenderer = table.getCellRenderer(row, column);
Component c = table.prepareRenderer(cellRenderer, row, column);
int width = c.getPreferredSize().width + table.getIntercellSpacing().width;
preferredWidth = Math.max(preferredWidth, width);
// We've exceeded the maximum width, no need to check other rows
if (preferredWidth >= maxWidth)
{
preferredWidth = maxWidth;
break;
}
}
tableColumn.setPreferredWidth( preferredWidth );
}
Use the addRow(...) method of the DefaultTableModel to add data to the table dynamically.
Update:
To adjust the width of a visible column I think you need to use:
tableColumn.setWidth(...);
I actually run into this problem too. I've found one useful link that solved my issue.
Pretty much get the specific column and set its setMinWidth and setMaxWidth to be the same(as fixed.)
private void fixWidth(final JTable table, final int columnIndex, final int width) {
TableColumn column = table.getColumnModel().getColumn(columnIndex);
column.setMinWidth(width);
column.setMaxWidth(width);
column.setPreferredWidth(width);
}
Ref: https://forums.oracle.com/thread/1353172