JTable selected Cell Fontsize

1)
I work with a JTable.
The cells display the value in font size 18.
If I click on a cell to edit it,
than the cell fontsize is smaller, I think its the default size 10.
How can I modify the selected cell fontsize?
2)
Is it possible to modify the font color of a cell
without using TableCellRenderer, because I have to modify it dynamically.
e.g. jTable.cell(2,2).setFontColor(Color.BLUE);

1)
I work with a JTable.
The cells display the value in font size 18.
If I click on a cell to edit it,
than the cell fontsize is smaller, I think its the
default size 10.
How can I modify the selected cell fontsize?probably something to do with the renderer
>
2)
Is it possible to modify the font color of a cell
without using TableCellRenderer, because I have to
modify it dynamically.
e.g. jTable.cell(2,2).setFontColor(Color.BLUE);no, use the renderer

Similar Messages

  • JTable selected cell highlight

    Hi,
    I want to reproduce Excel behaviour in a JTable :
    highlight the cell on which user has clicked once
    show the caret when the user has double-cliked on it.
    The second behaviour looks like being built-in the JTable
    But when the user clicks once on the cell not visual effect appears
    to reflect the click event.
    I would like to have the selected cell "border" painted in another color.
    Would you have a hint for that ?
    thanks

    Thanks you the hint Razor_Blade.
    could you elaborate a bit more please.
    I don't feel like getting deep into rendering stuff now,
    and was expecting a simple solution.
    But if there's no, don't bother.
    It will take the time that it needs but I'll find out.
    thx.

  • JTable select cells

    Hi,
    I have a JTable which is set individual cell selectable and allow multipleselection. I have a display problem when I use "CTRL" key and mouse toselect cells. The problem is that I cannot select them individually. (Someof Other cell are also selected) .
    Is it the behaviour of JTable?
    Could you tell me how can i select multiple "Cell Selection" from the JTable.
    For Example, you can find this feature in "MocroSoft Excel" (pressing "ctrl" key, select multiple cells)
    Thanks
    Nobi

    setSelectionMode
    public void setSelectionMode(int selectionMode)
    Sets the table's selection mode to allow only single selections, a single contiguous interval, or multiple intervals.
    Note: JTable provides all the methods for handling column and row selection. When setting states, such as setSelectionMode, it not only updates the mode for the row selection model but also sets similar values in the selection model of the columnModel. If you want to have the row and column selection models operating in different modes, set them both directly.
    Both the row and column selection models for JTable default to using a DefaultListSelectionModel so that JTable works the same way as the JList. See the setSelectionMode method in JList for details about the modes.

  • Selecting cells in a JTable

    Hi All,
    I'm looking for a way of selecting all cells from the original drag point to the current cell that the mouse is over.
    This is for a year planner which displays the months vertcally and the days horizontally. So if the user was to start selecting cells in one month and move the mouse down a row onto the next month, I would want all cells selected from the first cell to the current cell.
    Has anyone got any ideas?

    Hi Pchatwin,
    Any dukes available for bad news? :)
    Thanks Stas but wouldn't that select entire rows
    rather than cells?
    For example, if I have a grid:
    12345
    67890
    and drag from cell 3 to cell 9 I would need to see
    cells 3, 4, 5, 6, 7, 8, 9 highlightedUnfortunately this is impossible with JTable's default selection model. By default, JTable models selections simply as an intersection of selected rows and columns. It doesn't track individual cells.
    Turning to your example:
    If you select cells 2,3,4,5 JTable tracks the following.
    Note: The numbers I am using are row/col indexes, not your cell values.
    Selected rows = {0}
    Selected cols = {1,2,3,4}
    This means the following cells are selected:
    {{0,1},{0,2},{0,3},{0,4}} or {2,3,4,5}
    Now if you want to add cells 6, 7, 8, 9 it won't work. The selection model tracks whether a column is selected or not. It can't be selected for one row and not for another. So it's impossible to have cell 6 selected and not 1. It would mean that column 0 would need to be both selected (to include 6) and not (to include 1). Does this make sense?
    Sorry to have to tell you that. On the other hand it may save you some frustration.
    Oh, and whether or not one can provide a custom model that allows this, I don't know - I've not tried it myself. It could be, but might be very difficult. For example, what would you return from JTable.getSelectedRows()?
    Thanks!
    Shannon Hickey (Swing Team)
    >
    Paul

  • How to outline selected cells during drag and drop in the jtable

    Hi,
    I have spent a lot of time to find out how to outline selected cells during drag in the jtable, but I did not find the answer.
    Can anybody give me a tip, where to read more about this problem or even better, give an example...
    I have the following situation:
    1.Table has 10 rows and 10 columns
    2.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION) and setCellSelectionEnabled(true)
    3.user select 5 cells in 4th row (for example cell45,cell46,cell47,cell48 and cell49)
    4.user starts dragging. During dragging an outline should be drawn. Outline should be a rectangular with width of 5 cells and height of one cell. Outline should move according to the mouse position.
    5.rectangular disappears when dropped
    Regards,
    Primoz

    In "createTransferable" you can create a drag image
    which you can paint in "dragOver" and clear in "drop" method of DropTarget :
    package dnd;
    * DragDropJTableCellContents.java
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.datatransfer.*;
    import java.awt.dnd.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    public class DragDropJTableCellContents extends JFrame {
        public DragDropJTableCellContents() {
            setTitle("Drag and Drop JTable");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            getContentPane().add(createTable("JTable"), BorderLayout.CENTER);
            setSize(400, 300);
            setLocationRelativeTo(null);
        private JPanel createTable(String tableId) {
            DefaultTableModel model = new DefaultTableModel();
            for (int i = 0; i < 10; i++) {
                model.addColumn("Column "+i);
            for (int i = 0; i < 10; i++) {
                String[] rowData = new String[10];
                for (int j = 0; j < 10; j++) {
                    rowData[j] = tableId + " " + i + j;
                model.addRow(rowData);
            JTable table = new JTable(model);
            table.getTableHeader().setReorderingAllowed(false);
            table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
            table.setCellSelectionEnabled(true);
            JScrollPane scrollPane = new JScrollPane(table);
            table.setDragEnabled(true);
            TableTransferHandler th = new TableTransferHandler();
            table.setTransferHandler(th);
            table.setDropTarget(new TableDropTarget(th));
            table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            JPanel panel = new JPanel(new BorderLayout());
            panel.add(scrollPane);
            panel.setBorder(BorderFactory.createTitledBorder(tableId));
            return panel;
        public static void main(String[] args) {
            new DragDropJTableCellContents().setVisible(true);
        abstract class StringTransferHandler extends TransferHandler {
            public int dropAction;
            protected abstract String exportString(JComponent c);
            protected abstract void importString(JComponent c, String str);
            @Override
            protected Transferable createTransferable(JComponent c) {
                return new StringSelection(exportString(c));
            @Override
            public int getSourceActions(JComponent c) {
                return COPY;
            @Override
            public boolean importData(JComponent c, Transferable t) {
                if (canImport(c, t.getTransferDataFlavors())) {
                    try {
                        String str = (String) t.getTransferData(DataFlavor.stringFlavor);
                        importString(c, str);
                        return true;
                    } catch (UnsupportedFlavorException ufe) {
                    } catch (IOException ioe) {
                return false;
            @Override
            public boolean canImport(JComponent c, DataFlavor[] flavors) {
                for (int ndx = 0; ndx < flavors.length; ndx++) {
                    if (DataFlavor.stringFlavor.equals(flavors[ndx])) {
                        return true;
                return false;
        class TableTransferHandler extends StringTransferHandler {
            private int dragRow;
            private int[] dragColumns;
            private BufferedImage[] image;
            private int row;
            private int[] columns;
            public JTable target;
            @Override
            protected Transferable createTransferable(JComponent c) {
                JTable table = (JTable) c;
                dragRow = table.getSelectedRow();
                dragColumns = table.getSelectedColumns();
                createDragImage(table);
                return new StringSelection(exportString(c));
            protected String exportString(JComponent c) {
                JTable table = (JTable) c;
                row = table.getSelectedRow();
                columns = table.getSelectedColumns();
                StringBuffer buff = new StringBuffer();
                for (int j = 0; j < columns.length; j++) {
                    Object val = table.getValueAt(row, columns[j]);
                    buff.append(val == null ? "" : val.toString());
                    if (j != columns.length - 1) {
                        buff.append(",");
                return buff.toString();
            protected void importString(JComponent c, String str) {
                target = (JTable) c;
                DefaultTableModel model = (DefaultTableModel) target.getModel();
                String[] values = str.split("\n");
                int colCount = target.getSelectedColumn();
                int max = target.getColumnCount();
                for (int ndx = 0; ndx < values.length; ndx++) {
                    String[] data = values[ndx].split(",");
                    for (int i = 0; i < data.length; i++) {
                        String string = data;
    if(colCount < max){
    model.setValueAt(string, target.getSelectedRow(), colCount);
    colCount++;
    public BufferedImage[] getDragImage() {
    return image;
    private void createDragImage(JTable table) {
    if (dragColumns != null) {
    try {
    image = new BufferedImage[dragColumns.length];
    for (int i = 0; i < dragColumns.length; i++) {
    Rectangle cellBounds = table.getCellRect(dragRow, i, true);
    TableCellRenderer r = table.getCellRenderer(dragRow, i);
    DefaultTableModel m = (DefaultTableModel) table.getModel();
    JComponent lbl = (JComponent) r.getTableCellRendererComponent(table,
    table.getValueAt(dragRow, dragColumns[i]), false, false, dragRow, i);
    lbl.setBounds(cellBounds);
    BufferedImage img = new BufferedImage(lbl.getWidth(), lbl.getHeight(),
    BufferedImage.TYPE_INT_ARGB_PRE);
    Graphics2D graphics = img.createGraphics();
    graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f));
    lbl.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
    lbl.paint(graphics);
    graphics.dispose();
    image[i] = img;
    } catch (RuntimeException re) {
    class TableDropTarget extends DropTarget {
    private Insets autoscrollInsets = new Insets(20, 20, 20, 20);
    private Rectangle rect2D = new Rectangle();
    private TableTransferHandler handler;
    public TableDropTarget(TableTransferHandler h) {
    super();
    this.handler = h;
    @Override
    public void dragOver(DropTargetDragEvent dtde) {
    handler.dropAction = dtde.getDropAction();
    JTable table = (JTable) dtde.getDropTargetContext().getComponent();
    Point location = dtde.getLocation();
    int row = table.rowAtPoint(location);
    int column = table.columnAtPoint(location);
    table.changeSelection(row, column, false, false);
    paintImage(table, location);
    autoscroll(table, location);
    super.dragOver(dtde);
    public void dragExit(DropTargetDragEvent dtde) {
    clearImage((JTable) dtde.getDropTargetContext().getComponent());
    super.dragExit(dtde);
    @Override
    public void drop(DropTargetDropEvent dtde) {
    Transferable data = dtde.getTransferable();
    JTable table = (JTable) dtde.getDropTargetContext().getComponent();
    clearImage(table);
    handler.importData(table, data);
    super.drop(dtde);
    private final void paintImage(JTable table, Point location) {
    Point pt = new Point(location);
    BufferedImage[] image = handler.getDragImage();
    if (image != null) {
    table.paintImmediately(rect2D.getBounds());
    rect2D.setLocation(pt.x - 15, pt.y - 15);
    int wRect2D = 0;
    int hRect2D = 0;
    for (int i = 0; i < image.length; i++) {
    table.getGraphics().drawImage(image[i], pt.x - 15, pt.y - 15, table);
    pt.x += image[i].getWidth();
    if (hRect2D < image[i].getHeight()) {
    hRect2D = image[i].getHeight();
    wRect2D += image[i].getWidth();
    rect2D.setSize(wRect2D, hRect2D);
    private final void clearImage(JTable table) {
    table.paintImmediately(rect2D.getBounds());
    private Insets getAutoscrollInsets() {
    return autoscrollInsets;
    private void autoscroll(JTable table, Point cursorLocation) {
    Insets insets = getAutoscrollInsets();
    Rectangle outer = table.getVisibleRect();
    Rectangle inner = new Rectangle(outer.x + insets.left,
    outer.y + insets.top,
    outer.width - (insets.left + insets.right),
    outer.height - (insets.top + insets.bottom));
    if (!inner.contains(cursorLocation)) {
    Rectangle scrollRect = new Rectangle(cursorLocation.x - insets.left,
    cursorLocation.y - insets.top,
    insets.left + insets.right,
    insets.top + insets.bottom);
    table.scrollRectToVisible(scrollRect);
    Edited by: Andre_Uhres on Nov 18, 2007 10:03 PM

  • How do I change the colour of a selected cell in a jTable?

    I have a Jtable that displays URL names in one column. There are several problems I'm having. The effect I'm trying to achieve is this:
    When the user runs the mouse over the URL name the cursor should change into a hand (similar to what happens in an HTML hyperlink). I'm aware that the Cursor class can set the cursor graphic so i figure that i need a listener of some sort on each cell (so the cursor can change from an arrow to a hand) and also one to indicate when the cursor is not on a cell (so that it can change from a hand back into an arrow). Is this the right track?
    Also, I've looked at the DefaultTableCellRenderer class (which, as i understand it, is responsible for how each cell in the jtable is displayed) for a method that will allow me to set the background of a selected cell (or row or column). I require this because each time i select a cell (or row) it becomes highlighted in blue. I would rather it just remained white and changed the cursor to a hand. I know there exists a method for setting the background for an unselected cell but none for a selected cell. Again, I'm not sure if I'm going down the right track with this approach.
    Lastly, if the cell has been selected (by a mouse click) the font of the writing in the cell (i.e. The name of the URL) should change. This shouldn't be too much of a problem I think.
    I do not expect anyone to provide code to do all of this but some general pointers would be extremely helpful as I do not know if I'm thinking on the right track for any of this. Having some (limited) experience with Swing I doubt there is a simple way to do this but I can only hope!
    Thanks.
    Chris

    http://www2.gol.com/users/tame/swing/examples/SwingExamples.html
    there you can find some examples with CellRenderer's and so on ...
    have fun

  • Set background color to selected jtable columns cell

    I am clicking on jtables column.I want to select any column and that column (only selected cell of column)should get displayed with specific background color.
    plz help

    You can write your own tablemodel,
    i.e. use DefaultTableModel or implement AbstractTableModel.
    Good luck!

  • JTable: selecting multiple cells

    Supposing you have a spreadsheet layout with A,B,C on the columns and 1,2,3 on the rows, is it possible to allow the user to select cells A1 and C3, like they can in a normal spreadsheet app?
    Somehow I need to obtain this kind of functionality from our system, although I have no idea how at present.

    Something like.....
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TableExample extends JFrame {
       boolean[][] selectedCells = new boolean[5][5];
        public TableExample() {
           super("Table Selection Test");
           final JTable table = new JTable(5, 5) {
              public boolean isCellSelected(int row, int column) {
                 return selectedCells[row][column];
           table.addMouseListener(new MouseAdapter() {
              public void mousePressed(MouseEvent e) {
                 int row = table.rowAtPoint(e.getPoint());
                 int column = table.columnAtPoint(e.getPoint());
                 if (e.isControlDown()) {
                    selectedCells[row][column] = !selectedCells[row][column];
                 else {
                    for (int i = 0 ; i < 5 ; i++) {
                       for (int j = 0 ; j < 5 ; j++) {
                          selectedCells[i][j] = false;
                    selectedCells[row][column] = true;
                 table.repaint();
          getContentPane().setLayout(new BorderLayout());
          getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          setSize(400, 400);
       public static void main(String[] args) {
          new TableExample().setVisible(true);
    }

  • How to change a selected cell background color in JTable?

    Hi all,
    I am trying to change the background color of a selected cell by clicking on that particular cell. DefaultTableCellRenderer class provides setBackground(Color c) to change the background color of unselected cells. Is there a way to change a selected cell background color?
    Thank you,
    Arthur

    Write your own renderer (eg. extending DefaultTableRenderer) and put in getTableCellRendererComponent method something like this:
    if( isSelected && hasFocus )
        setBackground( Color.RED );
        setForeground( Color.GREEN );
    }

  • Jtable keep the selected cells' background

    hi,
    I want to change the background color of the selected cells.
    after selection, I may do another selection,but I want to keep the previous selected cells' background color.
    any help will be appreciated!
    thanks!
    zhangv

    Did you try using Ctrl + Mouse Click ?
    Remember you need to set following property before you try the above solution:
    tableObj.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION );

  • A problem to get the value of a selected cell

    Hi all,
    I am trying to get the value of a cell in JTable. The problem that I have is ListSelectionListener only listens if the selection changes(valueChanged method).
    It means that if I select apple then rum, only rowSelectionModel is triggered, which means I do not get the index of the column from selectionModel of ColumnModel.
    apple orange plum
    rum sky blue
    This is a piece of code from JTable tutorial that I modified by adding
    selRow and selCol variables to keep track of the location so that I can get the value of the selected cell.
    Thank you.
    if (ALLOW_ROW_SELECTION) { // true by default
    ListSelectionModel rowSM = table.getSelectionModel();
    rowSM.addListSelectionListener(new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent e) {
    if (e.getValueIsAdjusting()) return;
    ListSelectionModel lsm = (ListSelectionModel)e.getSource();
    if (lsm.isSelectionEmpty()) {
    System.out.println("No rows are selected.");
    } else {
    int selectedRow = lsm.getMinSelectionIndex();
    selRow = selectedRow;
    System.out.println("Row " + selectedRow + " is now selected.");
    else {
    table.setRowSelectionAllowed(false);
    if (ALLOW_COLUMN_SELECTION) { // false by default
    if (ALLOW_ROW_SELECTION) {
    table.setCellSelectionEnabled(true);
    table.setColumnSelectionAllowed(true);
    ListSelectionModel colSM = table.getColumnModel().getSelectionModel();
    colSM.addListSelectionListener(new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent e) {
    //Ignore extra messages.
    if (e.getValueIsAdjusting()) return;
    ListSelectionModel lsm = (ListSelectionModel)e.getSource();
    if (lsm.isSelectionEmpty()) {
    System.out.println("No columns are selected.");
    } else {
    int selectedCol = lsm.getMinSelectionIndex();
    selCol = selectedCol;
    System.out.println("Column " + selCol + " is now selected.");
    System.out.println("Row " + selRow + " is now selected.");
    javax.swing.table.TableModel model = table.getModel();
    // I get the value here
    System.out.println("Value: "+model.getValueAt(selRow,selCol));
    }

    maybe you can try with :
    table.getSelectedColumn()
    table.getSelectedRow()
    :)

  • JTable- Selection Color

    Hallo,
    I want to change my border Color of selected Cell. Because I don�t find any possibilty to change this Color.
    I create my Table with my own AbstractTableModel. Till now, I don�t have write my own TableCellRenderer.
    Can you help me?
    Stefan Gabel

    Till now, I don�t have write my own TableCellRenderer.Well, it seems that now you do...
    But watch out from a bug: the isSelected always returns false.
    So you have to do it this way:
            DefaultTableCellRenderer myColumnRenderer = new DefaultTableCellRenderer() {
                public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                    // Correct the selected value, since java has a bug here.
                    int[] iSelectedRows = table.getSelectedRows();
                    if (iSelectedRows != null) {
                        for(int i=0; i< iSelectedRows.length; i++) {
                            if (iSelectedRows[i] == row) {
                                isSelected = true;
                                break;
    ...This handles the rows, add a similar check for columns if you like cell-specific.
    Then just set the color if it is REALLY selected.

  • Cross-JTable selection

    In a scenario where there are two JTable's in order to implement "locked (frozen) columns", one has to address the cross-JTable selection issue that occurs when both tables' "columnSelection" and "rowSelection" properties are enabled, and the user clicks & drags the mouse to select a range of cells across the two JTables.
    Has anyone ever done this?
    Mert

    Interesting question - I would try to register one mouseListener to both tables that makes sure the events are redispatched if the mouse exits the one and enters the other during a addSelection.Or you can try to patch the BasicTableUI.MouseHandler to go on with addSelection even after a mouseExited during a mouseDragged. Never tried it, though. (Always assuming that one there is one selectionListener that extends a selection in one table to the other)
    Greetings
    Jeanette

  • JTable - active cell not highlited when editable

    Hello,
    I'm using JDK 1.4.2_05, and I'm seeing some behavior that seems a bit strange.
    In my JTables, some cells are editable, and others are not. When the user moves the active cell around (with the arrow keys, or TAB and RETURN) the non-editable cells show up with a nice blue color. If a cell is editable, it doesn't change at all, so the user has no idea where the "cursor" (meaning the active cell) is.
    These cells don't have any special renderer or anything. My JTable has these set:
    setRowSelectionAllowed(false);
    setColumnSelectionAllowed(false);
    setCellSelectionEnabled(true);Thanks for any advice!
    --- Eric

    Okay, yeah, I overrode the default renderer, and had it check whether the cell was selected or not, setting the background color appropriately. Duh. --- Eric

  • Jtable on cell changed event

    How can i treat an Jtable on cell changed event, not on value changed

    Do you mean cell selection changed? One way is to add a ListSelectionListener to both the table's and the table's ColumnModel's ListSelectionModels. Something likeListSelectionListener lsl = new ListSelectionListener() {
       public void valueChanged(ListSelectionEvent e) {
          System.out.println(e.getSource());
          ListSelectionModel lsm = (ListSelectionModel) e.getSource();
          if (!lsm.getValueIsAdjusting()) {
             System.out.println("Selection changed");
    table.getSelectionModel().addListSelectionListener(lsl);
    table.getColumnModel().getSelectionModel().addListSelectionListener(lsl);Note that simultaneous change of both row and column will generate two valueChanged events.
    If that's not what you wanted to know, ask a better question.
    [http://catb.org/~esr/faqs/smart-questions.html]
    db

Maybe you are looking for

  • Skinning with CSS in Flex

    I have a question regarding the best way to apply a CSS file to a component or application. I have tried compiling my CSS files into a SWF and then loading them at runtime like the first line of code below which would be associated with the root tag.

  • Connect ibook to Compuserve

    Hi. I am having a bit of a problem. I have an iBook G4, but I've always had a PC so I am still learning about Macs. At school, I am able to connect to the internet either with the use of an ethernet cable or with wireless. However, at home, I have di

  • PROBLEM IN SELECT OPTION

    Dear all, i want to display the document no,document status,date of document,document type and item details here input field is document number.tables are bkpf and bseg.i wrote the program and executed that program it causes runtime error.so please s

  • N97 How to sort contacts by company name

    Is it possible to sort contacts by company name rather than first name,last name etc?

  • Need sql query

    Hi, I need a query having the column name with comma... For Ex. select table_name from user_tables; I need the output as one, two, three, etc..., Kinldy provide me the query,... Rgds... Edited by: user537350 on May 28, 2009 10:20 PM