如何用 Java Swing 高亮表中的一行?


要高亮表中的一行,可以使用 addRowSelectionInterval() 方法。首先创建一张表 -

DefaultTableModel tableModel = new DefaultTableModel();
JTable table = new JTable(tableModel);

添加一些列 -

tableModel.addColumn("Language/ Technology");
tableModel.addColumn("Text Tutorial");
tableModel.addColumn("Video Tutorial");
tableModel.addColumn("Views");

现在,向表中添加行 -

tableModel.addRow(new Object[] { "NodeJS", "No", "Yes", "2350"});
tableModel.addRow(new Object[] { "MVC", "Yes", "No", "1500"});
tableModel.addRow(new Object[] { "ASP.NET", "Yes", "Yes", "3400"});
tableModel.addRow(new Object[] { "F#", "Yes", "No", "7890"});
tableModel.addRow(new Object[] { "Blockchain", "Yes", "No", "10600"});
tableModel.addRow(new Object[] { "SharePoint", "Yes", "Yes", "4900"});

通过添加行的间隔来高亮显示单个行。由于我们只需要高亮显示一行,因此为两个参数设置相同的索引 -

table.addRowSelectionInterval(4, 4);

以下是一个在 JTable 中高亮显示一行的示例 -

示例

package my;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class SwingDemo {
   public static void main(String[] argv) throws Exception {
      DefaultTableModel tableModel = new DefaultTableModel();
      JTable table = new JTable(tableModel);
      tableModel.addColumn("Language/ Technology");
      tableModel.addColumn("Text Tutorial");
      tableModel.addColumn("Video Tutorial");
      tableModel.addColumn("Views");
      tableModel.addRow(new Object[] { "NodeJS", "No", "Yes", "2350"});
      tableModel.addRow(new Object[] { "MVC", "Yes", "No", "1500"});
      tableModel.addRow(new Object[] { "ASP.NET", "Yes", "Yes", "3400"});
      tableModel.addRow(new Object[] { "F#", "Yes", "No", "7890"});
      tableModel.addRow(new Object[] { "Blockchain", "Yes", "No", "10600"});
      tableModel.addRow(new Object[] { "SharePoint", "Yes", "Yes", "4900"});
      tableModel.addRow(new Object[] { "AWS", "No", "Yes", "8900"});
      tableModel.addRow(new Object[] { "C#", "Yes", "Yes", "1300"});
      tableModel.addRow(new Object[] { "Java", "Yes", "No", "9686"});
      tableModel.addRow(new Object[] { "jQuery", "Yes", "Yes", "4500"});
      tableModel.addRow(new Object[] { "Python", "Yes", "No", "6789"});
      tableModel.addRow(new Object[] { "Scala", "Yes", "No", "3400"});
      tableModel.addRow(new Object[] { "Swift", "No", "Yes", "9676"});
      table.addRowSelectionInterval(4, 4);
      table.setBackground(Color.white);
      table.setForeground(Color.BLUE);
      Font font = new Font("Verdana", Font.CENTER_BASELINE, 12);
      table.setFont(font);
      JFrame frame = new JFrame();
      frame.setSize(600, 400);
      frame.add(new JScrollPane(table));
      frame.setVisible(true);
   }
}

输出

更新于: 30-Jul-2019

1K+ 次观看

启动您的职业生涯

完成该教程即可获得认证

立即开始
广告