JList custom renderer

Hello everybody.
I have a problem with rendering of JList cells. I have a JList-derived class which sets its own ListCellRenderer. The renderer returns an instance of a JPanel derived class, namely GraphicsPanel, which is responsible for drawing a histogram and a number of other things. In order to accomplish this work, the GraphicsPanel instance contains other JPanel-derived objects, one for each "thing", GridBag-laid out. Now the problem is that the paintComponent method never gets called for those objects, but only for the GraphicsPanel instance. The same is true for the getPreferredSize method and others. I tried to use the same GraphicsPanel class outside the JList and it works perfectly.
Inspecting the swing internal fields during every debug session, it comes out that the child components are not valid and their respective sizes are all 0-0. But the GraphicsPanel preferred size is greater than zero, and, when called from outside the JList, also its children sizes become greater than zero, as expected.
Moreover, calling invalidate(), revalidate(), validate(), repaint() in various places and times does not help, and the problem seems to be independent of the OS, because it is present under both Windows and Linux.
I believe I'm missing something amazingly trivial, but what? Any clues?

This may give you some ideasimport java.awt.*;
import javax.swing.*;
public class Test2 extends JFrame {
  MyObject[] data = {new MyObject("One",1),
                     new MyObject("Two",2),
                     new MyObject("Three",3),
                     new MyObject("Four",4),
                     new MyObject("Five",5),
                     new MyObject("Six",6),
                     new MyObject("Seven",7),
                     new MyObject("Eight",8),
                     new MyObject("Nine",9),
  public Test2() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container content = getContentPane();
    JList jl = new JList(data);
    jl.setCellRenderer(new MyRenderer());
    content.add(new JScrollPane(jl), BorderLayout.CENTER);
    setSize(300,300);
  public static void main(String[] args) { new Test2().setVisible(true); }
class MyRenderer extends javax.swing.DefaultListCellRenderer {
  public Component getListCellRendererComponent(JList list, Object value,
                                                int index, boolean selected,
                                                boolean focus) {
    JLabel jl = (JLabel)super.getListCellRendererComponent(list, value,index,
                                                           selected,focus);
    Image i = list.createImage(10,10);
    Graphics g = i.getGraphics();
    g.setColor(Color.red);
    g.fillRect(0,0,10,((MyObject)value).getNum());
    jl.setIcon(new ImageIcon(i));
    return jl;
class MyObject {
  String text; int num;
  public MyObject(String text, int num) { this.text=text; this.num=num; }
  public String toString() { return text; }
  public int getNum() { return num; }
}

Similar Messages

  • Customizing JList Cell Renderer

    Hi all,
    I got a problem with JList not rendering properly in my program. basically I create a customized renderer by extending JPanel and implementing ListCellRenderer.
    but somehow i cannot get the tooltiptext from the JLabel inside my JPanel (the renderer) to display the tooltiptext and responding to my mouse gesture. here's a snippet of my code.
    did i do something wrong?
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    public class TestR {
         private static class ListItem {
              private Color color;
              private String value;
              public ListItem(Color c, String s) {
                   color = c;
                   value = s;
              public Color getColor() {
                   return color;
              public String getValue() {
                   return value;
         private static class MyCellRenderer extends JPanel implements
                   ListCellRenderer {
              private JLabel lbl;
              public MyCellRenderer() {
                   // Don't paint behind the component
                   setOpaque(true);
                   setLayout(new BorderLayout());
                   lbl = new JLabel();
                   add(lbl);
              // Set the attributes of the
              //class and return a reference
              public Component getListCellRendererComponent(JList list, Object value, // value to display
                        int index, // cell index
                        boolean iss, // is selected
                        boolean chf) // cell has focus?
                   // Set the text and
                   //background color for rendering
                   lbl.setText(((ListItem) value).getValue());
                   lbl.setToolTipText("tooltip: "+((ListItem) value).getValue());
                   setBackground(((ListItem) value).getColor());
                   // Set a border if the
                   //list item is selected
                   if (iss) {
                        setBorder(BorderFactory.createLineBorder(Color.blue, 2));
                   } else {
                        setBorder(BorderFactory.createLineBorder(list.getBackground(),
                                  2));
                   return this;
         // Create a window
         public static void main(String args[]) {
              JFrame frame = new JFrame("Custom List Demo");
              frame.addWindowListener(new WindowAdapter() {
                   @Override
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              // Use a list model that
              //allows for updates
              DefaultListModel model = new DefaultListModel();
              JList statusList = new JList(model);
              statusList.setCellRenderer(new MyCellRenderer());
              // Create some dummy list items.
              ListItem li = new ListItem(Color.cyan, "test line one");
              model.addElement(li);
              li = new ListItem(Color.yellow, "foo foo foo");
              model.addElement(li);
              li = new ListItem(Color.green, "quick brown fox");
              model.addElement(li);
              // Display the list   
              JPanel panel = new JPanel();
              panel.add(statusList);
              frame.getContentPane().add("Center", panel);
              frame.pack();
              frame.setVisible(true);
    }

    hi!
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    public class TestR {
         private static class ListItem {
              private Color color;
              private String value;
              public ListItem(Color c, String s) {
                   color = c;
                   value = s;
              public Color getColor() {
                   return color;
              public String getValue() {
                   return value;
         private static class MyCellRenderer extends JPanel implements
                   ListCellRenderer {
              private JLabel lbl;
              public MyCellRenderer() {
                   // Don't paint behind the component
                   setOpaque(true);
                   setLayout(new BorderLayout());
                   lbl = new JLabel();
                   add(lbl);
              // Set the attributes of the
              //class and return a reference
              public Component getListCellRendererComponent(JList list, Object value, // value to display
                        int index, // cell index
                        boolean iss, // is selected
                        boolean chf) // cell has focus?
                   // Set the text and
                   //background color for rendering
                   lbl.setText(((ListItem) value).getValue());
                   /*lbl.*/setToolTipText("tooltip: "+((ListItem) value).getValue());
                   setBackground(((ListItem) value).getColor());
                   // Set a border if the
                   //list item is selected
                   if (iss) {
                        setBorder(BorderFactory.createLineBorder(Color.blue, 2));
                   } else {
                        setBorder(BorderFactory.createLineBorder(list.getBackground(),
                                  2));
                   return this;
         // Create a window
         public static void main(String args[]) {
              JFrame frame = new JFrame("Custom List Demo");
              frame.addWindowListener(new WindowAdapter() {
                   @Override
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              // Use a list model that
              //allows for updates
              DefaultListModel model = new DefaultListModel();
              JList statusList = new JList(model);
              statusList.setCellRenderer(new MyCellRenderer());
              // Create some dummy list items.
              ListItem li = new ListItem(Color.cyan, "test line one");
              model.addElement(li);
              li = new ListItem(Color.yellow, "foo foo foo");
              model.addElement(li);
              li = new ListItem(Color.green, "quick brown fox");
              model.addElement(li);
              // Display the list   
              JPanel panel = new JPanel();
              panel.add(statusList);
              frame.getContentPane().add("Center", panel);
              frame.pack();
              frame.setVisible(true);
    }try this out. this may help you. note at line no 50. /*lbl.*/setToolTipText("tooltip: "+((ListItem) value).getValue());:)
    Aniruddha

  • Custom JList Cell renderer

    Hey guys, i've made a JList put it inside a JScrollPane.
    All working nicely.
    I'm making my own cell renderer, which extends JLabel and implements ListCellRenderer, just the usual
    inside the getList...Component() method, im just adding in a new Icon and adding a border
    And setting the text via the setText method, also using a bit of html to format the text so it sits there nicely.
    It's exactly how i want it, however there's this issue, when i populate alot of items for some reason the JScrollPane isnt like aware of more items and scroll bar isnt made, but u can tell theres more because its cut off at the end.
    Also, when i resize it so the JScrollPanes width is really small, each JList items text is wrapped and causing some of the text to be hidden.
    I want to know how to fix these issues with no horizontal scroll bar etc
    what exactly is the issue?
    Is it because of the custom renderer?
    Thanks for your help guys.

    Is it because of the custom renderer?You tell us!
    Somewhere in your code you have the line:
    list.setCellRenderer(...);
    If you comment out that line does it work correctly? If so then the problem is the renderer and we can't help you solve the problem since we don't know what your code looks like.
    If you need furthre help then you need to post a [url http://www.physci.org/codes/sscce.jsp]Simple Executable Demo Program that shows the problem

  • Custom renderer (almost works)

    I'm creating a custom JComboBox renderer. What I want it to do is display text next to a colored box. Everything works except for the default value were its not showing the text. Anyone see the problem? Or is there a better way of doing this? I’ve included the code below:
    (Renderer Code: ComboBoxRenderer.java)
    import java.awt.*;
    import java.util.ArrayList;
    import javax.swing.*;
    class ComboBoxRenderer extends JLabel implements ListCellRenderer
        String[] _textLabels = {"Red", "Green", "Blue", "Orange", "Yellow", "Cyan"};
        private ArrayList _colors = null;
        private JPanel _coloredBox = null;
        private JPanel _container = null;
        private JLabel _label = null;
        public ComboBoxRenderer()
            setOpaque(true);
            setHorizontalAlignment(CENTER);
            setVerticalAlignment(CENTER);
            // Text container (can't get text to show without it being contained inside another jpanel. Why is this?)
            _container = new JPanel();
            Dimension holderSize = new Dimension(80, 20);
            _container.setLocation(22, 0);
            _container.setSize(holderSize);
            _container.setOpaque(false);
            _container.setLayout(new BorderLayout());
            this.add(_container, BorderLayout.WEST);
            // Text
            _label = new JLabel("Disabled");
            Dimension textSize = new Dimension(80, 20);
            _label.setForeground(Color.black);
            _label.setPreferredSize(textSize);
            _label.setHorizontalAlignment(JTextField.LEFT);
            _container.add(_label, BorderLayout.WEST);
            // Colored box
            _coloredBox = new JPanel();
            Dimension preferredSize = new Dimension(16, 16);
            _coloredBox.setLocation(2, 2);
            _coloredBox.setSize(preferredSize);
            _coloredBox.setOpaque(true);
            this.add(_coloredBox, BorderLayout.WEST);
            // Initialize color list
            _colors = new ArrayList();
            _colors.add(new Color(255, 0, 0));
            _colors.add(new Color(0, 255, 0));
            _colors.add(new Color(0, 0, 255));
            _colors.add(new Color(255, 215, 0));
            _colors.add(new Color(255, 255, 0));
            _colors.add(new Color(0, 255, 255));
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
            // Get the selected index.
            int selectedIndex = ((Integer)value).intValue();
            // Set the background color for each element
            if (isSelected) {
                setBackground(list.getSelectionBackground());
                setForeground(list.getSelectionForeground());
            } else {
                setBackground(list.getBackground());
                setForeground(list.getForeground());
            // Set text
            String text = _textLabels[selectedIndex];
            _label.setText(text);
            _label.setFont(list.getFont());
            // Set box
            Color current = (Color) _colors.get(selectedIndex);
            _coloredBox.setBackground(current);
            return this;
    }(Main: CustomComboBoxDemo.java)
    import java.awt.*;
    import javax.swing.*;
    public class CustomComboBoxDemo extends JPanel
        public CustomComboBoxDemo()
            super(new BorderLayout());
            // Combo list
            Integer[] intArray = new Integer[6];
            for (int i = 0; i < 6; i++) intArray[i] = new Integer(i);
            // Create the combo box.
            JComboBox colorList = new JComboBox(intArray);
            ComboBoxRenderer renderer= new ComboBoxRenderer();
            renderer.setPreferredSize(new Dimension(120, 20));
            colorList.setRenderer(renderer);
            colorList.setMaximumRowCount(5);
            colorList.setSelectedIndex(2);
            // Lay out the demo.
            add(colorList, BorderLayout.PAGE_START);
            setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
        private static void CreateAndShowGUI()
            // Create and set up the window.
            JFrame frame = new JFrame("CustomComboBoxDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            // Create and set up the content pane
            JComponent newContentPane = new CustomComboBoxDemo();
            newContentPane.setOpaque(true);
            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();
    }Edited by: geforce2000 on Dec 13, 2009 3:37 AM
    Edited by: geforce2000 on Dec 13, 2009 3:38 AM

    BeForthrightWhenCrossPostingToOtherSites
    Here's one: [custom-renderer-almost-works|http://www.java-forums.org/awt-swing/23831-custom-renderer-almost-works.html]
    Any others?
    Next issue: TellTheDetails
    You may understand fully just what is not working here, but we don't since you tell us that it doesn't work, but never really tell us how.

  • Changing JList cell renderer on selection

    Hi,
    In our application we need to change the renderer of the selected cell of JList to JTextArea while maintaining default cell renderer for unselected cells. I tried by providing custom cell renderer (code is given below) but it does not work..:-(. Though the component used by JList for rendering the cell is JTextArea, the height of the cell remains same as that of unselected cells. Our requirement is to change the cell height of the selected row so as to give a feel that selected row expands and shows some more information about the selected item to the user.
    Here is the code snippet of the cell renderer that I wrote:
    class CellRenderer1 extends DefaultListCellRenderer{
    private JTextArea selTxtArea;
    CellRenderer1() {
    selTxtArea = new JTextArea(3,20);
    this.setOpaque(true);
    public Component getListCellRendererComponent(JList list,
    Object value, int index,
    boolean isSelected, boolean cellHasFocus) {
    String name = (String) value;
    if ( isSelected ) {
    selTxtArea.setBackground(list.getSelectionBackground());
    selTxtArea.setForeground(list.getSelectionForeground());
    selTxtArea.setText(name + "\n" + name);
    return selTxtArea;
    else {
    this.setBackground(list.getBackground());
    this.setForeground(list.getForeground());
    this.setText(name);
    return this;
    //return this;
    Any pointers or help will be highly appreciated.
    Thanks
    Atul

    JList calculates fixedCellHeight and then uses the same for every cell. This was causing the problem. By overriding the getRowHeight method of BasicListUI class I was able to achieve different cell heights for selected and unselected rows. Following is the code snippet which shows how this was achieved:
    protected int getRowHeight(int row) {
    if ( (cellHeights == null) || (cellHeights.length < row )) {
    cellHeights = new int[row];
    ListModel model = list.getModel();
    Object value = model.getElementAt(row);
    ListSelectionModel selModel = list.getSelectionModel();
    boolean isSelected = selModel.isSelectedIndex(row);
    Component comp = list.getCellRenderer().
    getListCellRendererComponent( list, value, row,
    isSelected, false);
    Dimension dim = comp.getPreferredSize();
    int height = dim.height;
    cellHeights[row] = height;
    return cellHeights[row];
    }

  • Problem with JTree custom renderer when editing

    I have a JTree which uses a custom renderer to display my own icons for different types of nodes. The problem I am having is when I setEditable to true and then attept to edit a node the icon switches back to the default icon, as soon as I am done editing it goes back.
    What I am doing wrong?

    Here is my rendererer
    public class DeviceTreeRenderer extends DefaultTreeCellRenderer implements GuiConstants {
       public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
          JLabel returnValue = (JLabel)super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
          if (value != null) {
             returnValue.setToolTipText(value.toString());
          if (value instanceof Device) {
             returnValue.setIcon(TREE_DEVICE);
             if (!((Device)value).isAlive()) {
                returnValue.setEnabled(false);
          else if (value instanceof GuiPanelGroup) {
             if (expanded) {
                returnValue.setIcon(TREE_PANEL_GROUP_OPEN);
             else {
                returnValue.setIcon(TREE_PANEL_GROUP_CLOSED);
          else if (value instanceof GuiPanel && ((GuiPanel)value).isDirty()) {
             returnValue.setIcon(TREE_PANEL_DIRTY);
          return returnValue;
    }Here is my editor:
    public class WwpJTreeCellEditor extends DefaultTreeCellEditor implements GuiConstants {
          private WwpJTree tree;
           * Creates a new WwpJTreeCellEditor.
           * @param tree The WwpJTree to associate with this editor.
          public WwpJTreeCellEditor(WwpJTree tree) {
             super(tree, (DefaultTreeCellRenderer)tree.getCellRenderer());
             this.tree = tree;
           * Overrides the default isCellEditable so that we check the isEditable() method
           * of the WwpJTreeNodes.
           * @param e An EventObject.
          public boolean isCellEditable(EventObject e) {
             boolean returnValue = super.isCellEditable(e);
             if (returnValue) {
                WwpJTreeNode node = this.tree.getSelectedNode();
                if (node == null || !node.isEditable() || node.isDragging()) {
                   returnValue = false;
             return returnValue;
       }In my JTree I make these calls:
    super.setCellRenderer(new DeviceTreeRenderer());
    super.setCellEditor(new WwpJTreeCellEditor(this));
    super.setEditable(true);

  • Help! Using a custom renderer to display an image

    I have a JTable where I want to set the renderer of one column to a custom renderer. And I want this renderer to show either a play button image, or a stop button image, depending on the status, which is a Boolean value. However, the image won't show up when I run the application. Here's the code from the renderer...
    public class StatusRenderer extends DefaultTableCellRenderer {
    private ImageIcon playIcon = new ImageIcon("C:/play.jpg");
    private ImageIcon stopIcon = new ImageIcon("C:/stop.jpg");
    public StatusRenderer() {
    setHorizontalAlignment(JLabel.CENTER);
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
    Boolean b = (Boolean) value;
    setIcon(b.booleanValue() ? playIcon : stopIcon);
    return this;
    The application runs, but no icon shows up in the table cell. I'd really appreciate any help on this. Thanks.

    look at http://www2.gol.com/users/tame/swing/examples/JTableExamples1.html
    for some great table examples (they may need minor mods to work on 1.3/1.4)
    Basically I think you need something more like:
    public class StatusRenderer extends JLabel
      implements DefaultTableCellRenderer
        public StatusRenderer() {
            super();
            setHorizontalAlignment(JLabel.CENTER);
        public Component getTableCellRendererComponent(JTable table,
                                           Object value, boolean sSelected,
                                           boolean hasFocus, int row,
                                           int col)
            Boolean b = (Boolean) value;
            setIcon(b.booleanValue() ? playIcon : stopIcon);
            return this;
    }Don't forget to add the renderer to the column you want it in !

  • '...' not appearing in obscured table cell when using custom renderer.

    Hello all -
    I am using a custom JPanel as a cell renderer in a JTable to display two icons per cell. Unfortunately, I am running into a problem that occurs when resizing a column such that the width of the column is less than the size of the cell content. Normally, when resizing a cell in this manner, it will start to cut off the text within the cell and add '...' to signify that some material is obscured. However, using my cell renderer, the text simply cuts off with no indication whatsoever there is more content that is being hidden. I have tried looking through the JComponent code to find a function to overload but I haven't had much luck. Does anyone have any suggestions?
    For a simple example, compile and run the following code and try resizing the two columns. You should be able to notice the difference.
    Thanks,
    - Alex
    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 icon1, icon2;
              RendererPanel(Color bg){
                   setLayout(new BoxLayout(this,BoxLayout.LINE_AXIS) );
                   icon1=new JLabel();
                   icon2=new JLabel();
                   add(icon1);
                   add(icon2);
                   setBackground(bg);
              public void setIcons(IconPair value) {
                   icon1.setIcon(value.i1);
                   icon1.setToolTipText("Icon 1");
                   icon2.setIcon(value.i2);
                   icon2.setToolTipText("Icon 2");
                   //uncomment next 2 lines if you want text as well
                   icon1.setText(value.s1);
                   icon2.setText(value.s2);
         class IconPair {
              public Icon i1,i2;
              public String s1,s2;
              IconPair(String s1, String s2){
                   this.i1=(Icon)icons.get(s1);
                   this.i2=(Icon)icons.get(s2);
                   this.s1=s1;
                   this.s2=s2;
         static Map icons = new HashMap();
         public static  void createIcons(){
              Image img = new BufferedImage(10,10, BufferedImage.TYPE_INT_ARGB);
              Graphics2D g2=(Graphics2D)(img.getGraphics());
              g2.setColor(Color.BLUE);
              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.ORANGE);
              g2.drawOval(1,1,8,8);
              icons.put("circle",new ImageIcon(img));
    }

    Things aren't resizable in your layout for the custom renderer. Here's your code working as you want (I think)
    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);
              getContentPane().add(scp);
              setSize(400,100);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              pack();
              setVisible(true);
         class RendererPanel extends JPanel{
              JLabel icon1, icon2;
              RendererPanel(Color bg){
                   setLayout(new BoxLayout(this,BoxLayout.LINE_AXIS) );
                   icon1=new JLabel();
                   icon2=new JLabel();
                   add(icon1);
                   add(icon2);
                   icon1.setMinimumSize(new Dimension(0, 0));
                   icon2.setMinimumSize(new Dimension(0, 0));
                   icon1.setMaximumSize(new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE));
                   icon2.setMaximumSize(new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE));
                   setBackground(bg);
              public void setIcons(IconPair value) {
                   icon1.setIcon(value.i1);
                   icon1.setToolTipText("Icon 1");
                   icon2.setIcon(value.i2);
                   icon2.setToolTipText("Icon 2");
                   //uncomment next 2 lines if you want text as well
                   icon1.setText(value.s1);
                   icon2.setText(value.s2);
         class IconPair {
              public Icon i1,i2;
              public String s1,s2;
              IconPair(String s1, String s2){
                   this.i1=(Icon)icons.get(s1);
                   this.i2=(Icon)icons.get(s2);
                   this.s1=s1;
                   this.s2=s2;
         static Map icons = new HashMap();
         public static  void createIcons(){
              Image img = new BufferedImage(10,10, BufferedImage.TYPE_INT_ARGB);
              Graphics2D g2=(Graphics2D)(img.getGraphics());
              g2.setColor(Color.BLUE);
              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.ORANGE);
              g2.drawOval(1,1,8,8);
              icons.put("circle",new ImageIcon(img));
    }Note that the ... is a function of the JLabel when it is too small to render its text.

  • Adding a custom rendering extension to SQL Server Reporting Services 2012 for SharePoint 2010 integrated mode

    We are attempting to add OfficeWriter report rendering extensions for SSRS 2012 in SharePoint (2010) integrated mode through powershell. The documentation for “New-SPRSExtension” is rather
    sparse and we have not found any clear examples on the internet. With SSRS 2012 in native mode, we make the following two changes to the config files:
    We add the following report rendering extension declaration to
    RSReportServer.config:
    <Configuration>
        <Extensions>
            <Render>
                <Extension Name="XLTemplate" Type="SoftArtisans.OfficeWriter.ReportingServices.ExcelTemplateRenderer,
    SoftArtisans.OfficeWriter.RS2008"/>
                <Extension Name="WordTemplate" Type="SoftArtisans.OfficeWriter.ReportingServices.WordTemplateRenderer,
    SoftArtisans.OfficeWriter.RS2008"/>
            </Render>
        </Extensions>
    </Configuration>
    We add the following security trust codegroup to
    RSSvrPolicy.config:
    <configuration>
        <mscorlib>
            <security>
                <policy>
                    <PolicyLevel version="1">
                  <CodeGroup version="1" PermissionSetName="Nothing">
                    <CodeGroup
                                version="*"
                                PermissionSetName="FullTrust"
                                Name="SoftArtisans_OfficeWriter_Strong_Name"
                                Description="This
    code group grants SoftArtisans OfficeWriter code full trust.">
                              <IMembershipCondition
                                class="StrongNameMembershipCondition"
                                version="*"
                                PublicKeyBlob="00240000048000009400000006020000002400005253413100040000010001004779CB207F11
                                5E86EF9DD3233F9F130F8891911345176650F72330F84CA3F54C96DEB08439680660F02872EEF5DA3955
                                A14C63F96E57DFB71B1535280C37DA2CB5BA37D78A9882414DB11F67FD66DEBC4AD93DD34F4A587D34D
                                B4D23D9C6AF83431D88A7EF42BB01082913F3560DCB50129C5BBA7ECA0DE8BC286DA74F58FADE"/>
                  </CodeGroup>
              </CodeGroup>
           </PolicyLevel>
        </policy>
       </security>
      </mscorlib>
    </configuration>
    What would be the equivalent syntax for “New-SPRSExtension” to do the above for SSRS 2012 in SharePoint (2010) integrated mode?
    Alison Bird SoftArtisans Technical Services www.softartisans.com

    Hi Alison,
    Unlike the deployment of other custom extensions such as custom delivery extension and data processing extension, it is not necessary to add a code group for the custom assembly that grants FullTrust permission for the extension during the deployment of
    custom rendering extension. If you have copy the custom assembly to the %ProgramFiles%\Microsoft SQL Server\MSRS11.<InstanceName>\Reporting Services\ReportServer\Bin folder, and modify the RSreportserver.config file to add the extention entry properly,
    please open the SSRS Service Application created on the SharePoint and verify that your extension is included in the list of available export types for a report.
    Reference:
    Deploying a Rendering Extension
    Regards,
    Mike Yin
    TechNet Community Support

  • Best Practice : Creating Custom Renderer for Standard Component

    I've been reading the docs and a few threads about Custom Renderers. The best practice seems to be to create a Custom Component where you need a Custom Renderer. Is this the case?
    See [this post|http://forums.sun.com/thread.jspa?forumID=427&threadID=520422]
    I've created several Custom Renderers to override the HTML provided by the Standard Components, however I can't see the benefit in also creating a Custom Component when the behaviour of the standard component is just fine.
    Thanks,
    Damian.

    It all depends on what you are trying to accomplish. Generally speaking if all you need is for the user interface output to be changed then a renderer will work just fine. A new component is usually made in order to provide some fundamental change in server side functionality not related to the user interface. - Ponderator

  • Custom rendering extensions not working in SSRS Report Designer (rsreportdesigner.config)

    My custom rendering extension is working in Report Builder (in RSReportServer.config), but not in Report Designer (in RSReportDesigner.config):  instead of adding a "TXT" export option, it's just adding a duplicate "CSV" option.
    SUMMARY: 
    Is there a way to get these features working, with Report Designer?
    DETAILS:
    We are running SSRS (Reporting Services) under SQL Server 2008 R2.
    Here's my rendering section:
        <Render>
          <Extension Name="XML" Type="Microsoft.ReportingServices.Rendering.DataRenderer.XmlDataReport,Microsoft.ReportingServices.DataRendering" />
          <Extension Name="CSV" Type="Microsoft.ReportingServices.Rendering.DataRenderer.CsvReport,Microsoft.ReportingServices.DataRendering" />
          <!-- TXT extension with help from:  http://social.msdn.microsoft.com/Forums/sqlserver/en-US/d79845a8-17fb-4ec6-b121-2c40cf466d73/how-do-i-add-a-pipe-delimited-option-in-ssrs-2008-report-manager?forum=sqlreportingservices -->
          <Extension Name="TXT" Type="Microsoft.ReportingServices.Rendering.DataRenderer.CsvReport,Microsoft.ReportingServices.DataRendering">
            <OverrideNames>
                <Name Language="en-US">TXT(ASCII,NoColHds)</Name>
            </OverrideNames>
            <Configuration>
                 <DeviceInfo>
                     <FileExtension>txt</FileExtension>
                    <FieldDelimiter>,</FieldDelimiter>
                    <Encoding>ASCII</Encoding>
                    <NoHeader>true</NoHeader>
                </DeviceInfo>
            </Configuration>
          </Extension>
          <Extension Name="IMAGE" Type="Microsoft.ReportingServices.Rendering.ImageRenderer.ImageRenderer,Microsoft.ReportingServices.ImageRendering" />
          <Extension Name="PDF" Type="Microsoft.ReportingServices.Rendering.ImageRenderer.PDFRenderer,Microsoft.ReportingServices.ImageRendering" />
          <Extension Name="HTML4.0" Type="Microsoft.ReportingServices.Rendering.HtmlRenderer.Html40RenderingExtension,Microsoft.ReportingServices.HtmlRendering" Visible="false" />
          <Extension Name="MHTML" Type="Microsoft.ReportingServices.Rendering.HtmlRenderer.MHtmlRenderingExtension,Microsoft.ReportingServices.HtmlRendering" />
          <Extension Name="RPL" Type="Microsoft.ReportingServices.Rendering.RPLRendering.RPLRenderer,Microsoft.ReportingServices.RPLRendering" Visible="false" />
          <Extension Name="EXCEL" Type="Microsoft.ReportingServices.Rendering.ExcelRenderer.ExcelRenderer,Microsoft.ReportingServices.ExcelRendering" />
          <Extension Name="WORD" Type="Microsoft.ReportingServices.Rendering.WordRenderer.WordDocumentRenderer,Microsoft.ReportingServices.WordRendering" />
        </Render>
    When I add the above "TXT" section to RSReportServer.config, then Report Builder (and production) both show an export option "TXT(ASCII,NoColHds)". 
    But when I add this "TXT" section to RSReportDesigner.config, and then (in Report Designer / BIDS) attempt to export from a "Preview" of the report, the export drop-down does not show a "CSV" option followed by a "TXT"
    option, but instead shows the "CSV" option twice.
    This simply limits testing of the export option, to Report Builder... or requires any reports be published from Report Designer before they can be tested with
    this export option.
    (FYI, why this export option:  compliance in our industry requires sending data to government agencies, in text files, with fixed-length columns, and ASCII encoding.  Also, we're attempting to give the production of these files to the *users* managing
    communication with those agencies... so we're putting them into SSRS.
    I worked around the fixed length columns (and no delimiters -- no commas), by writing a version of the report where all string columns are padded, and all columns are concatenated, to form ONE LONG COLUMN... but Reporting Services' CSV export format produces
    a Unicode file (UTF-8, which the agency rejected, because it had a leading "", or "EF BB BF" in hex), whereas the agency requires an ASCII file.)

    Hi Doug_atMidway,
    According to your description, you want to enable your custom render extension. Right?
    In Reporting Services, if you want to deploy the custom extension, you just need to add the extension into rsreportserver.config file.  The
    RSReportDesigner.config file stores settings about the rendering extensions available to Report Designer. Since you still use the csv rendering extension in your assembly, we don't need to do any modification in rsreportdesigner.config file. Pleaes
    refer to the links below:
    Thanks for attempting to help, Simon.  
    As my question states, I've *already done* both the above:  changed (1) rsreportserver.config and (2) rsreportdesigner.config.  I added the same code, shown above, to both files.  I did that so I could see the new "txt" extension
    both (1) when exporting in production and Report Builder, and (2) when exporting in Report Designer's "preview".  
    The change in (2) is not working:  I do not see the "TXT" extension in Report Designer, when I try to export from a preview.  Instead, Report Designer shows the CSV extension repeated.
    Thanks for the docs.  I consulted them (well, I consulted the EQUIVALENT pages, for SQL Server 2008 R2), when creating my block of code above.
    Do you see anything to correct, in my code?
    Are the features I'm using actually working, with rsreportdesigner.config?
    Thanks again, 
    -- Doug

  • Custom Renderer

    Hi,
    I've created a custom parser which on taking certain
    binary files parses and inserts them into oracle
    tables.
    So anytime a file is updated on iFS so are the tables.
    Now conversly I want a custom renderer so whenever
    data is updated or inserted into these tables these
    changes will be reflected in the file blob itself.
    The tables can be updated in any of the normal ways,
    manually (SQLPlus), through a JDBC application etc ..
    any suggestions on the best way to do this?
    The only thing that comes to mind is to use
    a Java stored procedure with a trigger placed
    on the tables in question ..
    Thanks for your time,
    Cathal

    Got the info by adding a validator and printing out the Family and renderer values.
    <render-kit>
    <renderer>
    <component-family>javax.faces.SelectOne</component-family>
    <renderer-type>javax.faces.Menu</renderer-type>
    <renderer-class>my.MenuRenderer</renderer-class>
    </renderer>
    </render-kit>
    Fred

  • Custom renderer on standard component

    I try to implement a custom renderer to a standard component (<h:outputText>), but
    my Tomcat failed to start the webcontainer.
    here are my files:
    faces-config.xml
    <render-kit>
    <renderer>
    <renderer-type>MyRenderer</renderer-type>
    <renderer-class>renderkit.MyRenderer</renderer-class>
    </renderer>
    <supported-component-class>
    <component-class>javax.faces.Text</component-class>
    </supported-component-class>
    </render-kit>
    ...renderkit.MyRenderer.java
    package renderkit;
    import java.io.IOException;
    import javax.faces.component.UIComponent;
    import javax.faces.component.UIOutput;
    import javax.faces.context.FacesContext;
    import javax.faces.context.ResponseWriter;
    import javax.faces.render.Renderer;
    public class MyRenderer extends Renderer {
         public void decode(FacesContext context, UIComponent component) {
              System.out.println("decode");
              if ((context == null) || (component == null)) {
                   throw new NullPointerException();
         public void encodeBegin(FacesContext context, UIComponent component)
              throws IOException {
              System.out.println("encodeBegin");
              if ((context == null) || (component == null)) {
                   throw new NullPointerException();
         public void encodeChildren(FacesContext context, UIComponent component)
              throws IOException {
              System.out.println("encodeChildren");
              if ((context == null) || (component == null)) {
                   throw new NullPointerException();
         public void encodeEnd(FacesContext context, UIComponent component)
              throws IOException {
              System.out.println("encodeEnd");
              UIOutput comp = (UIOutput) component;
              ResponseWriter writer = context.getResponseWriter();
              StringBuffer sb = null;
              writer.startElement("<test>", comp);
              writer.write(comp.getValue().toString());
              writer.endElement("</test>");
    }

    <h:outputText> will use a rendererType of "javax.faces.Text"; to use a custom renderer on a standard component, you must not only write a renderer and register it, but also add a custom tag that uses that renderer type. Alternatively, you could use the "binding" attribute to set the renderer type like:
      <h:outputText binding="#{someBean.customText}" .../>
    public class SomeBean
      public SomeBean()
       HtmlOutputText customText = new HtmlOutputText();
        customText.setRendererType("MyRenderer");
        setCustomText(customText);
      public HtmlOutputText getCustomText()
        return _customText;
    public void setCustomText(HtmlOutputText customText)
       _customText = customText;
    private HtmlOutputText _customText;
    }-- Adam Winer (EG member)

  • JTree custom renderer - JScrollPane

    Hi,
    I am building a JTree and need a custom renderer that will allow me to display the contents of certain leaf nodes in a JEditorPane that is contained in a scrollpane as the leaf may contain a varying amount of text.
    I have managed to get a renderer displaying the text as expected however the scrollbars do not work as I hoped - I cannot scroll down the editorpane.
    Has anyone got an example of a renderer that uses a scrollpane, any help/suggestions would be gratefully received.
    Thanks

    Return the size of your editor pane in customized cell renderer's getPreferredSize() method and set JTree rowHeight to zero. When row height is 0, it use renderer's getPreferredSize() to get size of the cell, I think. I have made custom cellrenderer which extends Jpanel and in getCellRendererComponent I add there another panel which contains buttons etc. I have used super.getPreferredSize() in my renderer's getPreferredSize() method.

  • Cell with boolean value not rendering properly in Swing (custom renderer)

    Hello All,
    I have a problem rendenring boolean values when using a custom cell renderer inside a JTable; I managed to reproduce the issue with a dummy application. The application code follows:
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.lang.reflect.InvocationTargetException;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    import java.util.logging.Logger;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.SwingUtilities;
    * Simple GUI that uses custom cell rendering
    * @author josevnz
    public final class SimpleGui extends JFrame {
         private static final long serialVersionUID = 1L;
         private Logger log = Logger.getLogger(SimpleGui.class.getName());
         private JTable simpleTable;
         public SimpleGui() {
              super("Simple GUI");
              setPreferredSize(new Dimension(500, 500));
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setLayout(new BorderLayout());
         public void constructGui() {
              simpleTable = new JTable(new SimpleTableModel());
              simpleTable.getColumnModel().getColumn(2).setCellRenderer(new HasItCellRenderer());
              SpecialCellRenderer specRen = new SpecialCellRenderer(log);
              simpleTable.setDefaultRenderer(Double.class, specRen);
              simpleTable.setDefaultRenderer(String.class, specRen);
              simpleTable.setDefaultRenderer(Date.class, specRen);
              //simpleTable.setDefaultRenderer(Boolean.class, specRen);
              add(new JScrollPane(simpleTable), BorderLayout.CENTER);          
              pack();
              setVisible(true);
         private void populate() {
              List <List<Object>>people = new ArrayList<List<Object>>();
              List <Object>people1 = new ArrayList<Object>();
              people1.add(0, "Jose");
              people1.add(1, 500.333333567);
              people1.add(2, Boolean.TRUE);
              people1.add(3, new Date());
              people.add(people1);
              List <Object>people2 = new ArrayList<Object>();
              people2.add(0, "Yes, you!");
              people2.add(1, 100.522222);
              people2.add(2, Boolean.FALSE);
              people2.add(3, new Date());
              people.add(people2);
              List <Object>people3 = new ArrayList<Object>();
              people3.add(0, "Who, me?");
              people3.add(1, 0.00001);
              people3.add(2, Boolean.TRUE);
              people3.add(3, new Date());
              people.add(people3);
              List <Object>people4 = new ArrayList<Object>();
              people4.add(0, "Peter Parker");
              people4.add(1, 11.567444444);
              people4.add(2, Boolean.FALSE);
              people4.add(3, new Date());
              people.add(people4);
              ((SimpleTableModel) simpleTable.getModel()).addAll(people);
          * @param args
          * @throws InvocationTargetException
          * @throws InterruptedException
         public static void main(String[] args) throws InterruptedException, InvocationTargetException {
              final SimpleGui instance = new SimpleGui();
              SwingUtilities.invokeAndWait(new Runnable() {
                   @Override
                   public void run() {
                        instance.constructGui();
              instance.populate();
    }I decided to write a more specific renderer just for that column:
    import java.awt.Color;
    import java.awt.Component;
    import javax.swing.JTable;
    import javax.swing.UIManager;
    import javax.swing.table.DefaultTableCellRenderer;
    * Cell renderer used only by the DividendElement table
    * @author josevnz
    final class HasItCellRenderer extends DefaultTableCellRenderer {
         protected static final long serialVersionUID = 2596173912618784286L;
         private Color hasIt = new Color(255, 225, 0);
         public HasItCellRenderer() {
              super();
              setOpaque(true);
         @Override
         public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
              Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
              int desCol = table.convertColumnIndexToView(1);
              if (! isSelected && value instanceof Boolean && column == desCol) {
                   if (((Boolean) value).booleanValue()) {
                        comp.setForeground(hasIt);     
                   } else {
                        comp.setForeground(UIManager.getColor("table.foreground"));
              return comp;
          * Override for performance reasons
         @Override
         public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) {
              // EMPTY
         @Override
         protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) {
              // EMPTY
         @Override
         public void revalidate() {
              // EMPTY
         @Override
         public void validate() {
              // EMPTY
    } // end classBut the rendering comes all wrong (a String saying true or false, not the expected checkbox from the default renderer) and also there is a weird flickring effect as this particular boolean column is editable (per table model, not show here)...
    I can post the table model and the other renderer if needed (didn't want to put too much code on the question, at least initiallty).
    Should I render a checkbox myself for this cell in the custom renderer? I'm puzzled as I expected the default renderer part of the code to do this for me instead.
    Thanks!
    Edited by: josevnz on Apr 14, 2009 12:35 PM
    Edited by: josevnz on Apr 14, 2009 12:37 PM

    camickr
    Thats because the default render is a JLabel and it just displays the text from the toString() method of the Object in the table model.What I meant to say is that I expected the JCheckbox not a String representation of the boolean value.
    Thats because a different renderer is used depending on the Class of data in the column. Look at the source code for the JTable class to see what the "default >renderer for the Boolean class" is. Then you can extend that or if its a private class then you will need to copy all the code and customize it.At the end I looked at the code and replicated the functionality I needed. I thought than maybe there was a way to avoid replicating the same logic all over again in order to implement this functionality. Good advice, though.
    see you learned nothing from your last posting. This is NOT a SSCCE. 90% of the code you posted is completely irrelevant for the described problem. There is abosutelly no need to post the custom TableModel, because there is no need to use a custom TableModel for this problem. The TableModel has nothing to do with how a column is rendererd.The custom table model returns the type of the column (giving a hint to the renderer on what to expect, right?) and for the one that had a problem it says than the class is Boolean. That's why I mentioned it:
    public Class getColumnClass(int columnIndex) {
        // Code omited....
    You also posted data for 4 columns worth of data. Again, irrelevant. Your question is about a single column containing Boolean data, so forget about the other columns.
    When creating a SSCCE you don't start with your existing code and "remove" code. You start with a brand new class and only add in what is important. That way hopefully if you made a mistake the first time you don't repeat it the second time.That's what I did, is not the real application. I copy & pasted code in a haste from this dummy program on this forum, not the best approach as it gave the wrong impression.
    Learn how to write a proper SSCCE if you want help in the future. Point taken, but there is NO need for you to be rude. Your help is appreciated.
    Regards,
    Jose.

Maybe you are looking for