java 如何在 JTable 单元格中显示多行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9955595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 23:02:52  来源:igfitidea点击:

How to display multiple lines in a JTable Cell

javaswingjtable

提问by Mohammad Faisal

I would like to create a JTablelike the below picture:enter image description here

我想创建一个JTable如下图所示:在此处输入图片说明

Which javaclass will be used and possibly how?

java将使用哪个类以及可能如何使用?

采纳答案by mKorbel

basically you can put any type of JComponentsto the JTablecell, depends of if is contents editable, thats talking me about follows

基本上你可以JComponentsJTable单元格中放置任何类型的,取决于内容是否可编辑,这就是我所说的以下内容

  • JTablewith one TableColumnwithout TableHeader

  • JPanel(GridBagLayout) with JLabelsor JTextFields

  • JList

  • JTable有一个TableColumn没有TableHeader

  • JPanel( GridBagLayout) 与JLabelsJTextFields

  • JList

回答by Channa Jayamuni

Multiline JTablecell can make using a customized TableCellRenderereasily. Use following steps to create the TableCellRenderer.

多线JTable单元可以TableCellRenderer轻松定制使用。使用以下步骤创建TableCellRenderer.

Step 1: Create TableCellRenderer

第 1 步:创建 TableCellRenderer

Following code shows to create a multi-line TableCellRendererfor String[]values. It's possible to change the String[]into a Vectoror an other Collectiontype

以下代码显示TableCellRendererString[]值创建多行。可以将其更改String[]为 aVector或其他Collection类型

public class MultiLineTableCellRenderer extends JList<String> implements TableCellRenderer {

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        //make multi line where the cell value is String[]
        if (value instanceof String[]) {
            setListData((String[]) value);
        }

        //cell backgroud color when selected
        if (isSelected) {
            setBackground(UIManager.getColor("Table.selectionBackground"));
        } else {
            setBackground(UIManager.getColor("Table.background"));
        }

        return this;
    }
}

Step 2: Set TableCellRendererinto the JTable

第 2 步:设置TableCellRendererJTable

    MultiLineTableCellRenderer renderer = new MultiLineTableCellRenderer();

    //set TableCellRenderer into a specified JTable column class
    table.setDefaultRenderer(String[].class, renderer);

    //or, set TableCellRenderer into a specified JTable column
    table.getColumnModel().getColumn(columnIndex).setCellRenderer(renderer);

This is my tested screenshot:

这是我测试过的截图:

Multi-line TableCellRenderer Test

多行 TableCellRenderer 测试

回答by raicoder

This will not work if you use a DefaultTableModel. You have to use a custom model for your table that extends AbstractTableModeland have to override the method getColumnClass(), along with other abstract methods.

如果您使用DefaultTableModel. 您必须为您的表使用自定义模型,该模型扩展AbstractTableModel并必须覆盖方法getColumnClass()以及其他抽象方法。

You will also set your table row height as mentioned in a comment above.

您还将按照上面的评论中所述设置表格行高。

The official documentation from Oracleclarifies this.

Oracle官方文档对此进行了澄清。

回答by Marcel

Besides the TableCellRendererbased on JList<String>as suggested by Channa Jayamuni you can build a multi-line renderer on top of the DefaultTableCellRendereras well. The trick is to use the HTML feature of the JLabelcomponent and adjust the line height accordingly. This preserves more of the features of the default renderer.

除了Channa Jayamuni 建议的TableCellRenderer基于之外,JList<String>您还可以在其之上构建多行渲染器DefaultTableCellRenderer。诀窍是使用JLabel组件的 HTML 功能并相应地调整行高。这保留了默认渲染器的更多功能。

Activating this renderer for all Strings will do what you want in most cases:

在大多数情况下,为所有字符串激活此渲染器将执行您想要的操作:

setDefaultRenderer(String.class, new MultiLineCellRenderer());

The solution handles automatic line heightto some degree. I.e. it will not decreasethe height of a table line if the content is updated with less lines. This is a quite complex task because it depends on the content of any other cell in the same line as well.

该解决方案在某种程度上处理自动行高。即,如果用较少的行更新内容,它不会降低表格行的高度。这是一项相当复杂的任务,因为它也取决于同一行中任何其他单元格的内容。

/** Variant of DefaultTableCellRenderer that automatically switches
 *  to multi-line HTML when the value contains newlines. */
class MultiLineCellRenderer extends DefaultTableCellRenderer
{
  @Override public Component getTableCellRendererComponent(JTable table,
    Object value, boolean isSelected, boolean hasFocus, int row, int column)
  { Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    int height = c.getPreferredSize().height;
    if (table.getRowHeight(row) < height)
      table.setRowHeight(row, height);
    return c;
  }

  @Override protected void setValue(Object value)
  { if (value instanceof String)
    { String sVal = (String)value;
      if (sVal.indexOf('\n') >= 0 && // any newline?
        !(sVal.startsWith("<html>") && sVal.endsWith("</html>"))) // already HTML?
        value = "<html><nobr>" + htmlEncodeLines(sVal) + "</nobr></html>";
    }
    super.setValue(value);
  }

  /** Encode string as HTML. Convert newlines to &lt;br&gt; as well.
   * @param s String to encode.
   * @return Encoded string. */
  protected static String htmlEncodeLines(String s)
  { int i = indexOfAny(s, "<>&\n", 0); // find first char to encode
    if (i < 0)
      return s; // none
    StringBuffer sb = new StringBuffer(s.length() + 20);
    int j = 0;
    do
    { sb.append(s, j, i).append(htmlEncode(s.charAt(i)));
      i = indexOfAny(s, "<>&\n", j = i + 1);
    } while (i >= 0);
    sb.append(s, j, s.length());
    return sb.toString();
  }

  private static String htmlEncode(char c)
  { switch (c) {
    case '<': return "&lt;";
    case '>': return "&gt;";
    case '&': return "&amp;";
    case '\n': return "<br>";
    default: return Character.toString(c);
  } }

  private static int indexOfAny(String s, String set, int start)
  { for (int i = start; i < s.length(); ++i)
    if (set.indexOf(s.charAt(i)) >= 0)
      return i;
    return -1;
  }
}

回答by Shinwar ismail

jTable1.setShowGrid(true);

Try this code :)

试试这个代码:)

回答by Shinwar ismail

jTable1.setShowHorizontalLines(true); // only HorizontalLines
  jTable1.setShowVerticalLines(true); //  only VerticalLines
  jTable1.setShowGrid(true);          // show Horizontal and Vertical
  jTable1.setGridColor(Color.yellow); // change line color 

回答by harry

When any table has large volume of data, the use of scrollbar is applied in the JTable. The JScrollPane provides you to scrollable facility to scroll the scroll bar and you get all the contents. Simple example using JTable:

当任何表有大量数据时,JTable 中应用滚动条的使用。JScrollPane 为您提供了可滚动工具来滚动滚动条并获得所有内容。使用 JTable 的简单示例:

import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;

public class ScrollableJTable{
public static void main(String[] args) {
new ScrollableJTable();
}
public ScrollableJTable(){
JFrame frame = new JFrame("Creating a Scrollable JTable!");
JPanel panel = new JPanel();
 String data[][] =
  {{"001","abc","xyz","wtwt","gwgw","tttr","rtrt"},
  {"002","rwtr","ttrt","rtttr","trt","rtrt","trtrd"},
  {"003","rtt","trt","trt","trrttr","trt","rtr"},
  {"004","trt","trtt","trtrt","rtrtt","trt","trrt"},
  {"001","rttr","trt","trt","trtr","trt","trttr"},
  ;
  JTable table = new JTable(data,col);
  JTableHeader header = table.getTableHeader();
  header.setBackground(Color.yellow);
  JScrollPane pane = new JScrollPane(table);
  table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
  panel.add(pane);
  frame.add(panel);
  frame.setSize(500,150);
  frame.setUndecorated(true);
  frame.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.setVisible(true);
  }
}

Now you can modify this table according to your requirements

现在您可以根据您的要求修改此表