0

==== New info and mre at bottom =====

What I would like to get from the code below is the second row with a different font from the other rows and that the whole table is center aligned. The problem is that if I leave both renders uncommented only the second one is displayed. If the first is the font change, only the center alignment is displayed and vice versa if the first is the alignment, only the font change is displayed

public class Example extends JFrame {
 
    private static final String[] COLUMNS = { "1", "2","3"}; //, "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"  };

    public Example() {
        super("test");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        JTable table = new JTable(data(), COLUMNS);
        
        for (int i = 1; i<= 2; i++){
        table.getColumnModel().getColumn(i).setCellRenderer((TableCellRenderer) new 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);
                if (c instanceof JLabel) {
                    JLabel renderer = (JLabel) c;
                    if (row == 1) {
                        renderer.setFont(new Font("Arial", Font.BOLD, 15));} 
                    else {
                            renderer.setFont(table.getFont());} 
                }
                return c;
            }
            });
            }
        /**
        TableColumn column = null;
        DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer(); //center value in columns
        centerRenderer.setHorizontalAlignment(JLabel.CENTER);
        for (int i = 0; i <= 2; i++) {
        column = table.getColumnModel().getColumn(i);
        if (i == 0) { //This must be letf aligned with size of 100
            column.setPreferredWidth(100);}
        else {
            column.setPreferredWidth(30);
            table.getColumnModel().getColumn(i).setCellRenderer(centerRenderer);
        }}
        
        **/

        JScrollPane sp = new JScrollPane(table);
        add(sp);
        pack();
        setLocationRelativeTo(null);
    }

    private Object[][] data() {
        Object[][] data = { { 113, 444, 234 }, { 233, 555, 234  }, { 110, 92, 234  }, { 55, 66, 234  }, { 123, 603, 234  }, { 412, 120, 234  }, };
        return data;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new Example().setVisible(true));
    }
}

==== ==== This is new ===

=== It's not very orthodox but I didn't know how to do it ===

The link you suggested is good for two of the three things I would like to achieve: the colored background and the change of font on one line. [in the mre only column 0 is affected but this is not a problem)

What I can't figure out is the sizing of the first column. Problem parts are commented out where column == 0

public class TableRenderer extends JPanel
{
    public TableRenderer()
    {
        String[] columnNames = {"String", "Integer"};
        Object[][] data =
        {
            {"AAAAAAAAAAAAAAAAAAAA", new Integer(1)},
            {"B", new Integer(2)},
            {"C", new Integer(10)},
            {"D", new Integer(4)}
        };

        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        JTable table = new JTable( model );
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane( table );
        add( scrollPane );

        //  Override default renderer on a specific column

        TableCellRenderer colorRenderer = new ColorRenderer();
        table.getColumnModel().getColumn(1).setCellRenderer( colorRenderer );
    }

    /*
    **  Color the focused cell
    */
    class ColorRenderer extends DefaultTableCellRenderer
    {
        public ColorRenderer()
        {
            super();
            setHorizontalAlignment(JLabel.CENTER);
        }

        @Override
        public Component getTableCellRendererComponent(
            JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
        {
            super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

            if (isSelected)
                setBackground( table.getSelectionBackground() );
            else
            {
                setBackground( null );
                
                if (column == 0) { //This must be letf aligned with size of 100
                }//setPreferredWidth(100);}
                else {
                    //setPreferredWidth(30);
                    //table.getColumnModel().getColumn(i).setCellRenderer(colorRenderer) 
                }
                try
                {
                    int number = Integer.parseInt( value.toString() );
                    if (row == 1) {
                        setFont(new Font("Arial", Font.BOLD, 25));} 
                    if (number > 9)
                        setBackground( Color.RED );
                }
                catch(Exception e) {}
            }

            return this;
        }
    }
    
    private static void createAndShowGUI()
    {
        JFrame frame = new JFrame("Color Renderer");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new TableRenderer());
        frame.pack();
        frame.setLocationByPlatform( true );
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater( () -> createAndShowGUI() );
/*
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowGUI();
            }
        });
*/
    }}
Ryan Day
  • 113
  • 1
  • 8
  • 2
    You can only have a single renderer for each column. So your custom renderer needs to control both the Font and alignment. – camickr Jun 26 '23 at 19:08
  • Nice to kinow. Will work on it. Thank you – Ryan Day Jun 27 '23 at 07:42
  • Im sorry but I cant obtain a single renderer making the two thing. May I need a different renderer – Ryan Day Jun 27 '23 at 11:44
  • Why? You already have the renderer to set the Font. So you just add your setHorizontalAlignement(...) statement to that renderer. See: https://stackoverflow.com/a/42180634/131872 for an example. Post your ]mre] demonstrating the problem if you need more help – camickr Jun 27 '23 at 13:41
  • Pls, see the add after the original question – Ryan Day Jun 27 '23 at 18:35
  • Read the Swing tutorial on [How to Use Tables](https://docs.oracle.com/javase/tutorial/uiswing/components/table.html) for the basics. *This must be letf aligned* - if a column has different rendering logic, then use a different renderer. You need one for the first column and one for the others. *with size of 100* - the renderer doesn't control the width of the column. Read the tutorial for information on how to control the width. – camickr Jun 28 '23 at 01:12

0 Answers0