How to give different Colour to Columns in JTable

Hi,
I am using a JTable and entering Data into it. I want each column of the JTable to be in different colour. Kindly Help. Some example code will be very helpful.
Waiting Eagerly.....
My Code....
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowAdapter;
import java.awt.Window;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import javax.swing.*;
import java.util.Vector;
import java.awt.GridLayout;
import java.util.*;
import javax.swing.table.TableModel;
public class SummScr extends JPanel {
public JTable ProSerSumTable;
public String ColumnNames[];
public String dataValues[][];
//public Vector ProSerDet = new Vector();
//constructor
public SummScr(){     
super(new GridLayout(1,0));
createColumns();
createData();
TableModel ProSerTabMod = new AbstractTableModel(){
public int getColumnCount(){return ColumnNames.length; }
public int getRowCount(){return dataValues.length;}
public Object getValueAt(int row, int col){return dataValues[row][col]; }
public String getColumnName(int col){return ColumnNames[col];}
public Class getColumnClass(int col) {return getValueAt(0,col).getClass();}
public void setValueAt(Object aValue, int row, int col){dataValues[row][col] = (String)aValue; }
ProSerSumTable = new JTable(ProSerTabMod);
ProSerSumTable.setPreferredScrollableViewportSize(new Dimension(400,200));
JScrollPane scrollpane = new JScrollPane(ProSerSumTable);
//JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
//scrollpane.add(ProSerSumTable);
add(scrollpane);
public void createColumns(){
ColumnNames = new String[4];
ColumnNames[0] = "Processes";
ColumnNames[1] = "Normal Threshold";
ColumnNames[2] = "On Hold";
ColumnNames[3] = "Exceeded Threshold";
public void createData(){
dataValues = new String[3][4];
dataValues[0][0] = "Merit";
dataValues[0][1] = "60%";
dataValues[0][2] = "0%";
dataValues[0][3] = "40%";
dataValues[1][0] = "SuperMarket";
dataValues[1][1] = "70%";
dataValues[1][2] = "0%";
dataValues[1][3] = "30%";
dataValues[2][0] = "Passport";
dataValues[2][1] = "65%";
dataValues[2][2] = "0%";
dataValues[2][3] = "35%";
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create and set up the window.
JFrame frame = new JFrame("Summary Screen");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
SummScr newContentPane = new SummScr();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}

try this, also put your code into the code tags to help read your code
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
public class SummScr extends JPanel {
     private static final long serialVersionUID = 1L;
     public JTable ProSerSumTable;
     public String ColumnNames[];
     public String dataValues[][];
     // public Vector ProSerDet = new Vector();
     // constructor
     public SummScr() {
          super(new GridLayout(1, 0));
          createColumns();
          createData();
          TableModel ProSerTabMod = new AbstractTableModel() {
               private static final long serialVersionUID = 1L;
               public int getColumnCount() {
                    return ColumnNames.length;
               public int getRowCount() {
                    return dataValues.length;
               public Object getValueAt(int row, int col) {
                    return dataValues[row][col];
               public String getColumnName(int col) {
                    return ColumnNames[col];
               public Class<?> getColumnClass(int col) {
                    return getValueAt(0, col).getClass();
               public void setValueAt(Object aValue, int row, int col) {
                    dataValues[row][col] = (String) aValue;
          ProSerSumTable = new JTable(ProSerTabMod);
          TableColumn tc = null;
//next line sets the renderer to your columns, in this example there are only four columns so its fairly easy,
//though it should be no harder no matter how many columns
          for(int i = 0; i < 4; i++){
               tc = ProSerSumTable.getColumnModel().getColumn(i);
               tc.setCellRenderer(new ColumnColourRenderer());
          ProSerSumTable.setPreferredScrollableViewportSize(new Dimension(400,
                    200));
          JScrollPane scrollpane = new JScrollPane(ProSerSumTable);
          // JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
          // scrollpane.add(ProSerSumTable);
          add(scrollpane);
     public void createColumns() {
          ColumnNames = new String[4];
          ColumnNames[0] = "Processes";
          ColumnNames[1] = "Normal Threshold";
          ColumnNames[2] = "On Hold";
          ColumnNames[3] = "Exceeded Threshold";
     public void createData() {
          dataValues = new String[3][4];
          dataValues[0][0] = "Merit";
          dataValues[0][1] = "60%";
          dataValues[0][2] = "0%";
          dataValues[0][3] = "40%";
          dataValues[1][0] = "SuperMarket";
          dataValues[1][1] = "70%";
          dataValues[1][2] = "0%";
          dataValues[1][3] = "30%";
          dataValues[2][0] = "Passport";
          dataValues[2][1] = "65%";
          dataValues[2][2] = "0%";
          dataValues[2][3] = "35%";
     private static void createAndShowGUI() {
          // Make sure we have nice window decorations.
          JFrame.setDefaultLookAndFeelDecorated(true);
          // Create and set up the window.
          JFrame frame = new JFrame("Summary Screen");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          // Create and set up the content pane.
          SummScr newContentPane = new SummScr();
          newContentPane.setOpaque(true); // content panes must be opaque
          frame.setContentPane(newContentPane);
          // Display the window.
          frame.pack();
          frame.setVisible(true);
     public static void main(String[] args) {
          // Schedule a job for the event-dispatching thread:
          // creating and showing this application's GUI.
          javax.swing.SwingUtilities.invokeLater(new Runnable() {
               public void run() {
                    createAndShowGUI();
     class ColumnColourRenderer extends DefaultTableCellRenderer{
          public ColumnColourRenderer() {
               super();
          public Component getTableCellRendererComponent(JTable table, Object value,
                    boolean isSelected, boolean cellHasFocus, int row, int column) {
               if (column %2 == 0) {
                    setText((table.getModel().getValueAt(row, column)).toString());
                    if (isSelected) {
                          setBackground(table.getSelectionBackground());
                          setForeground(table.getSelectionForeground());
                    else {
                         setBackground(Color.RED);
               } else if (column %2 != 0){
                    setText((table.getModel().getValueAt(row, column)).toString());
                    if (isSelected) {
                          setBackground(table.getSelectionBackground());
                          setForeground(table.getSelectionForeground());
                    else {
                         setBackground(Color.BLUE);
               return this;
}

Similar Messages

  • HELP Friends!!! How to set the width of columns of JTABLE?

    Hi!
    How to set the width of a particular column in JTable?
    I tried using headerRenderers and though I'm able to set the color and font of the header (using getTableCellRendererComponent method)I can't change the size.
    Pls some one help me..it's very urgent.
    Thanks in advance.
    Regards,
    Naval

    JTable.getColumnModel().getColumn(i).setWidth(width). There are also setPreferredWidth, setMaxWidth and setMinWidth methods.

  • How to give different value to a static variable???

    Hi all:
    Is there any solution to set different values to a static variable???I had try two ways but all have errors!
    1.Way_1
    protected String tmp=null;
    protected void initSituation(int sayorpress)
    if (sayorpress==0)
    tmp = "string1";
    else if (sayorpress==1)
    tmp = "string2";
    protected static String RESOURCE_STRING = tmp; <---error
    Error:non-static variable tmp cannot be referenced from a static context
    2.Way_2
    protected void initSituation(int sayorpress)
    if (sayorpress==0)
    protected static String RESOURCE_STRING = "string1"; <---error
    else if (sayorpress==1)
    protected static String RESOURCE_STRING = "string2"; <---error
    Error:illegal start of expression at
    not an expression statement at
    Thank you very mich!!!

    Try this:
    protected static String RESOURCE_STRING = null;
    protected void initSituation(int sayorpress)
    if (sayorpress==0)
    yourClass.RESOURCE_STRING = "string1";
    else if (sayorpress==1)
    yourClass.RESOURCE_STRING = "string2";
    You cannot declare a static variable inside a method. But you can access a static variable thorugh your class.

  • Two 23" displayed hooked on same G5 give different colours

    I have just bought a new G5 and hooked my 23" HD Cinema display to it. I used to use it with my Powerbook, and I missed the spanning feature, so I decided to get a second one which was delivered and installed yesterday.
    Immediately I noticed a difference in the colors of the two units. The older display has a whitewashed look on all colors as if the contrast is set too low.
    The colorsync utility reports that the factory setting for each monitor is different. 42482EC.icc for the new one and 424832D.icc for the old one.
    Does this mean that I have to live with the color difference or is it possible that the older monitor has a damaged backlight? I have two months left under guarantee for it so hopefully I will be able to get this repaired (replaced) for free.
    Any ideas or suggestions?

    You need to calibrate your displays. If you really want them to match, you will need to use a colorimeter with a software bundle that includes dual display matching. It's really tough to do "by eye" but you can probably get "reasonably close" by using OSX's "expert mode" calibration tool. It is completely unrealistic (unless you are Irish) to expect two displays to match "out of the box" even if they are "identical" units.

  • Alternate rows with different number of columns in JTable or similar

    Hi Guys,
    I have tried searching google and these forums, but have not been able to find what I am looking for.
    Looking for ideas, on how to do the following
    I have a swing application, that I would like to have alternate rows
    eg.
    1st row has 10 columns
    2nd row has 1 column, that expands all 10 columns of the 1st row
    and keeps alternating like this for the rest of the records in the table.
    Is there a special JTable that can do this for me, or has anyone had to do this before.
    Thanks,
    Mac

    an example of merging cells is here
    [http://www.crionics.com/products/opensource/faq/swing_ex/JTableExamples4.html]
    scroll down to 'Multi-Span Cell'
    run the program, highlight some cells, click combine.
    if that's the type of thing you're after, modify your code per what's in 'combine'
    note: the original code (now) produces a stack overflow error (don't know if it's been fixed in the above link),
    but if you get that error, in AttributiveCellTableModel's setDataVector( Vector newData, Vector columnNames )
    change
    setColumnIdentifiers(columnNames);
    to
    columnIdentifiers = columnNames;

  • How to make a cell or column in JTable non focusable.

    I have created a table which contains 2 rows and 2 columns. My requirement is that 2nd column should be non editable and non focusable. Making any cell non editable is very easy but how should i avoid focus on particular cell.i.e., suppose focus is on first cell and now if u press right arrow button on the keyboard 2nd cell should not get highlighted and focus should remain on first cell.
    Thanks in advance

    Override the default Tab Action. Here is an example:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=657819

  • Different coloured text in one Textbox

    Can someone PLEASE help me!!!!!!!!!!!!!!
    I need to know how to have different coloured text in the same textbox.
    My application has text being inputted into the textbox every 5 seconds from 2 different sources. I want to differenciate the text by showing the user 2 different colours for each source.
    Thank you very much

    Acording to the first post it also shows data, so it is a GUI component. i never sow a textbox.
    JTextPane can show data in different colors. also JTextArea can.
    Noah

  • Serial number column in Jtable

    Apologies for this distraction.
    I read at this forum about a year ago how to add a s/n column in Jtable such that all the nos are automatically updated/adjusted when a row is added/deleted. the count starts from the top down serially and unaffected by sorting.
    pls help!

    thanks a million BaltimoreJohn and especially camickr whose solutions to problems have been most helpful. applying the referenced post, i worked around the problem by resetting the values of the column having the serial number, based on table rowCount every time there is an operation on it(deleting, addition etc)

  • How can I give folders different colours in Mail?

    How can I give folders different colours in Mail?
    I can give emails different colours via the colour picker, but dont know how for folders.... Any help is welcome

    Thanks! Well that disappoints me very much,...
    There is really no way to make it easier visually?
    I mean I have so many folders and subfolders.
    There are no add-ons perhaps?
    Still have hope ,...

  • How do I fix colour picker to work across different colour-managed monitors?

    Hey everyone!
    I'm assuming this problem I'm having stems from having colour-calibrated monitors, but let me know if I'm wrong!
    To preface, this is the setup I have:
    Windows 7
    3 monitors as follows, all have individual colour profiles calibrated using the Spyder 3
    Cintiq 12WX
    Dell U2410
    Dell 2409WFP
    Photoshop CS6 - Proofed with Monitor RGB, and tested with colour-managed and non-colour-managed documents
    I usually do most of my work on the Cintiq 12WX, but pull the photoshop window to my main monitor to do large previews and some corrections. I noticed that the colour picker wouldn't pick colours consistently depending on the monitor the Photoshop window is on.
    Here are some video examples:
    This is how the colour picker works on my Dell U2410: http://screencast.com/t/lVevxk5Ihk
    This is how it works on my Cintiq 12WX: http://screencast.com/t/tdREx4Xyhw9
    Main Question
    I know the Cintiq's video capture makes the picture look more saturated than the Dell's, but it actually looks fine physically, which is okay. But notice how the Cintiq's colour picker doesn't pick a matching colour. It was actually happening the opposite way for a while (Dell was off, Cintiq was fine), but it magically swapped while I was trying to figure out what was going on. Anyone know what's going on, and how I might fix it?
    Thanks for *any* help!
    Semi-related Question regarding Colour Management
    Colour management has always been the elephant-in-the-room for me when I first tried to calibrate my monitors with a Spyder colourimeter years ago. My monitors looked great, but Photoshop's colours became unpredictable and I decided to abandon the idea of calibrating my monitors for years until recently. I decided to give it another chance and follow some tutorials and articles in an attempt to keep my colours consistent across Photoshop and web browsers, at least. I've been proofing against monitor colour  and exporting for web without an attached profile to keep pictures looking good on web browsers. However, pictures exported as such will look horrible when uploaded to Facebook. Uploading pictures with an attached colour profile makes it look good on Facebook. This has forced me to export 2 versions of a picture, one with an attached colour profile and one without, each time I want to share it across different platform. Is there no way to fix this issue?
    Pictures viewed in Windows Photo Viewer are also off-colour, but I think that's because it's not colour managed... but that's a lesser concern.

    I think I've figured out the colour management stuff in the secondary question, but the weird eyedropper issue is still happening. Could just be a quirk from working on things across multiple monitors, but I'm hoping someone might know if this is a bug/artifact.
    Going to lay out what I inferred from my experiments regarding colour management in case other noobs like me run into the same frustrations as I did. Feel free to correct me if I'm wrong - the following are all based on observation.
    General Explanation
    A major source of my problems stem from my erroneous assumption that all browsers will use sRGB when rendering images. Apparently, most popular browsers today are colour-managed, and will use an image's embedded colour profile if it exists, and the monitor's colour profile if it doesn't. This was all well and good before I calibrated my monitors, because the profile attached to them by default were either sRGB or a monitor default that's close to it. While you can never guarantee consistency on other people's monitors, you can catch most cases by embedding a colour profile - even if it is sRGB. This forces colour-managed browsers to use sRGB to render your image, while non-colour-managed browsers will simply default to sRGB. sRGB seems to be the profile used by Windows Photo Viewer too, so images saved in other wider gamut colour spaces will look relatively drab when viewed in WPV versus a colour-managed browser.
    Another key to figuring all this out was understanding how Profile Assignment and Conversion work, and the somewhat-related soft-proofing feature. Under Edit, you are given the option to either assign a colour profile to the image, or convert the image to another colour profile. Converting an image to a colour profile will replace the colour profile and perform colour compensations so that the image will look as physically close to the original as possible. Assigning a profile only replaces the colour profile but performs no compensations. The latter is simulated when soft-proofing (View > Proof Colors or ctrl/cmd-Y). I had followed bad advice and made the mistake of setting up my proofing to Monitor Color because this made images edited in Photoshop look identical when the same image is viewed in the browser, which was rendering my images with the Monitor's colour profile, which in turn stemmed from yet another bad advice I got against embedding profiles .  This should formally answer Lundberg's bewilderment over my mention of soft-proofing against Monitor Colour.
    Conclusion and Typical Workflow (aka TL;DR)
    To begin, these are the settings I use:
    Color Settings: I leave it default at North American General Purpose 2, but probably switch from sRGB to AdobeRGB or  ProPhoto RGB so I can play in a wider gamut.
    Proof Setup: I don't really care about this anymore because I do not soft-proof (ctrl/cmd-Y) in this new workflow.
    Let's assume that I have a bunch of photographs I want to post online. RAWs usually come down in the AdobeRGB colour space - a nice, wide gamut that I'll keep while editing. Once I've made my edits, I save the source PSD to prep for export for web.
    To export to web, I first Convert to the sRGB profile by going to Edit > Convert to Profile. I select sRGB as the destination space, and change the Intent to either Perceptual or Relative Colorimetric, depending on what looks best to me. This will convert the image to the sRGB colour space while trying to keep the colours as close to the original as possible, although some shift may occur to compensate for the narrower gamut. Next, go to Save for Web. The settings you'll use:
    Embed Color Profile CHECKED
    Convert to sRGB UNCHECKED (really doesn't matter since you're already in the sRGB colour space)
    and Preview set to Internet Standard RGB (this is of no consequence - but it will give a preview of what the image will look like in the sRGB space)
    That's it! While there might be a slight shift in colour when you converted from AdobeRGB to sRGB, everything from then on should stay consistent from Photoshop to the browser
    Edit: Of course, if you'd like people to view your photos in glorious wide gamut in their colour-managed browsers, you can skip the conversion to sRGB and keep them in AdobeRGB. When Saving for Web, simply remember to Embed the Color Profile, DO NOT convert to sRGB, and set Preview to "Use Document Profile" to see what the image would look like when drawn with the embedded color profile

  • How to create a front panel display that lights up with different colours depending on its input signal?

    I am doing a project where I have this array which has different voltage outputs for each grid. How do I create a front panel object that lights up with different colours depending on the voltage input or is there already such a pre-built function?
    In addition, I wish to display these in an array on screen. Is there any pre-built function for this?

    Repulse wrote:
    I am doing a project where I have this array which has different voltage outputs for each grid. How do I create a front panel object that lights up with different colours depending on the voltage input or is there already such a pre-built function?
    The simplest way would be an intensity graph. It gives you a 2D grid where each grid point is colored according to the value of a 2D array. The Z axis color ramp determines the color.
    My second choice would be an array of colorboxes. (They could even be made to look like LEDs (see image, if course you can leave them square too), All you need is a scaling function thap maps voltages into a color ramp lookup table with an 8bit index)
    (Using booleans and color property nodes is relatively clumsy. Booleans are meant for two states because the value is boolean. Since array elements can only differ in value, and not in properties, it will not even work. Color boxes have a color data type which is much more appropriate for this case)
    LabVIEW Champion . Do more with less code and in less time .

  • [SCORE] How to give several notes a different color?

    Hello,
    Is it possible to give all notes with a certain pitch a different color in the score window? So let's say all the A# notes are red, and all the others remain black. How can I accomplish this?
    Thanks in advance.

    Hi
    Sure!
    Colours can be assigned in the Staff Style editor, or you can assign by pitch, velocity, voice assignment and the like.
    See
    Score Editor:View:Colours and Layout:Colours.
    For details see p995 and 1257 of the pdf manual.
    To get only 1 note a different colour, you could do it by velocity, or, if that's not helpful, changing the default Pitch Colours.
    HTH
    CCT

  • Different measures use same source column but gives different values in SSAS project

    I've inherited a SSAS project. I'm currentlig gaining knowledge, but do not understand this: There are 4 measures that get data from same source table and column. Example measures:
    [Started]
    [Processing]
    [Processed]
    [Finished]
    All of them gets data from a table (view), and a column "Event_count" with just value 0 in each row. Usage of the measure is "Count of non-empty values".
    Correctly all of these measures gives different values, but I don't understand how since they all go against the same source column. I thougt maybe they were defined in Calculated measures, but nothing there. Where or what else could be affecting this behavior?
    Bonus information (problem): One of the measures is returning blank/empty, which is why started with this research at all.
    Help anyone?
    regards .r

    Hi ,
    I would ask if all the measures are under the same measure group ? It is important to know, since in the dimension usage we are creating relationships between dimensions and measure
    groups .
    Did you try the delete all the calculation's code and leave only the " CALCULATE ; " part ? Do the values change after deploying the slim script ?
    Are all properties the same ? defaults & caching ?
    Regards, David .

  • Forms 6.0-- How can I show records in a block in different colours.

    In a multi record block, how can I show few records in one colour and few more in a different colour depending on a condition.

    Use DISPLAY_ITEM.
    This will change the visual attribute of the item in the current(!) record,
    set_item_property changes the attributes of the item in all(!) records.

  • How can we assign different colours to different records(line items) in alv

    how can we assign different colours to different records(line items) in alv reporting?

    Hi Friend,
    Please see this SDN Wiki  for setting the color in ALV :[http://wiki.sdn.sap.com/wiki/display/ABAP/ABAP-DevelopingInteractiveALVReportusing+OOABAP]
    There are so many SDN Wiki's on this  just try with search  Alv Color display in SDN,
    Regards,

Maybe you are looking for

  • Special Characters formatting in java

    My program is going through files and searches and replaces blah blah, problem is, the files are written in french, therefore there are special characters in the files. and it replaces them all with a ?. how would i make java recognize all these char

  • What is the Exchange 2010 maximum mailbox database size that is support by MS in a single DAG environment?

    My Exchange setup: Exchange 2010 Enterprise 2 mailbox servers 2 CAS, 2 HT 12 mailbox databases. The total of all databases combine is about 2TB. The largest mailbox databases are 530GB, 250GB, and 196GB. Are this over the supported recommendations? b

  • Blank images in Crystal reports

    I'm trying to put image files from a sql server DB (gif format) in a report but they are blank in the report. Any ideas?

  • Using photo browser in Mail

    Friends, When I access the photo browser in Mail to add a photo to an email, the image names that the browser displays are the file names for each image.  I would like it to display the caption that I have applied to each image.  Aperture is my photo

  • From to Dev to QA

    Hello All,              How to go about moving changes from DEV to QA?