JTable Column Headers with wrapped and center aligned text - java

I am currently trying to wrap and align center text of a column header. The problem seems to be that while the first line of column header is aligned, the second one does not get aligned properly.
I am using DefaultTableCellRenderer to render it as such:
public void centerAlign(JTable t, int numberOfColumns){
centerRenderer.setHorizontalAlignment(SwingConstants.CENTER);
for (int i = 0; i < numberOfColumns; i++){
t.getColumnModel().getColumn(i).setCellRenderer(centerRenderer);
}
headerRender = (DefaulttableCellRenderer)
t.getTableHeader().getDefaultRenderer();
headerRenderer.setHorizontalAlignment(JLabel.CENTER);
}

In your table model class use html of column name
example:
"<html><center>First column</html>"

Related

JTable setPreferredWidth() for columns displaying incorrectly

I have a JTable with an AbstractTabelModel displayed. I tried to create a void method in my project that sets the width of each column to the length of the longest value in the column. Here is the method that I am using right now, where "accountWindow" is the JTable:
public void setColumnWidths(){
accountWindow.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
for (int i = 0; i < accountWindow.getColumnCount(); i++){
int greatestStringLength = 2;
for (int z = 0; z < accountWindow.getRowCount(); z++){
if (accountWindow.getValueAt(z, i).toString().length() > greatestStringLength){
System.out.println("Width SET");
greatestStringLength = accountWindow.getValueAt(z, i).toString().length();
accountWindow.getColumnModel().getColumn(i).setPreferredWidth(greatestStringLength);
}
//System.out.println(accountWindow.getValueAt(z, i).toString());
//System.out.println("Greatest Value: " + greatestValueWidth);
}
}
}
The method is called correctly in my Controller class (MVC), but it is setting the width of each column to essentially 0. Method is called after the table is updated and the fireTableData() method is called and account information is displayed. I have added the JTable to a scroll pane. Any comments or suggestions would be appreciated.
The width needs to be specified in pixels not characters in the String.
if (accountWindow.getValueAt(z, i).toString().length() > greatestStringLength){
Looks to me like you are just getting the number of characters in the String, not the width it takes to render the String. That is 20 characters will NOT render in 20 pixels. The width of the String will vary for different Fonts.
Check out Table Column Adjuster for the solution on how to determine the rendered width. It gives a simple usage and a custom class that you can use which has more features.
Both solutions will actually invoke the renderer used by the table to determine the maximum width.

Highlight found data in JTable row

I want to search data from JTable when data found then I want to highlight table row. This code is work properly search record but I don't know what I do for highlight the row.
String target = jTextField1.getText();
for(int row = 0; row < jTable1.getRowCount(); row++)
for(int col = 0; col < jTable1.getColumnCount(); col++)
{
String next = (String)jTable1.getValueAt(row, col);
if(next.equals(target))
{
System.out.println("found");// here what change for highlight row.
}
}
The answer depends on your idea of "highlighting"
You could use JTable#addRowSelection to highlight a row using the default selection
Or, you could setup your cell renders to apply additional highlighting support via an additional lookup to determine if the cell/row should be highlighted
Or, you could use the inbuilt filtering capabilities of the JTable to filter out unwanted content
See How to use tables for more details
Or, you could use the highlighting support from the SwingLabs, SwingX librRies
We can achieve that with a custom JLabel and TableCellRenderer.
Following example does the highlighting on the found (filtered) rows in JTable. The rows are filtered via RowFilter:
http://www.logicbig.com/tutorials/core-java-tutorial/swing/jtable-row-filter-highlighting/
else if(e.getSource()==field){
int z;
for(z = 0;z<table.getRowCount();z++){
if(Integer.parseInt(field.getText()) == Integer.parseInt((String)table.getValueAt(z, 1))){
break;
}
}
table.setRowSelectionInterval(z, z);
}
i had the same problem and this was how i went about it.

JTable-Paint the content(text) in a cell

I have a JTable and i have a method which implements search in table rows and columns, i use regular expressions and i want to paint(eg yellow) the text which matches with the regular expression in the cell. I want to paint the text not the background of the cell and only the part of word which matches with reg expression.
The code for my search method is:
for (int row = 0; row <= table.getRowCount() - 1; row++) {
for (int col = 0; col <= table.getColumnCount() - 1; col++) {
Pattern p = Pattern.compile("(?i)" + search_txt.getText().trim());
Matcher m = p.matcher(table.getValueAt(row, col).toString().trim());
if (m.find()){
isFound = true;
table.scrollRectToVisible(table.getCellRect(row, 0, true));
table.setRowSelectionInterval(row, row);
break;
}
}
}
You will need a custom renderer to do this.
The default renderer is a JLabel. So the only way to do this would to wrap HTML around your text string and change the font color of the text you are searching for. You would need to pass the search text to the renderer so the renderer can determine which text to highlight.
The code you posted has a problem in that it will always scroll to the bottom of the table. So what is your exact requirement. Do you want to highlight all cells at one time. Or do you just want to have a "Next" button that will find the next cell with the text. In the first case you would not want to automatically scroll the table. In the second case you would scroll the table.
Also, depending on the requirement you would need to either repaint the entire table (if you show all occurrences at once) or only the current row (if you have next functionality).
Edit:
Normally when you add text to a label you use:
label.setText("user1005633");
If you want to highlight any text containing "100" then you would need to do:
label.setText("<html>user<font color="yellow">100</font>5633</html>");
This is what I mean by wrapping.

Auto resize the widths of JTable's columns dynamically

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

how to fill JTextFields with the columns of a JTable search?

I have a master/detail form with a JTable on top, and all the JTextFields corresponding below in the JPanel. I'm trying to make a search in the JTable, so that when the correct row gets picked, all the JTextFields can be filled with the column values. I don't know how can I call the rows programmatically to do so. How would it be done?
This is the code I'm using to do the search:
int rows = (masterTable.getModel()).getRowCount();
final int colCedula = 1; //columna de la CEDULA
final int colRuc = 11; //columna de RUC
String value = null ;
for(int i=0; i
value = (String) (masterTable.getModel()).getValueAt(i, colCedula);
if (value.equals(this.txt_BuscaCliente.getText())) {
//CODE FOR FILLING JTEXTFIELDS
}
If the search finds the column value and stops the loop, could I just write in the //CODE section masterTable.getSelectedRow() and then fill all the JTextFields with its column values???
Also, how is it done to have the row selected highlighted, programatically? Let's say, after my search finds the column value, to have that row highlighted in the JTable
I'd start with the example in the tutorial article How to Use Tables: User Selections in order to understand list selection events. Given a SINGLE_SELECTION model, you won't have to search; just fill in the text fields from the selected row. Alternatively, you can make the cells editable in your table model, and you won't have to copy them at all.
Addendum:
Also, how is it done to have the row selected highlighted, programatically?
Instead of searching, let your implementation of ListSelectionListener tell you what selection has been made by the user. In the example cited, modify the RowListener as shown below to iterate through the columns in the selected row.
private class RowListener implements ListSelectionListener {
#Override
public void valueChanged(ListSelectionEvent event) {
if (!event.getValueIsAdjusting()) {
for (int c : table.getSelectedRows()) {
int row = table.convertRowIndexToModel(c);
TableModel model = table.getModel();
for (int col = 0; col < model.getRowCount(); col++) {
System.out.println(model.getValueAt(row, col));
}
System.out.println();
}
}
}
}

Categories