JTable: setSelectionBackground with columnMargin

I have a JTable in which I'm setting a selection background color.
objectTable.setSelectionBackground( new Color( 0xCC, 0xCC, 0xFF ) );
I'm also setting a column margin using :
DefaultTableColumnModel colModel = (DefaultTableColumnModel) objectTable.getColumnModel( );
colModel.setColumnMargin( 12 );
When you select a row in the table, the selection background is only used for
the cells themselves, excluding the margins. You end up with selected cells
interspersed with white margins.
Anyone know of a reasonably simple way to get the margins around a selected
cell to paint with the selection background color?

I have a JTable in which I'm setting a selection
background color.
objectTable.setSelectionBackground( new Color( 0xCC,
0xCC, 0xFF ) );
I'm also setting a column margin using :
DefaultTableColumnModel colModel =
(DefaultTableColumnModel)
objectTable.getColumnModel( );
olModel.setColumnMargin( 12 );
When you select a row in the table, the selection
background is only used for
the cells themselves, excluding the margins. You end
up with selected cells
interspersed with white margins.
Anyone know of a reasonably simple way to get the
margins around a selected
cell to paint with the selection background color?The margin, by definition, is the space between cells, so it plays no part in selection and such. I think Michael is on the right track. Forget about the margin, do the work in the renderer. See example below.
Jim S.
=================
import java.awt.Color;
import java.awt.Component;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.table.DefaultTableCellRenderer;
public class MarginTest {
    MarginTest() {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        String[][] data = new String[10][10];
        String[] columnNames = new String[10];
        for (int i = 0; i < 10; i++) {
            for (int j = 0; j < 10; j++) {
                data[i][j] = "<" + i + "," + j + ">";
            columnNames[i] = "Column " + i;
        JTable t = new JTable(data, columnNames);
        t.setDefaultRenderer(Object.class, new MyRenderer());
        f.add(new JScrollPane(t));
        f.setSize(400, 300);
        f.setVisible(true);
    public static void main(String[] args) {
        new MarginTest();
    static class MyRenderer extends DefaultTableCellRenderer {
        private Border CACHED_SEL_BORDER = BorderFactory.createMatteBorder(
                0,
                6,
                0,
                6,
                UIManager.getColor("Table.selectionBackground"));
        private Border CACHED_BORDER = BorderFactory.createMatteBorder(
                0,
                6,
                0,
                6,
                UIManager.getColor("Table.background"));
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            Border currentBorder = getBorder();
            if(isSelected) {
                ((JComponent)this).setBorder(BorderFactory.createCompoundBorder(currentBorder, CACHED_SEL_BORDER));
            } else {
                ((JComponent)this).setBorder(BorderFactory.createCompoundBorder(currentBorder, CACHED_BORDER));
            return this;
}

Similar Messages

  • JTable/jlist with word wrapping cells?

    Hello all,
    I got a simple looking problem but i can't seem to find any working solution for it:
    A jtable or jlist with cells that wordwrap text (cells differ in height).
    I found many examples on groups.google and this forum but they all seem to suffer a 100% processor load when 2 or more cells differ in height.
    Can anyone point me to a working example?
    Kind regards,
    Twan

    Thanks! That's a real live saver.
    I had been looking for a solution for several days, strange google did not yet found the mentioned page, cause it contains usefull information.
    I've just implemented the multiline table and it works without any problems and most important without 100% cpu usage.
    The bucks are comming your way ;-)

  • Traverse JTable cells with arrow keys?

    I want to be able to use arrow keys to travel in the matrix. But I want to restrict entering column 0. That is, the user should not be able to enter column 0, with the arrow keys (and neither using the mouse). Anyone have hints how to do this?

    Well, the problem is that I have a viewport into a big matrix. The user is able to scroll the viewport around.
    I must be able to figure out if the user is pressing the arrow buttons to go outside the viewport, because then I have to change the viewport. Somewhere, there is a class that knows the current cell that is highlighted. I must check that class to see what direction the user wants to go with the highlighted cell.
    And, also, the user is not allowed to enter column 0. If he wants to go column 0, then the viewport will be scrolled.
    So my question is, which class knows which cell is highlighted? The Jtable, probably? Which methods?

  • JTable Cell with two icons

    Hello -
    I'm rather new to Java, so please excuse me if this is a simple question. For a project I am working on, I am attempting to deal with placing two icons in a single JTable cell. For the life of me I have no idea if this is even feasible, let alone how I would implement it. Originally I thought about attempting to overload the JLabel class (as this is what the JTable cell is based upon, if I'm not mistaken?) and allowing two icons to be placed per label.
    Am I on the right track? Is this even possible? Any suggestions?
    Thanks much.

    Please read the forum for JTable.
    http://java.sun.com/docs/books/tutorial/uiswing/components/table.html
    You will know that you canuse any component as CellRenderer, this component can have whatever you want (say 2 icons and 5 comboboxes)
    here is short example that shows 2 icons in JTable
    import java.awt.*;
    import java.awt.image.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TwoIcons extends JFrame {
         public static void main(String[] args){
              createIcons();
              SwingUtilities.invokeLater
                   new Runnable()
                        public void run() {
                             new TwoIcons();
         public TwoIcons(){
              super("Test");
              DefaultTableModel tm = new DefaultTableModel(
                   new Object[][]{
                        {new IconPair("cross", "cross"), "just a string"},
                        {new IconPair("circle", "cross"),"just another string"},
                        {new IconPair("String", "circle"),"yet another string"}
                   }, new String[]{"Two Icons","String"}){
                   public Class getColumnClass(int columnIndex){
                        if(columnIndex==0){
                             return IconPair.class;
                        else
                             return super.getColumnClass(columnIndex);
              JTable table = new JTable(tm);
              final Color bg = table.getBackground();
              table.setDefaultRenderer(IconPair.class, new TableCellRenderer(){
                        RendererPanel renderer = new RendererPanel(bg);
                        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                             renderer.setIcons((IconPair)value);
                             return  renderer;
              JScrollPane scp = new JScrollPane(table);
              add(scp);
              setSize(400,100);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              pack();
              setVisible(true);
         class RendererPanel extends JPanel{
              JLabel tf1,tf2;
              RendererPanel(Color bg){
                   setLayout(new BoxLayout(this,BoxLayout.LINE_AXIS) );
                   tf1=new JLabel();
                   tf2=new JLabel();
                   add(tf1);
                   add(Box.createRigidArea(new Dimension(5,0)));
                   add(tf2);
                   setBackground(bg);
              public void setIcons(IconPair value) {
                   tf1.setIcon(value.i1);
                   tf2.setIcon(value.i2);
                   //uncomment next 2 lines if you want text as well
    //               tf1.setText(value.s1);
    //               tf2.setText(value.s2);
         class IconPair {
              public Icon i1,i2;
              public String s1,s2;
              IconPair(String s1, String s2){
                   this.i1=icons.get(s1);
                   this.i2=icons.get(s2);
                   this.s1=s1;
                   this.s2=s2;
         static Map<String,Icon> icons = new HashMap<String,Icon>();
         public static  void createIcons(){
              Image img = new BufferedImage(10,10, BufferedImage.TYPE_INT_ARGB);
              Graphics2D g2=(Graphics2D)(img.getGraphics());
              g2.setColor(Color.RED);
              g2.drawLine(0,0,10,10);
              g2.drawLine(0,10,10,0);
              icons.put("cross",new ImageIcon(img));
              img = new BufferedImage(10,10, BufferedImage.TYPE_INT_ARGB);
              g2=(Graphics2D)(img.getGraphics());
              g2.setColor(Color.GREEN);
              g2.drawOval(1,1,8,8);
              icons.put("circle",new ImageIcon(img));
    }

  • JTable sorting with frozen columns

    Hi All,
    I have implemented a table with two frozen columns by using two Jtables within a JScrollpane. I've added a TableRowSorter to each table (the fixed and the scrollable one). The first two columns are removed from the main JTable's columnModel and the other columns are removed from the fixed JTable's columnModel. The sorting works fine but currently works on the two tables seperately. They both have the same table model which is one i implemented by extending AbstractTableModel. How can i link up the two tables so that they sort together?
    Thanks

    using the same instance of TableRowSorter with both tables fixed it

  • Sorting JTable column with DefaultTableModel

    Hi all,
    can i sort the column in Jtable which is using the DefaultTableModel? If can, how? I have downlaad the TableSorter.java and implement it into my code which is using DefaultTablemodel, but it doesn't work... :(
    If sort does not work with the DefaultTableModel, which model should i use that will list the records in the JTable and sort it?
    Thanks in advance for yr help...

    When you create your own table model you usually extend the AbstractTableModel class, and the DefaultTableModel class does just the same.
    So I think your problem is likely to be due to the sorter class itself, rather than the model.
    I hope this will help you.
    Bye

  • JTable crashes with NullPointer exception

    Hi
    I use a JTable with a selfmade TableModel.
    On first display I get an Nullpointer exception
    in the JTable, when it calls prepareRenderer.
    I'm not using the DefaultRenderer ... that is I'm not specifying it explicitly.
    Has anybody seen this behaviour before?
    Thanx a lot
    Spieler

    In your TableModel do you use a custom Renderer as well? You said you're not using the DefaultRenderer, so I assume you're calling the setDefaultRenderer() method?
    Check to make sure you have the proper class given as the class of the renderer. I had this problem once because I had accidentally given a different class than what the renderer really was.
    Example:
    // my custom renderer
    MyRenderer1 renderer = new MyRenderer1();
    // wrong class
    setDefaultRenderer(MyRenderer.class, renderer);
    // right class
    setDefaultRenderer(MyRenderer1.class, renderer);Hope this helps!
    - Brion Swanson

  • JTable - Help with updating a Text File

    Hi all,
    I've been fighting this for a few days. I am trying to update a Text File with my JTable.... Displaying the data works great but when I try to edit a cell/field on the gui, I'm bombing out...... My text fiel is a small user control file with Id, Name,
    Date, etc etc with the fields delimited with a "|".... I have built an Abstract Data Model (see below).... and I think my problem is in the setValueAt method.......
    Thanks so much in advance!!!!
    Mike
    code:
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    import java.io.*;
    import java.util.*;
    public class DataFileTableModel extends AbstractTableModel {
    protected Vector data;
    protected Vector columnNames ;
    protected String datafile;
    public DataFileTableModel(String f){
    datafile = f;
    initVectors();
    public void initVectors() {
    String aLine ;
    data = new Vector();
    columnNames = new Vector();
    try {
    FileInputStream fin = new FileInputStream(datafile);
    BufferedReader br = new BufferedReader(new InputStreamReader(fin));
    // extract column names
    StringTokenizer st1 =
    new StringTokenizer(br.readLine(), "|");
    while(st1.hasMoreTokens())
    columnNames.addElement(st1.nextToken());
    // extract data
    while ((aLine = br.readLine()) != null) { 
    StringTokenizer st2 =
    new StringTokenizer(aLine, "|");
    while(st2.hasMoreTokens())
    data.addElement(st2.nextToken());
    br.close();
    catch (Exception e) {
    e.printStackTrace();
    public int getRowCount() {
    return data.size() / getColumnCount();
    public int getColumnCount(){
    return columnNames.size();
    public String getColumnName(int columnIndex) {
    String colName = "";
    if (columnIndex <= getColumnCount())
    colName = (String)columnNames.elementAt(columnIndex);
    return colName;
    public Class getColumnClass(int columnIndex){
    return String.class;
    public boolean isCellEditable(int rowIndex, int columnIndex) {
    return true;
    public Object getValueAt(int rowIndex, int columnIndex) {
    return (String)data.elementAt( (rowIndex * getColumnCount()) + columnIndex);
    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
    Vector rowVector=(Vector)data.elementAt(rowIndex);
    rowVector.setElementAt(aValue, columnIndex);
    fireTableCellUpdated(rowIndex,columnIndex);
    // return;
    }

    No, the DefaultDataModel does not update the physical data file. It is just used to store the data as you type in the table cells.
    The code from above is used to read data from a file and populate the DataModel.
    Now you need to write another routine that will take the data from the DataModel and write it to your file. I have never actually done this but I think the code would be something like:
    int rows = table.getModel().getRowCount();
    int columns = table.getModel().getColumnCount();
    //  Write column headers
    for (int j = 0; j < columns; j++)
         TableColumn column = table.getColumnModel().getColumn(j);
            Object o = column.getHeaderValue();
         writeToFile( o.toString() + "|" );
    writeToFile( "\n" );
    // Write each row
    for (int i = 0, i < rows; i++)
        for (int j = 0, j < columns; j++)
            Object o = table.getValueAt(i, j);
            writeToFile( o.toString + "|" );
        writeToFile( "\n" );
    }If you need to update the file whenever data in a cell changes, then you could extend the DefaultTableModel and override the setValueAt() method to also write the contents of the DataModel to a file. But this is a lot of overhead since it rewrite the entire file for every cell change.

  • JTable setSelectionBackground

    Is there a way to set all the cells in a selected row in a JTable to the same selection background color.
    I'm able to set all cells in a selected row to a specific color EXCEPT the selected cell. This selected cell defaults to a white background - while all cells to the left and right in the current row change background colors as specified.
    Using the code
    myTable.setSelectionBackground(myTable.getSelectionBackground());
    or
    myTable.setSelectionBackground(Color.blue);
    yeild the same results - it changes all the selected row's cells but the one cell that's actually selected.
    thanks for any help

    Is there a way to set all the cells in a selected row in a JTable to the same selection background colI know of at least two ways to do that.... The background color of the cell that looks different than the rest is the cell that currently has focus -- if you change it to look the same as the rest, if would be difficult to tell which cell has focus. But if you want to change the color anyway, you can either use:
    1) UIManager.put("Table.focusCellBackground",Color.red); // or whatever color you want
    2) Add a cell renderer and change the color of the cell that has focus.
    If you chose 1, you must do it before a table is created. If you chose step 2 and don't know how to do it, click the Tutorials on the left of this page or search for cellrenderer.
    ;o)
    V.V.

  • JTable interferes with form scrolling

    Hi,
    I have a dialog with a scrollpane around a form which has many controls. The form gets a vertical scrollbar and I want to scroll the form up and down.
    This works fine but I have several tables on the form which if my mouse is over the jtable it (I suppose) tries to scroll the jtable - even though there is no vertical scrollbar on the table to scroll.
    How can I get it to not try to scroll the table and instead have the form (jpanel) scroll up and down - like it does if my mouse is over the panel itself.
    thanks!
    Greg

    try removing the mouseWheelListeners from the various table scrollpanes
    e.g.
    sp.removeMouseWheelListener(sp.getMouseWheelListeners()[0]);

  • JTable - Help with column names and rowselection

    Hi,
    Is there anyone that can help me. I have successfully been able to load a JTable from an MS access database using vectors. I am now trying to find out how to hardcode the column names into the JTable as a string.
    Can anyone please also show me some code on how to be able update a value in a cell (from ''N'' to ''Y'') by double clicking on that row.
    How can I make all the other columns non-editable.
    Here is my code:
         private JTable getJTable() {
              Vector columnNames = new Vector();
    Vector data = new Vector();
    try
    // Connect to the Database
    String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
    // String url = "jdbc:odbc:Teenergy"; // if using ODBC Data Source name
    String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=C:/Documents " +
              "and Settings/Administrator/My Documents/mdbTEST.mdb";
    String userid = "";
    String password = "";
    Class.forName( driver );
    Connection connection = DriverManager.getConnection( url, userid, password );
    // Read data from a table
    String sql = "select * from PurchaseOrderView";
    Statement stmt = connection.createStatement();
    ResultSet rs = stmt.executeQuery( sql );
    ResultSetMetaData md = rs.getMetaData();
    int columns = md.getColumnCount();
    // Get column names
    for (int i = 1; i <= columns; i++)
    columnNames.addElement( md.getColumnName(i) );
    // Get row data
    while (rs.next())
    Vector row = new Vector(columns);
    for (int i = 1; i <= columns; i++)
    row.addElement( rs.getObject(i) );
    data.addElement( row );
    rs.close();
    stmt.close();
    catch(Exception e)
    System.out.println( e );
              if (jTable == null) {
                   jTable = new JTable(data, columnNames);
                   jTable.setAutoCreateColumnsFromModel(false);
                   jTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_NEXT_COLUMN);
                   jTable.setShowHorizontalLines(false);
                   jTable.setGridColor(java.awt.SystemColor.control);
                   jTable.setRowSelectionAllowed(true);
                   jTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
                   jTable.setShowGrid(true);     
              return jTable;
         }

    this method has a default behavior to supply exactly what you're seeing: column names consisting of the capitalized letters, "A", "B", "C".Thanks Pete, had seen that but never really thought about it... about 10 days ago somebody needed to obtain Excel column names, I'd offered a rigorous solution and now see it would have been shorter and simpler (if a little heavier) to extend DefaultTableModel and provide the two additional methods needed (getOffsetCol and getColIndex).
    Not much of a difference in LOC but certainly more elegant ;-)
    Darryl

  • Highlight JTable Row with Right-Click

    How can I get a JTable to highlight a row when that row is right-clicked? Thanks, Jeremy

    table.addMouseListener(new MouseAdapter()
    public void mouseClicked (MouseEvent e)
    if(e.isMetaDown())
    int row = table.rowAtPoint(e.getX((), e.getY();
    table.setSelectionInterval(row, row);
    });Or something like that.

  • JTable Cells with different Color according to value

    Pls help I want to be able to display all rows (students) that paid more than 20 naira in Green
    else display rows (student) that paid < 20 naira in red
    But at the moment it is displaying everything in green why?
    tmp is the variable
    Code would help pls!
    class TestRenderer extends DefaultTableCellRenderer     
    public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,               int column)          
    super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);          
    if (row > 0)               
    for (int i =0; i < table.getRowCount(); i++)
    String tmpString = (String) table.getValueAt(i,3);
    if (tmpString != null)
    double tmp = Double.parseDouble(tmpString);
    if (tmp > 20)
    System.out.println("Variable is "+tmp);
    setBackground( Color.green );
    else
    setBackground( Color.red );     
    return this;

    Get rid of that loop
    String tmpString = (String) table.getValueAt(row,3);

  • Single JTable Column with several diff Cell Editors

    Am trying to create a single JTable column that can have several different cell editors. Java seems to be bias to having 1 cell editor for the whole column.
    For example in 1 column can I have
    Row1 : TextBox
    Row2: Check Box
    Row3: Radio Buttons
    Row4: JColorChooser
    At the moment I can only have one CellEditor for the whole column which is not very helpful.

    the default implementation offers to provide editors per column in the tableColumn and/or editors per class type by setting default editors ( JTable.setDefaultEditor(Class class, TableCellEditor editor) ). If you look at the getCellEditor method of JTable you see that first the tablecolumns are asked for an editor, and if this doesnt succeed a default editor for the class acording to the value at the passed grid position is determined.
    If this does not fullfil your needs, you can still overwrite the getCellEditor method of JTable and return whatever editor is suitable.
    regards,
    stefan

  • Priblem with JTable constructer with Vector!!!

    Hi,
    I have a big problem,
    I defined my table,
    in an interface i have;
    Vector rdata = new Vector();
    Vector cnames = new Vector();
    Object rowdatas = {"a","b","c"}
    and in my class i defined
    JTable mytable = new JTable(rdata , cnames);
    and in an other interface i have a function ,
    void setRow(JTable table, Object[] rowdatas)
    Vector onerow = new Vector();
    for(int i=0; i<rowdatas.length ; i++)
    onerow.addElement(rowdatas);
    row.addElement(onerow);
    but when i write,
    ...setRow(mytablem,rowdatas )
    then the added row in my table is
    | a | a | a |
    i.e however my vector have the correct datas, in table all the row datas are the first data of the vector.Why!
    Plese help,Thanks... :(

    Sorry!You are wright,I had written wrong.
    The correct codes are :
    in an interface i have;
    Vector rdata = new Vector();
    Vector cnames = new Vector();
    Object rowdatas = {"a","b","c"}
    and in my class i defined
    JTable mytable = new JTable(rdata , cnames);
    and in an other interface i have a function ,
    void setRow(JTable table, Object[] rowdatas)
    Vector onerow = new Vector();
    for(int i=0; i<rowdatas.length ; i++)
    onerow.addElement(rowdatas);
    row.addElement(onerow);
    but when i write,
    ...setRow(mytablem,rowdatas )
    then the added row in my table is
    | a | a | a |
    i.e however my vector have the correct datas, in table all the row datas are the first data of the vector.Why!
    ,also you can rewrite the as
    Vactor rowdatas = new Vector();
    rowdatas.addelement(a);
    rowdatas.addelement(b);
    rowdatas.addelement(c);
    and then add this vector to the rdata ...

Maybe you are looking for

  • MacBook Pro retina or non retina?

    What is a better laptop ? I'm not sure which one to buy, the retina which I would have to wait for updates to see the full potential of the retina. I want to have the laptop for A while and will need it to use everyday, emailing, TONS of googling and

  • Credit Card: New Number

    My credit card has expired.  How do I let you know the new one?

  • Button on selection screen to link with PDF

    Hello, I have a customer request to provide documentation for each transaction on its selection screen. So they want to have a button on selection screen which should download PDF file stored on SAP application server. Is this possible (they said it

  • Denying end users access to a flash file

    Hi everyone, I'm working on a project that I'm hoping to get some help with, I'm very new to flash. I need a way to steam a flash video to a users browser, without the file actualy being downloaded onto the users computer. Basicly my company wants to

  • I need to use Adobe Flash PLayer for an online conference.  I get a pop-up blocked message.

    I need to use Adobe Flash PLayer for an online conference.  I get a pop-up blocked message. I have already unblocked pop-ups as far as I can see. Maybe I'm missing something?