Drawing String In Different Colors

Hi!
I need to do the following. Using DrawString method, I need to make a special character, each time it appears in string, invisible(but not to remove it from string). So I decided to draw it in a background color(If you know some other way to hide it, please share it with me). But other letters should be in foreground colors. How can I define only that letter in different(background) color?
If you understood my problem, please help me to solve it.

This program will do it :
import java.awt.event.*;  
import java.awt.*;
public class DrawS extends Frame
public DrawS()
     addWindowListener(new WindowAdapter()
    {     public void windowClosing(WindowEvent ev)
          {     dispose();
               System.exit(0);
     setBounds(50,50,450,400);
     setBackground(Color.lightGray);
     setForeground(Color.red);
    setVisible(true);
public void paint(Graphics g)
     super.paint(g);
     String s = "this is a string";
     char   c = 'i';
     g.drawString(s,50,50);
     FontMetrics fm = getFontMetrics(g.getFont());
     int x = 50;
     for (int j=0; j < s.length(); j++)
          if (s.charAt(j) == c) g.setColor(getBackground());
               else              g.setColor(getForeground());
          g.drawString(s.substring(j,j+1),x,100);
          x = x + fm.charWidth(s.charAt(j));
public static void main(String[] args )
     new DrawS();
Noah

Similar Messages

  • Displaying String in two colors.....

    Hello....
    I'm working on chat project. How can i show string in different colors in JTextArea control.
    Hope you understand my question.
    Thanks in advance

    You may use a JTextPane - here is an example:
    import java.awt.Color;
    import javax.swing.JFrame;
    import javax.swing.JTextPane;
    import javax.swing.text.SimpleAttributeSet;
    import javax.swing.text.StyleConstants;
    public class Frame3 extends JFrame {
         public Frame3(){
              super("Frame1");
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              JTextPane field = new JTextPane();
              //field.setContentType("text/html");
              add(field);
              try{
                   SimpleAttributeSet style1 = new SimpleAttributeSet();
                   StyleConstants.setForeground(style1,Color.BLUE);
                   SimpleAttributeSet style2 = new SimpleAttributeSet();
                   StyleConstants.setForeground(style2,Color.RED);    
                   field.getDocument().insertString(0, "first\n",style1);
                   field.getDocument().insertString(0, "second\n",style2);
              catch(Exception exc){
                   exc.printStackTrace();
              setSize(200,200);
         public static void main(String args[]){
              new Frame3().setVisible(true);
    }

  • Draw a string with one character in a different color

    This problem sounds trivially simple, but I don't have a clue on how to implement it.
    What I'm basically trying to do, is use Graphics2D.drawString() to draw a string...but I want one letter to be in a different color. Guessing from the API this could be possible with an AttributedCharacterIterator, but I don't know how to set 'color' as one of the attributes.
    Does anyone with knowledge of Java 2D havy any solution for this?

    keeskist wrote:
    This problem sounds trivially simple, but I don't have a clue on how to implement it.
    What I'm basically trying to do, is use Graphics2D.drawString() to draw a string...but I want one letter to be in a different color. Guessing from the API this could be possible with an AttributedCharacterIterator, but I don't know how to set 'color' as one of the attributes.
    Does anyone with knowledge of Java 2D havy any solution for this?Here's an example using AttributedString/AttributedCharacterIterator:
    import java.awt.*;
    import java.awt.font.TextAttribute;
    import java.text.AttributedString;
    import javax.swing.*;
    public class AttributedCharacterIteratorDemo extends JFrame {
         public AttributedCharacterIteratorDemo() {
              AttributedString as = new AttributedString("Hello, world!");
              as.addAttribute(TextAttribute.FOREGROUND, Color.RED, 2, 3);
              JPanel cp = new ACRPanel(as);
              cp.setPreferredSize(new Dimension(300,300));
              setContentPane(cp);
              setTitle("AttributedCharacterIterator Demo");
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              pack();
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        new AttributedCharacterIteratorDemo().setVisible(true);
         private class ACRPanel extends JPanel {
              private AttributedString as;
              public ACRPanel(AttributedString as) {
                   this.as = as;
              protected void paintComponent(Graphics g) {
                   g.drawString(as.getIterator(), 40,40);
    }

  • How to print different colors of Strings into JEditorpane?

    How to print different colors of Strings into JEditorpane?
    Can any body give me answer ...

    JEditorPane contain HTML. So write your HTML using the color attribute.
    Start by read the the API description of JEditorPane. you will find a link to the Swing tutorial on "Using Text Components" which has working examples of using a JEditorPane. It also has an example of using a JTextPane where you can dynamically change the attributes of individual pieces of text.

  • JTextArea-Using different colors  for the Strings added

    I'm looking for a way to write in a textArea using different colors for the Strings

    use SetForeground(Color newForegroundColor) on the JTextArea class
    good luck
    krishna

  • Different color ROIs

    I've seen this post:
    http://forums.ni.com/ni/board/message?board.id=170&message.id=418659&query.id=2770634#M418659
    But it doesn't really help in what we're trying to do. is there any known way to have multiple ROIs programatically drawn with different colors? I have tried to draw 1, change the color, and then draw another. If I do this using the ROI tools LabVIEW is happy and let's the previous colored ROIs stay on the viewer. If I do it programatically, then when I draw the last ROI it destroys all of the previous ROIs. Is there any way to add a new ROI of a different color without changing the color of (or destroying) the previous ROIs?
    LabVIEW Integration Engineer with experience in LabVIEW Real-Time, LabVIEW FPGA, DAQ, Machine Vision, as well as C/C++. CLAD, working on CLD and CLA.

    Hi Falk,
    Probably an easier way to go would be to use a Combo Box string control on the front panel to select which "group" overlay you want to clear, modify, and redefine. The problem is that ROIs are not primarily intended to be viewed -- they are kind of a behind-the-scenes tool for machine vision, not necessarily intended for viewing by humans. Thus, they normally don't require a certain color to be associated with them. That's why we have the function to create an overlay from the ROI, and the overlay is the part that has color as an input. 
    If you can give some more info about your application and why you need to be changing the ROI, we may be able to come up with a different method that could be more useful for you. Would IMAQ ContstructROI be something that you could use instead? It allows you to draw the ROI right on the image, so if you needed to change the ROI you could clear the current ROI and then construct a new one with IMAQ ConstructROI.
    Regards,
    Daniel H. 
    Customer Education Product Support Engineer
    National Instruments
    Certified LabVIEW Developer

  • Different Colors - ColorModel

    I have a Swing GUI on Windows NT with different colors.
    Then I started the same GUI on Solaris.
    If found out that Java does not use the whole RGB range on solaris - only 256 colors are used.
    The difference is that on Windows the DirectColorModel and on Solaris
    the IndexColorModel is used. (Toolkit.geToolkit.getDefaultToolkit().getColorModel())
    Is there a way to show the whole RGB range on Solaris?
    Thanks in advance,
    Anita

    Test thid code and tell me if you can change the display modes :
    * This test generates a table of all available display modes, enters
    * full-screen mode, if available, and allows you to change the display mode.
    * The application should look fine under each enumerated display mode.
    * On UNIX, only a single display mode should be available, and on Win32,
    * display modes should depend on direct draw availability and the type
    * of graphics card.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    class DisplayModeModel extends DefaultTableModel {
        private DisplayMode[] modes;
        public DisplayModeModel(DisplayMode[] modes) {
            this.modes = modes;
        public DisplayMode getDisplayMode(int r) {
            return modes[r];
        public String getColumnName(int c) {
            return DisplayModeTest.COLUMN_NAMES[c];
        public int getColumnCount() {
            return DisplayModeTest.COLUMN_WIDTHS.length;
        public boolean isCellEditable(int r, int c) {
            return false;
        public int getRowCount() {
            if (modes == null) {
                return 0;
            return modes.length;
        public Object getValueAt(int rowIndex, int colIndex) {
            DisplayMode dm = modes[rowIndex];
            switch (colIndex) {
                case DisplayModeTest.INDEX_WIDTH :
                    return Integer.toString(dm.getWidth());
                case DisplayModeTest.INDEX_HEIGHT :
                    return Integer.toString(dm.getHeight());
                case DisplayModeTest.INDEX_BITDEPTH : {
                    int bitDepth = dm.getBitDepth();
                    String ret;
                    if (bitDepth == DisplayMode.BIT_DEPTH_MULTI) {
                        ret = "Multi";
                    } else {
                        ret = Integer.toString(bitDepth);
                    return ret;
                case DisplayModeTest.INDEX_REFRESHRATE : {
                    int refreshRate = dm.getRefreshRate();
                    String ret;
                    if (refreshRate == DisplayMode.REFRESH_RATE_UNKNOWN) {
                        ret = "Unknown";
                    } else {
                        ret = Integer.toString(refreshRate);
                    return ret;
            throw new ArrayIndexOutOfBoundsException("Invalid column value");
    public class DisplayModeTest extends JFrame implements ActionListener,
        ListSelectionListener {
         public KeyListener kl;
        private boolean waiting = false;
        private GraphicsDevice device;
        private DisplayMode originalDM;
        private JButton exit = new JButton("Exit");
        private JButton changeDM = new JButton("Set Display");
        private JLabel currentDM = new JLabel();
        private JTable dmList = new JTable();
        private JScrollPane dmPane = new JScrollPane(dmList);
        private boolean isFullScreen = false;
        public static final int INDEX_WIDTH = 0;
        public static final int INDEX_HEIGHT = 1;
        public static final int INDEX_BITDEPTH = 2;
        public static final int INDEX_REFRESHRATE = 3;
        public static final int[] COLUMN_WIDTHS = new int[] {100, 100, 100, 100 };
        public static final String[] COLUMN_NAMES = new String[] {"Width", "Height", "Bit Depth", "Refresh Rate"};
        public DisplayModeTest(GraphicsDevice device) {
            super(device.getDefaultConfiguration());
            this.device = device;
            setTitle("Display Mode Test");
            originalDM = device.getDisplayMode();
            setDMLabel(originalDM);
            setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
            // Make sure a DM is always selected in the list
            exit.addActionListener(this);
            changeDM.addActionListener(this);
            changeDM.setEnabled(device.isDisplayChangeSupported());
            setUndecorated(true);
              addWindowListener(new WindowAdapter() {
                   public void windowActivated(WindowEvent e) {
                        changeScreen(true);
                   public void windowDeactivated(WindowEvent e) {
                        changeScreen(false);
        public void actionPerformed(ActionEvent ev) {
            Object source = ev.getSource();
            if (source == exit) {
                device.setDisplayMode(originalDM);
                System.exit(0);
              else { // if (source == changeDM)
                int index = dmList.getSelectionModel().getAnchorSelectionIndex();
                if (index >= 0) {
                    DisplayModeModel model = (DisplayModeModel)dmList.getModel();
                    DisplayMode dm = model.getDisplayMode(index);
                    device.setDisplayMode(dm);
                    setDMLabel(dm);
                    setSize(new Dimension(dm.getWidth(), dm.getHeight()));
                    validate();
        public void valueChanged(ListSelectionEvent ev) {
            changeDM.setEnabled(device.isDisplayChangeSupported());
        private void initComponents(Container c) {
            setContentPane(c);
            c.setLayout(new BorderLayout());
            // Current DM
            JPanel currentPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
            c.add(currentPanel, BorderLayout.NORTH);
            JLabel current = new JLabel("Current Display Mode : ");
            currentPanel.add(current);
            currentPanel.add(currentDM);
            // Display Modes
            JPanel modesPanel = new JPanel(new GridLayout(1, 2));
            c.add(modesPanel, BorderLayout.CENTER);
            // List of display modes
            for (int i = 0; i < COLUMN_WIDTHS.length; i++) {
                TableColumn col = new TableColumn(i, COLUMN_WIDTHS);
    col.setIdentifier(COLUMN_NAMES[i]);
    col.setHeaderValue(COLUMN_NAMES[i]);
    dmList.addColumn(col);
    dmList.getSelectionModel().setSelectionMode(
    ListSelectionModel.SINGLE_SELECTION);
    dmList.getSelectionModel().addListSelectionListener(this);
    modesPanel.add(dmPane);
    // Controls
    JPanel controlsPanelA = new JPanel(new BorderLayout());
    modesPanel.add(controlsPanelA);
    JPanel controlsPanelB = new JPanel(new GridLayout(2, 1));
    controlsPanelA.add(controlsPanelB, BorderLayout.NORTH);
    // Exit
    JPanel exitPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
    controlsPanelB.add(exitPanel);
    exitPanel.add(exit);
    // Change DM
    JPanel changeDMPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
    controlsPanelB.add(changeDMPanel);
    changeDMPanel.add(changeDM);
    controlsPanelA.add(new JPanel(), BorderLayout.CENTER);
    public void setVisible(boolean isVis) {
    super.setVisible(isVis);
    if (isVis) {
    dmList.setModel(new DisplayModeModel(device.getDisplayModes()));
    public void setDMLabel(DisplayMode newMode) {
    int bitDepth = newMode.getBitDepth();
    int refreshRate = newMode.getRefreshRate();
    String bd, rr;
    if (bitDepth == DisplayMode.BIT_DEPTH_MULTI) {
    bd = "Multi";
    } else {
    bd = Integer.toString(bitDepth);
    if (refreshRate == DisplayMode.REFRESH_RATE_UNKNOWN) {
    rr = "Unknown";
    } else {
    rr = Integer.toString(refreshRate);
    currentDM.setText(
    COLUMN_NAMES[INDEX_WIDTH] + ": " + newMode.getWidth() + " "
    + COLUMN_NAMES[INDEX_HEIGHT] + ": " + newMode.getHeight() + " "
    + COLUMN_NAMES[INDEX_BITDEPTH] + ": " + bd + " "
    + COLUMN_NAMES[INDEX_REFRESHRATE] + ": " + rr
    public void begin() {
    isFullScreen = device.isFullScreenSupported();
    // setUndecorated(isFullScreen);
    // setResizable(!isFullScreen);
    if (isFullScreen) {
    // Full-screen mode
    device.setFullScreenWindow(this);
    validate();
    } else {
    // Windowed mode
    pack();
    setVisible(true);
    public void changeScreen(boolean full) {
    if (full) {
    // Full-screen mode
                   setResizable(!full);
    device.setFullScreenWindow(this);
    validate();
    } else {
    // Windowed mode
    device.setFullScreenWindow(null);
    // setUndecorated(full);
    /* setResizable(!full);
    pack();*/
    public static void main(String[] args) {
              try {
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              catch (Exception ex) {
                   System.out.println(ex);
    GraphicsEnvironment env = GraphicsEnvironment.
    getLocalGraphicsEnvironment();
    GraphicsDevice[] devices = env.getScreenDevices();
    // REMIND : Multi-monitor full-screen mode not yet supported
    for (int i = 0; i < 1 /*devices.length */; i++) {
    DisplayModeTest test = new DisplayModeTest(devices[i]);
    test.initComponents(test.getContentPane());
    test.setVisible(true);
    // test.begin();
              //     test.changeScreen(false);
    Denis

  • How to set different color for items in selectManyCheckbox

    hi,
    I would like to change item text background color for each item on selectManyCheckbox (different for each item).
    It is only 5 items so that could be static reference or select.
    I know only how to change background for all items
    af|selectManyCheckbox::item-text {
        background:orange;
    How to select concrete item text and change color for only them?
    I found similar problem:
    css - Set background color of every individual checkbox of p:selectManyCheckbox - Stack Overflow
    but this dont work for me because I dont have in adf tr structure
    I need somethink like this:
    af|selectManyCheckbox::item-text XXXX - select here one of the item by number on list or id  {
        background:orange;

    hi,
    thanks Alejandro and Federico for answers.
    I use JDev 11.1.1.6. I dont write it in previously post because I think that is a more css then adf problem.
    I have 5 selectItem based on simple List<String> {"text1", "text2", "text3", "text4". "text5"}:
    <af:selectManyCheckbox label="List" id="smc2"
                                               layout="horizontal"
                                               value="#{bean.listInBean}"
                                               autoSubmit="true">
                          <af:selectItem label="text1" value="text1" id="si47"/>
                          <af:selectItem label="text2" value="text2" id="si43"/>
                          <af:selectItem label="text3" value="text3" id="si46"/>
                          <af:selectItem label="text4" value="text4" id="si45"/>
                          <af:selectItem label="text5" value="text5" id="si44"/>
                        </af:selectManyCheckbox>
    and I would like to color first selectItem text to orange, second to red.. etc, The list is a static list. Not would be changed.
    After Alejandro answer I build simple for each element (anyCollection contains item with two fields: textValue and label {(text1,text1), (text2,text2)...}
      <af:forEach items="#{bean.anyCollection}"
                                      var="item">
                            <af:selectItem id="si48" value="#{item.textValue}"  styleClass="yourClassName#{var.index}"
                                           label="#{item.label}"/>
                          </af:forEach>
    And now if I have my var called "item" I can write 5 css style classe yourClassName#{var.index} with different color, but there is a problem:
    Attribute styleClass is not defined for af:selectItem
    If it will be so simple I will just add 5 style classes for each selectItem
    <af:selectItem label="text1" value="text1" id="si47" styleClass="yourClassName0"/>
    <af:selectItem label="text2" value="text2" id="si43" styleClass="yourClassName1"/>
    Should I use other component then adf facer rich?

  • Changing the text in each dataGrid row to a different color

    Okay I am going to try and be as clear as possible with this,
    so bare with me.
    What I am trying to do is make it so that when my
    arraycollection objects that I have retrieved from a web service
    are loaded in (by using the "dataProvider" attribute) my dataGrid
    that some sort of code will take place changing the color of each
    line of text (all the objects stored in the array collection are
    string types) and display each rows text in a different color.
    Now after looking into it, it seems the only way to alter the
    color of the text is to use some sort of style or format but it
    seems it only effects text in a "textArea, textField, textInput"
    etc... SOOO I figured why not create a itemRenderer that contains
    one of those and put it into the dataGrid... Which I did and still
    can't figure out a way to make it so you can dynamically alter the
    color based on a set of rbg values stored in a array the same size
    as the rowCount of the datagrid.
    so I am rather stumpped in what to do.. I DON'T want to
    change the background color of each row, so alternatingItemColor is
    out of the question, I just want the text displayed in each row to
    be a different color.... And I want all this color changing to
    happen either before the data is inputted into the dataGrid
    (manipulating the arraycollection some how..) or when its all
    already in there, it all needs to happen in code no user
    interaction.
    I was thinking perhaps maybe I could create a item Renderer
    object that contains the compenent (the textArea in it) and just
    make a array of item Renderer objects and pass those into the
    dataGrid, but I don't think that is possible.
    ANY IDEAS AT ALL!! On how to change the color of the text in
    each row of the datagrid to a different color would be a HUGE,
    HUGE!!! help. Or any info on how to setup a datagrid listener that
    listens for when a object (a row) from the arraycollection is added
    to the datagrid... Perhaps I could use that info some how to my
    advantage.
    email me, if you like I don't care I just need a answer to
    this its driving me crazy! I can change the background row color
    based on a array of rgb values but I can't change the color of the
    item in that row based on array of rgb values, ARG!
    [email protected]
    thanx in advanced.

    <mx:itemRenderer>
    <mx:Component>
    <mx:Label color = "red" />
    </mx:Component>
    </mx:itemRenderer>
    want to make it so I can change the color of the label on the
    dynamically by calling some sort of method I have created.. is that
    possible? if so coudl you please give a example, thanx!

  • Compare two string in different line in textarea

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TextCounterPanel extends JPanel {
    private JTextArea textInput;
    private JLabel lineCountLabel;
                        public TextCounterPanel() {
                        setBackground(Color.DARK_GRAY);
                        textInput = new JTextArea();
                        textInput.setBackground(Color.WHITE);
                        JPanel south = new JPanel();
                        south.setBackground(Color.DARK_GRAY);
                        south.setLayout( new GridLayout(4,1,2,2) );
                             JButton countButton = new JButton("Process the Text");
                             countButton.addActionListener( new ActionListener() {
                                  public void actionPerformed(ActionEvent evt) {
                                       processInput();
                             south.add(countButton);
                        lineCountLabel = new JLabel(" Number of lines:");
                        lineCountLabel.setBackground(Color.WHITE);
                        lineCountLabel.setForeground(Color.BLUE);
                        lineCountLabel.setOpaque(true);
                        south.add(lineCountLabel);
                        setLayout( new BorderLayout(2,2) );
                        setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY));
                        JScrollPane scroller = new JScrollPane( textInput );
                        add(scroller, BorderLayout.CENTER);
                        add(south, BorderLayout.SOUTH);
    public void processInput() {
    String text,vin; // The user's input from the text area.
    text = textInput.getText();
    vin =text.substring(25,42);
    lineCountLabel.setText(" vin: " + vin);
    } // end class TextCounterPanel
    How can I compare two string in different line in text area

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TextCounterPanel extends JPanel {
    private JTextArea textInput;
    private JLabel lineCountLabel;
    public TextCounterPanel() {
    setBackground(Color.DARK_GRAY);
    textInput = new JTextArea();
    textInput.setBackground(Color.WHITE);
    JPanel south = new JPanel();
    south.setBackground(Color.DARK_GRAY);
    south.setLayout( new GridLayout(4,1,2,2) );
    JButton countButton = new JButton("Process the Text");
    countButton.addActionListener( new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
    processInput();
    south.add(countButton);
    lineCountLabel = new JLabel(" Number of lines:");
    lineCountLabel.setBackground(Color.WHITE);
    lineCountLabel.setForeground(Color.BLUE);
    lineCountLabel.setOpaque(true);
    south.add(lineCountLabel);
    setLayout( new BorderLayout(2,2) );
    setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY));
    JScrollPane scroller = new JScrollPane( textInput );
    add(scroller, BorderLayout.CENTER);
    add(south, BorderLayout.SOUTH);
    public void processInput() {
    String text,vin; // The user's input from the text area.
    text = textInput.getText();
    vin =text.substring(25,42);
    lineCountLabel.setText(" vin: " + vin);
    } // end class TextCounterPanel

  • A quick way to set different color for certain items in JList?

    is there a quick way of setting different color for certain items in JList?

    Either use HTML strings as the values in your JList (quickest, but may not be the most convenient, especially if your model isn't just text), or create your own ListCellRenderer (e.g. extend DefaultListCellRenderer).
    There is no such thing as "list.setItemForeground(int index, Color c)". You'll have to use one of the methods above.

  • How to set different color text in JTabe cell

    Hi
    I have been searching many forums to find how can this be done, but no success.
    I have Custom JTable with MyTableRenderer which is nothing else but alternate the color of rows(cells), CustomTableModel extends DefaultTableModel adding functionality for updateCellContent with different messages.
    I have a column in which cells i want to set these messages in different color.They are not set by user's editing, and by updating the content using the table model.
    Here is the code for that
    public void updateCellContent(HashMap<String, String> messages, int col) {
            for (int row = 0; row < this.dataVector.size() - 1; row++) {
                //This value is hardcoded for now.
                boolean isError = true;
                String filename = getFilename(row);
                String message = messages.get(filename);
                if (message != null) {
                    if (isError) {
                        setErrorMessage(message, row);
                    } else {
                        setMessage(message, row);
        private void setErrorMessage(String message, int row) {
            this.setFileStatus(message, row);
        private void setMessage(String message, int row) {
            String value = (String) this.getValueAt(row, COL_FILE_STATUS);
            ((Vector) this.dataVector.get(row)).setElementAt(value + " " + message, COL_FILE_STATUS);
            fireTableCellUpdated(row, COL_FILE_STATUS);
    public void setFileStatus(String message, int row) {
            setValueAt(message, row, COL_FILE_STATUS);
        }Thanks
    Dimitar

    I have Custom JTable with MyTableRenderer which is nothing else but alternate the color of rows(cells)If I understand you correctly a better way to do this is to override the prepareRenderer(...) method of JTable. You can search the forum for my "Table Prepare Renderer" (without the spaces) example which shows how this can be done.
    I have a column in which cells i want to set these messages in different color.Then you need to use a custom renderer for that column.
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.

  • Ho to set different color to different Jtree Nodes

    hi,
    In a JTree I need to remark with a different color the leaves that bring
    different categories of information.
    I wrote this function to achieve this purpose:
    private void assignRenderToTrees(JTree jTree, String category) {
             // a different color depending from the category
            Color color = null;
            String ssttrr = category.substring(0, 1);
            if (ssttrr.compareTo("*") == 0) {
                color = Color.YELLOW;
             if (ssttrr.compareTo("^") == 0) {
                color = Color.BLUE;
            // the same icon to all nodes
            String pathXopen = "resources_toShowMouth/oneToothGoodMod.gif";
            URL imgURLXopen = MedidentStart.class.getResource(pathXclose);
            ImageIcon iconXopen = new ImageIcon(imgURLXopen);
            if (iconXopen != null) {
                DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
                renderer.setLeafIcon(null);
                renderer.setClosedIcon(iconXclose);
                renderer.setOpenIcon(iconXopen);
                renderer.setBackgroundNonSelectionColor(color);
                jTree.setCellRenderer(renderer);
            } else {
                System.err.println("Leaf icon missing; using default.");
        } // assignIconsToTree()But in this way, I don't get the selection for the leaf, depending for the category.
    Instead I get all the nodes with the same color.
    I can believe that this happen because I am getting the nodes of all the tree,
    instead the single nodes..., but I am not able to select a single node to
    assign the color...
    I would have an help to do it..
    thank you
    regards
    tonyMrsangelo.

    hi,
    thank you for your kind answer.
    You are right..., JTree are a large framework that I don't know very good.
    ..So often I try to arrange a solution witouth to know good the environment where I am working ...
    This is the reason I changed the approch to the problem in the different time when I posted my ask.
    At any rate now I reproduced the problem selecting a part of my program.
    To use tree.setCellRenderer(renderer) is I found in an example that I was not
    able to reproduce.
    I hope to know what is wrong in the code I posted...
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import javax.swing.tree.DefaultTreeModel;
    public class SSCCE_ForPeriodontalCharting extends JFrame {
        PanelArcSupSx panelArcSupSx;//
        public SSCCE_ForPeriodontalCharting() {
            panelArcSupSx = new PanelArcSupSx();
            add(panelArcSupSx);
            setSize(900, 300);
            setVisible(true);
            this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        public static void main(String[] args) {
            SSCCE_ForPeriodontalCharting xxx = new SSCCE_ForPeriodontalCharting();
    } // class SSCCE_ForPeriodontalCharting
    class PanelArcSupSx extends JPanel {
        JScrollPane jScrollPane[];
        JTree jTreeForArcSS[];
        DefaultMutableTreeNode[] rootNodeArcSS;
        Dimension dimPrefSemiArcPanels = new Dimension(850, 140);
        Dimension treePrefDim = new Dimension(100, 110);
        Dimension dimMinSemiArcPanels = new Dimension(650, 90);
        String[] treesContents = {        "* aaaaa - 2",     "* bbbbb - 2",
            "^ ccccc - 2",    "ddddd - 3",     "* eeeee - 2",
            "fffff - 6",    "* ggggg - 6",     "* hhhhh - 5",
            "* iiiii - 5",   "* kkkkkkk - 1",   "^ llllll - 5",
            "^ mmmmmmm - 2",   "nnnnnnn - 4",    "^ oooooo - 4",
            "* pppppppp - 4"};
        public PanelArcSupSx() { // costruttore
            this.setMinimumSize(dimMinSemiArcPanels);
            this.setPreferredSize(dimPrefSemiArcPanels);
            setLayout(new FlowLayout());
            jScrollPane = new JScrollPane[8];
            jTreeForArcSS = new JTree[8];
            rootNodeArcSS = new DefaultMutableTreeNode[8];
            // arc sup Sx
            for (int i = 0; i < 8; i++) {
                rootNodeArcSS[i] = new DefaultMutableTreeNode("    " + i);
                jTreeForArcSS[i] = new JTree(rootNodeArcSS); // create le 8 roots
    // assignIconsToRootInTheTree(jTreeForArcSS[i]);
    jScrollPane[i] = new JScrollPane();
    jScrollPane[i].setViewportView(jTreeForArcSS[i]); // mette il nodo nel Viewport
    add(jScrollPane[i]); // mette il Viewport nel pannello
    jScrollPane[i].setPreferredSize(treePrefDim);
    // attiva gli ascoltatori ....
    jTreeForArcSS[i].addTreeSelectionListener(new TreeSelectionListener() {
    public void valueChanged(TreeSelectionEvent e) {
    activateDialogXshowTreatments();
    } // for
    fillTrees();
    expandTrees();
    } // costruttore
    private void fillTrees() {
    for (int i = 0; i < treesContents.length; i++) {
    String strNmbr = treesContents[i].substring(treesContents[i].length()-1, treesContents[i].length());
    int nmbr = Integer.parseInt(strNmbr);
    addToothNodeForArcSupSx(nmbr, treesContents[i]);
    private void expandTrees(){
    for (int i = 0; i < 8; i++) {
    jTreeForArcSS[i].expandRow(0);
    * @param toothNmbr
    * @param strTreatment
    private void addToothNodeForArcSupSx(int toothNmbr, String strTreatment) {
    DefaultMutableTreeNode newChild = new DefaultMutableTreeNode(strTreatment); // nuovo treatment da inserire
    DefaultTreeModel model = (DefaultTreeModel) jTreeForArcSS[toothNmbr].getModel();
    DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) model.getRoot();
    model.insertNodeInto(newChild, parentNode, 0); // 0 = assegnamo sempre come primo nodo
    assignColorToLeafInTheTree(model);
    } // assingTreatmentToTooth()
    private void assignColorToLeafInTheTree(DefaultTreeModel model) {
    MyCustomizedRendererForJTree renderer = new MyCustomizedRendererForJTree();
    JTree tree = new JTree(model);
    tree.setCellRenderer(renderer);
    } // assignIconsToLeafInTheTree()
    private void activateDialogXshowTreatments() {
    // do anithing
    private void assignIconsToRootInTheTree(JTree jTree) {
    // do nothing now
    } // assignIconsToTree()
    } // class PanelArcSupSx
    class MyCustomizedRendererForJTree extends DefaultTreeCellRenderer {
    @Override
    public Component getTreeCellRendererComponent(
    JTree tree,
    Object value,
    boolean sel,
    boolean expanded,
    boolean leaf,
    int row,
    boolean hasFocus) { // costruttore
    super.getTreeCellRendererComponent(
    tree, value, sel,
    expanded, leaf, row,
    hasFocus);
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
    // String value = (String) val;
    String text = (String) node.getUserObject();
    String prefix = text.substring(0, 1);
    System.out.println("------------------ text = " + text + " prefix = " + prefix);
    // per quanto riguarda il colore ....
    if (prefix.compareTo("*") == 0) {
    setForeground(Color.YELLOW);
    setBackground(Color.YELLOW);
    // System.out.println("colore da usare giallo ");
    } else if (prefix.compareTo("^") == 0) {
    setForeground(Color.BLUE);
    setBackground(Color.BLUE);
    // System.out.println("colore da usare blu ");
    } else {
    setForeground(Color.BLACK);
    setBackground(Color.BLACK);
    // System.out.println("colore da usare bianco ");
    return this;
    } // costruttore

  • Is it possible to set a different color to part of a cell?

    Hi all,
    I am have trouble setting cell-specific Renderer.
    I have followed the instructions in the UISwing tutorial
    and extended JTable definition to overload getCellRenderer()
    to return myRenderer
    final JTable tableView = new JTable(dataModel){
    public TableCellRenderer getCellRenderer(int row, int column) {
    TableCellRenderer colorRenderer = new ColorRenderer();
    return(colorRenderer);
    My class definition for ColorRenderer is as follows:
    class ColorRenderer extends JLabel implements TableCellRenderer {
    public ColorRenderer() {
    public Component getTableCellRendererComponent(
    JTable table, Object color,
    boolean isSelected, boolean hasFocus,
    int row, int column) {
    setForeground(Color.blue);
    return this;
    Is it possible to set a different color to part of a cell?
    eg. I have "TEST,CELL,COLOR" as a string in a cell.
    Can I set a different color to the substring "CELL"?
    Your suggestions will be accepted most gratefully!
    Thanks in advance
    -Kalpana

    You should inherit your table cell renderer from a container, for example JPanel, add different JLabels to the panel and color them separately.
    Kurta

  • How to show the contents of a dropdown list with different colors

    Hi,
    I have a drop downlist on my dialog. I want to show each of its text attribute and its back ground with different color.
    Suppose I am showing 4 strings in the dropdown like Name1, Name2, Name3 and Name4, then how to change the color of each name and its background.
    Please let me know if it is possible.

    If the above asked is not possibe can we have an alternative as mentioned below :-
    A dropdown similar to the one shown in "Edit->Preferences->Grids->Colors" having our own text names instead of the default color names.
    So that I can show some color symbol and a text name along with it in my dropdown.
    One more query, is it possible to show the images/giff/png files in dropdown ?

Maybe you are looking for

  • DMS Data Migration-Help required

    Hi, I don't have enough knowledge on DMS Data migration. In our recent Implementation, we are implementing SAP DMS. Our client has more legacy data which is in their server. So we have to upload all the data's into SAP DMS. I gone through few SCN thr

  • Is the iPhone release simple by design??

    Is iPhone Intentionally simple to start with? I was thinking about this a lot lately. There are so many things, simple things, obvious things, missing from iPhone on its release that I cant help thinking its more of a strategy then lack of foresight

  • Displaying picture

    Hello to everybody! I need little help. Let me describe you a problem. I've created one table CREATE TABLE "FILMOVI" (     "SIF_FILM" NUMBER,      "NAZIV_FILM" VARCHAR2(50),      "DATUM_IZLASKA" DATE,      "MOVIE_IMAGE" BLOB,      "MIMETYPE" VARCHAR2

  • Publishing to facebook

    I am trying to get the connection set up with facebook and have allowed lightroom to publish there. Back in lightroom the publishing manager is then telling me it is authorizing and that is were it stays and hangs fore ever. In my face book app accou

  • Can't view most folders in icon view, it just crashes.

    When I try to do icon view in most folders, finder freezes and restarts. But the strange thing is that icon view works in most sections of my home folder. http://www.youtube.com/watch?v=DjyHbiO_cY4