JTable table = new JTable(); table.setSelectionForeground(Color.RED); Color selectedForeground = table.getSelectionForeground();
import javax.swing.*; import java.awt.*; public class TableExample extends JFrame { public static void main(String[] args) { JTable table = new JTable(new String[][]{{"Row 1, Column 1", "Row 1, Column 2"}, {"Row 2, Column 1", "Row 2, Column 2"}}, new String[]{"Column 1", "Column 2"}); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); table.getTableHeader().setReorderingAllowed(false); table.setSelectionForeground(Color.WHITE); table.setSelectionBackground(Color.BLUE); JScrollPane scrollPane = new JScrollPane(table); JFrame frame = new JFrame(); frame.add(scrollPane); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setTitle("Table Example"); frame.setSize(300, 200); frame.setVisible(true); } }In this example, we have created a table and set the selection mode to single selection, disabled column reordering and specified the foreground and background colors for selected cells. We then add the table to a scroll pane and the scroll pane to a JFrame. Package library: javax.swing