I want to put a String in a JTable
that is longer than the given cell-width.
How can I set the rowHeight
dynamically so that I can read the whole String?
Here is an example:
import javax.swing.*;
public class ExampleTable {
public JPanel createTable() {
JPanel totalGUI = new JPanel();
//define titles for table
String[] title = {"TITLE1", "TITLE2", "TITLE3"};
//table data
Object[][] playerdata = {
{new Integer(34), "Steve", "test test test"},
{new Integer(32), "Patrick", "dumdi dumdi dummdi dumm di di didumm"},
{new Integer(10), "Sarah", "blabla bla bla blabla bla bla blabla"},};
//create object 'textTable'
JTable textTable = new JTable(playerdata,title);
//set column width
textTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
textTable.getColumnModel().getColumn(0).setPreferredWidth(60);
textTable.getColumnModel().getColumn(1).setPreferredWidth(60);
textTable.setDefaultRenderer(String.class, new RowHeightCellRenderer());
//scrollbar
JScrollPane scrollPane = new JScrollPane(textTable);
totalGUI.add(scrollPane);
return totalGUI;
}
private static void createAndShowGUI() {
//create main frame
JFrame mainFrame = new JFrame("");
ExampleTable test = new ExampleTable();
JPanel totalGUI = new JPanel();
totalGUI = test.createTable();
//visible mode
mainFrame.add(totalGUI); //integrate main panel to main frame
mainFrame.pack();
mainFrame.setVisible(true);
}
public static void main (String[] args) {
createAndShowGUI();
}//main
}
And here you'll see the code which line-breaks each text that is to long for the given cell
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
public class RowHeightCellRenderer extends JTextArea implements TableCellRenderer
{
/**
*
*/
private static final long serialVersionUID = 1L;
public Component getTableCellRendererComponent (JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column ) {
setText( value.toString() );
return this;
}
}
thank you but I want to implement the RowHeight dynamically, depending on String length... I want to read the whole String/text in the cell. any suggestions?
I'm java beginner and this is my first question. I would be delighted I get an answer.
See Question&Answers more detail:os