Custom Jtree Cell Renderer goes to infinite loopp...any suggestion???
Hey ...thanks for you help before....
Another problem..
My Jtree works fine with default Cell Renderer .. but goes to infinite
loop with CustomDefaultRenderer after few minutes...
Any suggestions....
public DynamicTree() {
super(new GridLayout(1,0));
rootNode = new DefaultMutableTreeNode("POSTINGS & SEARCHES");
treeModel = new DefaultTreeModel(rootNode);
treeModel.addTreeModelListener(new MyTreeModelListener());
tree = new JTree(treeModel);
tree.setEditable(false);
tree.getSelectionModel().setSelectionMode
(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.setShowsRootHandles(true);
// tree.addMouseListener(ml);
// tree.addKeyListener(kl);
JScrollPane scrollPane = new JScrollPane(tree);
add(scrollPane);
// tree.setCellRenderer();
tree.addTreeSelectionListener(new TreeSelectionListener(){
public void valueChanged(TreeSelectionEvent evt){
System.out.println("Tree's lead selection path is " +
tree.getLeadSelectionPath());
tree.setCellRenderer( new CustomDefaultRenderer());
public class CustomDefaultRenderer extends DefaultTreeCellRenderer {
String suffix = null ;
String prefix = null ;
boolean expired = false;
boolean matched = false ;
PostingHandler pHandler = new PostingHandler();
public Component getTreeCellRendererComponent(
JTree tree,
Object value,
boolean sel,
boolean expanded,
boolean leaf,
int row,
boolean hasFocus) {
super.getTreeCellRendererComponent(
tree, value, sel,
expanded, leaf, row,
hasFocus);
suffix = (String)value.toString() ;
try {
prefix = value.toString().substring(0,value.toString().indexOf(":") + 1);
suffix = suffix.substring(suffix.indexOf(":")+1,suffix.length());
System.out.println("Prefix:"+prefix +"\tSufix :"+suffix);
}catch (Exception e){System.out.println("Nothing to index yet" + e);}
// value = (Object)suffix;
if(pHandler.newPostingsMatch.contains(prefix)) {
// if(hasFocus){pHandler.removePostingMatch(prefix);}
setBackgroundNonSelectionColor(Color.CYAN);
}else
setBackgroundNonSelectionColor(Color.WHITE);
System.out.println("Other <>values:\tValue" + value.toString() + "\tSEL:"+sel +"\tExpanded:" + "\tLEAF:"+leaf +
"\tRow:" +row + "\tfocus:"+hasFocus );
return this;
public void paintComponent(Graphics g){
System.out.println("Paint is called");
//g.drawLine(0, 0, 100, 100);
if(expired){
g.drawLine(22, 11, 100,11);
g.drawString(suffix, 22,15);
validate();
repaint();
}
Figured it out right after this post :)
I had to do the following in my cellrenderer
setBackgroundNonSelectionColor(new Color(0, 0, 0, 0));As a parameter I sent a color object with a alpha level of 0 (completly transparent)...
Similar Messages
-
Custom table cell renderer in a JTable is not called
Hello, all,
I have the following task: I need to select several cells in a column, change the value of those cells, and once the value changes, the color of these cells should change as well. I wrote a custom cell renderer, and registered it for the object type that will use it to render the cell. However, the custom cell renderer is never called. Instead, the class name of the object is displayed in the cell.
My code snippents are as follows:
//Declare the table and add custom cell renderer
JTable table = new JTable (7,7);
table.setCellSelectionEnabled (true);
table.setSelectionMode (ListSelectionModel.SINGLE_INTERVAL_SELECTION);
//Add the custom cell renderer to render objects of type Item
table.setDefaultRenderer(Item.class, new CustomTableCellRenderer());
//Get the selected cells and change the object type in those cells
//This part works, since I see the app entering the for loop in the debugger, and the item.toString() value is displayed in each selected cell
int rowIndexStart = table.getSelectedRow();
int rowIndexEnd = table.getSelectionModel().getMaxSelectionIndex();
int colIndex = table.getSelectedColumn();
Item item = new Item ();
for (int i = rowIndexStart; i<=rowIndexEnd; i++){
table.setValueAt(item, i, colIndex);
//I expect the cell to redraw now using custom cell renderer defined below, but that cell render is never called. Instead, the item.toString() value is displayed in the cell. What is wrong?
//Definition of custom cell renderer.
//the getTableCellRendererComponent is never called, since the System.out.println never prints. I expected this method to be called as soon as the Item object is added to the cell. Am I wrong in expecting that?
class CustomTableCellRenderer extends DefaultTableCellRenderer {
public Component getTableCellRendererComponent (JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Component cell = super.getTableCellRendererComponent (table, value, isSelected, hasFocus, row, column);
System.out.println("value: "+value.getClass()+" isSelected "+isSelected+" hasFocus "+hasFocus+" row "+row+" col "+column);
if (this.isFocusOwner()) {
cell.setBackground( Color.red );
cell.setForeground( Color.white );
return cell;
} Please, help,
Thank you!
ElanaThe suggestion given above assumes that all the data in a given column is of the same type.
If you have different types of data in different rows the you should be overriding the getCellRenderer(...) method. Something like:
public TableCellRenderer getCellRenderer(int row, int column)
Object o = getValueAt(row, column);
if (o instanceof Item)
return yourCustomRenderer
else
return super.getCellRenderer(row, column);
} -
JTree cell renderer: how to fill whole row?
hi,
i'm trying to make a tree cell renderer that renders at default height, but fills the horizontal width of the tree (e.g. with a JLabel with a custom background color). I'm working on the theory that in order to do this you need to change the preferred size of the component used to stamp the image at render time.
The problem is that the preferred width then needs to be set to a value that depends on the context of the particular node (e.g. a deeply nested child node will be further to the right than the root node).
I can't seem to find a method to say where the rendering starts though - does anyone know a way?
(also if not then would setting the width to some astronimcal value break anything?)
thanks,
asjfTry this one, it will higlight the background and foreground colors of entire rows.
Oscar
class TableRenderer
extends DefaultTableCellRenderer
implements ListCellRenderer
private boolean focused = true;
private JLabel renderer;
public TableRenderer()
super();
renderer = new JLabel();
renderer.setOpaque(true);
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus)
return renderer;
public Component getTableCellRendererComponent(
JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column)
renderer =
(JLabel) super.getTableCellRendererComponent(
table,
value,
isSelected,
hasFocus,
row,
column);
/* Make the Labels border empty and indented */
setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0));
/* This is used to create alternate row colors */
Color bgColor = Color.white;
if (row % 2 == 0)
bgColor = new Color(237, 243, 254);
/* if the table has focus and the row is selected use these colors */
if (table.hasFocus() && table.getSelectedRow() == row)
table.setSelectionForeground(Color.WHITE);
table.setSelectionBackground(new Color(101, 137, 178));
/* if the table has not the focus but the row is selected use these colors */
else if (
table.hasFocus() == false && table.getSelectedRow() == row)
table.setSelectionBackground(new Color(196, 196, 194));
/* if not use the standard color */
else
renderer.setBackground(bgColor);
table.setSelectionForeground(SystemColor.textText);
if (value instanceof ColorData)
ColorData cvalue = (ColorData) value;
setForeground(cvalue.color);
setText(cvalue.data.toString());
/* Set the Labels value */
setText(String.valueOf(value));
return renderer;
} -
How to make JTree cell renderer respect layout?
Hi,
In the JTree tutorial, the first example TreeDemo shows a simple tree.
http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html
If you grab the frame and make it really thin, you get a horizontal scroll bar in the top pane.
How can I make it so that the tree cells just draw "..." at the end of the string if there is not enough space?
I know the tree cell renderer uses JLabel, but they never seem to show "...", which is one of the best features of a JLabel. Any help is greatly appreciated!Hi,
I got it working, but I also discovered a Java bug that ruins all this effort!
Calculating the node's position & width:
- When child nodes are indented, there is an "L" shaped line drawn... the space to the left of the line's vertical bar is the "leftChildIndent", and the space to the right is the "rightChildIndent". So you add both to get the whole indent.
- I use label.getPreferredSize().width to figure out the node width, since that includes the icon width, the icon-text gap, and the font metrics.
Example program:
- This program models how I want it to look... Always expanded and automatic "..." when the scroll pane is not big enough.
Bug found:
- There is a runnable example below. Just run it and after a couple seconds, move the split pane to the right.
- I use a timer to add a new node every 1 second. The new nodes get stuck being too small, and the original nodes don't have this problem.
// =====================================================
* Adaptation of TreeDemo to allow for tree nodes that show "..."
* when there is not enough space to display the whole label.
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTree;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeWillExpandListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.ExpandVetoException;
import javax.swing.tree.TreeCellRenderer;
import javax.swing.tree.TreeSelectionModel;
public class TreeDemo extends JPanel {
private JTree tree;
protected class EllipsesTreeCellRenderer implements TreeCellRenderer {
Integer leftIndent = (Integer) UIManager.get("Tree.leftChildIndent");
Integer rightIndent = (Integer) UIManager.get("Tree.rightChildIndent");
int indent = leftIndent.intValue() + rightIndent.intValue();
JLabel label = new JLabel();
DefaultTreeCellRenderer r = new DefaultTreeCellRenderer();
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean selected, boolean expanded, boolean leaf, int row,
boolean hasFocus) {
label.setText("why hello there why hello there why hello there");
if (selected) {
label.setForeground(r.getTextSelectionColor());
label.setBackground(r.getBackgroundSelectionColor());
} else {
label.setForeground(r.getTextNonSelectionColor());
label.setBackground(r.getBackgroundNonSelectionColor());
if (leaf) {
label.setIcon(r.getLeafIcon());
} else if (expanded) {
label.setIcon(r.getOpenIcon());
} else {
label.setIcon(r.getClosedIcon());
label.setComponentOrientation(tree.getComponentOrientation());
int labelWidth = label.getPreferredSize().width;
DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
int level = node.getLevel();
if (!tree.isRootVisible()) {
--level;
int indentWidth = indent * level;
int rendererWidth = labelWidth + indentWidth;
// This is zero the first few times getTreeCellRenderer is called
// because the tree is not yet visible.
int maxWidth = (int) tree.getVisibleRect().getWidth();
if (maxWidth > 0) {
if (rendererWidth > maxWidth) {
// figure out how much space "..." will consume.
label.setText(label.getText() + "...");
maxWidth = maxWidth
- (label.getPreferredSize().width - labelWidth);
label.setText(label.getText());
// chop off characters until "..." fits in the visible
// portion.
if (maxWidth > 0) {
while (rendererWidth > maxWidth
&& label.getText().length() > 1) {
label.setText(label.getText().substring(0,
label.getText().length() - 2));
rendererWidth = indentWidth
+ label.getPreferredSize().width;
label.setText(label.getText() + "...");
return label;
public TreeDemo() {
super(new GridLayout(1, 0));
//Create the nodes.
final DefaultMutableTreeNode top = new DefaultMutableTreeNode("");
createNodes(top);
//Create a tree that allows one selection at a time.
tree = new JTree(top);
tree.getSelectionModel().setSelectionMode(
TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.setCellRenderer(new EllipsesTreeCellRenderer());
tree.addTreeWillExpandListener(new TreeWillExpandListener() {
public void treeWillExpand(TreeExpansionEvent event) {
public void treeWillCollapse(TreeExpansionEvent event)
throws ExpandVetoException {
throw new ExpandVetoException(event);
for (int i = tree.getRowCount(); i >= 0; i--) {
tree.expandRow(i);
//Create the scroll pane and add the tree to it.
JScrollPane treeView = new JScrollPane(tree);
//Add the scroll panes to a split pane.
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
splitPane.setTopComponent(treeView);
splitPane.setBottomComponent(new JLabel(""));
Dimension minimumSize = new Dimension(0, 0);
treeView.setMinimumSize(minimumSize);
splitPane.setDividerLocation(200); //XXX: ignored in some releases
//of Swing. bug 4101306
//workaround for bug 4101306:
//treeView.setPreferredSize(new Dimension(100, 100));
// Makes tree nodes appear cut-off initially.
splitPane.setPreferredSize(new Dimension(500, 300));
//Add the split pane to this panel.
add(splitPane);
// Adds a new node every 1 second
Timer timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
DefaultMutableTreeNode child = new DefaultMutableTreeNode("");
model.insertNodeInto(child, top, 0);
for (int i = tree.getRowCount(); i >= 0; i--) {
tree.expandRow(i);
timer.start();
private void createNodes(DefaultMutableTreeNode top) {
DefaultMutableTreeNode category = null;
DefaultMutableTreeNode book = null;
category = new DefaultMutableTreeNode("");
top.add(category);
category.add(new DefaultMutableTreeNode(""));
category.add(new DefaultMutableTreeNode(""));
category.add(new DefaultMutableTreeNode(""));
category.add(new DefaultMutableTreeNode(""));
category.add(new DefaultMutableTreeNode(""));
category.add(new DefaultMutableTreeNode(""));
category.add(new DefaultMutableTreeNode(""));
category.add(new DefaultMutableTreeNode(""));
category.add(new DefaultMutableTreeNode(""));
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
private static void createAndShowGUI() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
System.err.println("Couldn't use system look and feel.");
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create and set up the window.
JFrame frame = new JFrame("TreeDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
TreeDemo newContentPane = new TreeDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
} -
Custom Table Cell Renderer Unable To Set Horizontal Alignment
Hello,
I have a problem that I'm at my wit's end with, and I was hoping for some help.
I need to render the cells in my table differently (alignment, colors, etc) depending on the row AND the column, not just the column. I've got this working just fine, except for changing the cell's horizontal alignment won't work.
I have a CustomCellRenderer that extends DefaultTableCellRenderer and overrides the getTableCellRendererComponent() method, setting the foreground/background colors and horizontal alignment of the cell based on the cell's value.
I have a CustomTable that extends JTable and overrides the getCellRenderer(int row, int column) method to return a private instance of this CustomCellRenderer.
This works fine for foreground/background colors, but my calls to setHorizontalAlignment() in the getTableCellRendererComponent() seem to have no effect, every cell is always displayed LEFT aligned! It's almost like the cell's alignment is determined by something else than the table.getCellRenderer(row,column).getTableCellRendererComponent() method.
I've also tried setting the renderer for every existing TableColumn in the TableModel to this custom renderer, as well as overriding the table's getDefaultColumn() method to return this custom renderer as well for any Class parameter, with no success.
No matter what I've tried, I can customize the cell however I want, EXCEPT for the horizontal alignment!!!
Any ideas???
Here's the core custom classes that I'm using:
class CustomTable extends JTable {
private CustomRenderer customRenderer = new CustomRenderer();
public CustomTable() {
super();
public TableCellRenderer getCellRenderer(int row, int column) {
return customRenderer;
} // end class CustomTable
class CustomRenderer extends DefaultTableCellRenderer {
public CustomRenderer() {
super();
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if (row % 2 == 0) {
setForeground(Color.red);
setHorizontalAlignment(RIGHT);
} else {
setForeground(Color.blue);
setHorizontalAlignment(LEFT);
return this;
} // end class CustomRenderer
Even worse, I've gotten this to work fine in a trivial example I made to try and re-create the problem. But for some reason, this same thing is just not working for horizontal alignment in my actual project?!?
Anyone have any ideas how the cell's horizontal alignment set in the getTableCellRendererComponent() method is being ignored or overwritten before the cell is being displayed???
Thanks, any help is appreciated,
-Alex BlumeOk, so I've looked into their source and I think I know where and what the trouble is. The JTable.java has a method called:
3658> public TableCellRenderer getCellRenderer(int row, int column) {
3659> TableColumn tableColumn = getColumnModel().getColumn(column);
3660> TableCellRenderer renderer = tableColumn.getCellRenderer();
3661> if (renderer == null) {
3662> renderer = getDefaultRenderer(getColumnClass(column));
3663> }
3664> return renderer;
3665> }
starting at line 3658 of their source code. It retrieves the TableCellRenderer on line 3660 by calling the tableColumn's getCellRenderer method. This is found in the TableColumn.java class:
421> public TableCellRenderer getCellRenderer() {
422> return cellRenderer;
423> }
See the problem? Only ONE cell Renderer. It's referring to a variable found at line 140 which is of type TableCellRenderer ... well actually it's created as a DefaultTableCellRenderer at some point since TableCellRenderer is an interface.
Basically the fix is this:
In the TableColumn.java file, a collection (Vector, LinkedList, whatever) needs to keep track of each cell's renderer. This will solve the solution. Of course this will be something that you or I can make.
What's funny is the contradiction in documentation between JTable's and TableColumn's getCellRenderer() method. First, if we look at TableColumn's documentation it states:
"Returns the TableCellRenderer used by the JTable to draw values for this column."
Based on that first statement, the getCellRenderer() method in TableColumn is doing its job exactly. No lies, no contradictions in what it does.
However, that method is called up inside of the JTable's getCellRenderer() method which says a completely different thing which is:
"Returns an appropriate renderer for the cell specified by this row and column."
Now we have a problem. For the cell specified. It appears that the rush to push this out blinded some developer who either:
1) mis-interpreted what the JTable getCellRenderer() method was supposed to do and inadvertently added a feature or;
2) was in a 2 a.m. blitz, wired on Pepsi and adrenalin and wrote the bug in.
Either way, I'm really hoping that they'll fix this because it will take care of at least 2 bugs. Btw, anyone interested in posting a subclass to solve this problem (subclass of TableColumn) is more than welcome. I've spent much too much time on this and my project is already behind so I can't really afford any more time on this.
later,
a. -
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 -
hi. im doing a scheduler application
wherein a list is displayed and when user post
a scheduled activity, a textbox will be painted
on top of the list, so that you could do away with
overlapping schedules(2 or more schedule with
the same time interval/s). Much like as that of
the MS Outlook calendar.
Can anyone post a snippet of the code of the
cell renderer? im having a hard time studying
cell rendering.
thank you very much.Pls i badly nedd your help. somebody knowledgable on this?
-
Customized table cell renderer doesn't work after table data model changed
Hi:
I have a jtable with a custimized table cell render (changes the row color). Everything works fine while the data model is unchanged. I can change the row color, etc. However, after I delete one row or any number of rows in the table, the data model is updated and the custmized table cell renderer is not being called anymore while jtable is rendering on its cells. Seems like the table cell render is no long associated with the jtable. Is this a known problem? Any help would be appreciated.
ThanksI am having the same problem. Has anybody solved this issue?
Thanks -
Customizing JTree data rendering for Dates
I have a JTree that has different data types in each column that I'm sorting. I'd like to be able to control the String that appears in the table cell(s) based on the value in the model. I'm trying to make it so that if a Date is less than some predeterminded Date value that a custom string is output to the Table cell instead of the normal Date string.
I thought a JTable took the toString() of the Date object for its value and that I could just subclass the java.util.Date object and override the toString() with a conditional. such as (toString() in my CustomDate subclass that extends java.util.Date):
public String toString() {
defaultDate = new java.util.Date();
if (defaultDate.getTime()>this.getTime()){
return "Date entered in the past";
} else { //get the normal Date toString
return new String(super.toString());
}I'm not so much asking what is wrong with my code, but how to accomplish this task, the code is simply to show the direction I've taken. Am i close, or way out in left field?
Thanks for any help guys!Zulfi100 needs a BrainCellRenderer.He is strangely disturbing yet amusing at the same time. It worries me that he is going to use the skills he learns here to teach.
-
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 -
Hi can someone help me please??
I've created a JTree with a custom TreeUI which paints the JTree's backround with gradient paint.
The problem i'm having is that i want to make the background color of the treecells transparent, no color at all. In my custom TreeCellRenderer it works fine setting the foreground color and everything, but not the background...
Any clues anyone?Figured it out right after this post :)
I had to do the following in my cellrenderer
setBackgroundNonSelectionColor(new Color(0, 0, 0, 0));As a parameter I sent a color object with a alpha level of 0 (completly transparent)... -
Hi all,
I am trying to set up an option that will allow a user to change the JTree Icon image to their prefered choice, I have a number of different images that changes when I select on the JMenuItem selection, as I am calling the ActionListener to another class called Renderer(), like:
tree.setCellRenderer(new Renderer());
But what I am trying to do is to try to allow the user to select the java default icons, can anybody show me how this is done. Its being annoying me for ages.
thanks allHi all,
I am trying to set up an option that will allow a
user to change the JTree Icon image to their prefered
choice, I have a number of different images that
changes when I select on the JMenuItem selection, as
I am calling the ActionListener to another class
called Renderer(), like:
tree.setCellRenderer(new Renderer());
But what I am trying to do is to try to allow the
user to select the java default icons, can anybody
show me how this is done. Its being annoying me for
ages.
thanks allThis information can be retrieved from the UIDefaults in the UIManager. The keys are:
Tree.closedIcon
Tree.collapsedIcon
Tree.drawsFocusBorderAroundIcon
Tree.expandedIcon
Tree.leafIcon
Tree.openIcon
To retrieve the Icon, something like the following should work:
Icon closedIcon = UIManager.getDefaults().getIcon("Tree.closedIcon");Jim S. -
Selection of Custom JTable cell renderer inconsistenent between LAFs
Sorry if that seems cryptic, but I don't know if I've run into a bug or not. I've recently switched from windows to linux and have noticed a problem with one of my programs. I have a "multiline" renderer that I made for my JTable. The renderer isn't terribly elegant, but when I'd select the row of the table, I made the multi-line renderer change its colors in response to the selection.
This color selection switching works fine under the Metal LAF and the Windows LAF. However, this no longer works in the default look and feel is for linux (GTK+???). My multiline renderer in the JTable won't change its foreground/background in response to selection, but will if I use the Metal LAF under linux.
Any idea what I'm doing wrong? Is this a bug? (I'm fairly certain I'm doing something silly, I just can't see it for the life of me).
Here's the code I use to update the selection:
class MultilineRenderer extends JTextArea
implements TableCellRenderer {
public MultilineRenderer(){
super();
setWrapStyleWord(false);
setLineWrap(true);
setFont(Const.TABLE_FONT);
setOpaque(true);
public Component getTableCellRendererComponent(
JTable table, Object text,
boolean isSelected, boolean hasFocus,
int row, int column) {
String data = (String)text;
setText(data);
if (isSelected){
setForeground(table.getSelectionForeground());;
setBackground(table.getSelectionBackground());
} else {
setForeground(table.getForeground());
setBackground(table.getBackground());
return this;
}Some look and feels will ignore calls to setBackground and setForeground, and will instead decide their own colour.
To quote the API documentation:
"The background color affects each component differently and the parts of the component that are affected by the background color may differ between operating systems."
I would imagine that this is your problem. Annoying, I know! -
All my tree nodes has an icon on the left and text on the right
Just for a node or two, I need to put extra text on the right of the label text but in different color. What's the best way to do that?
Would I have to change my renderer to not inherit DefaultTreeCellRenderer and inherit JPanel with TreeCellRenderer?
Can I do it overwriting a paint function and check for that instance?
Need a little example of doing extra work for a particular node that involves rendering in different colors...
Thanks
Abraham Khalilhave you seen the demo tree renderer code here?
http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html
as long as you have some way of telling when you need to render differently then you can either pass back the default renderer's component (ie call the super classes method) or pass back a privately owned one.
you could either use JLabels support of HTML for rendering the text in a different color, or maintain two instances of a JLabel on a JPanel and use that as the stamp
asjf -
Slow rendering of all pages. Any suggestions?
Hi Folks.
Just after any ideas you may have.
Application Builder and APEX Admin are fine. They render page requests almost instantly.
Front end, however, is now taking a little over a minute to render each and every page. Login 62 seconds, post-login screen 65 seconds, subsequent screens roughly 63 seconds each.
I have had a look at the SYSAUX tablespace where the Flows schemas reside. This is presently using 3025MB of a 3070 allocation. Currently 98.54% used.
I can access the tables using OEM and SQLDeveloper with no delays.
I will, of course, be getting our DBA to have a look on Monday morning but I wondered if, in the meantime, any of you had come across anything like this and what the cause/solution was.
Many thanks
Simon Gadd
Application Express 3.1.2.00.02
Database 10.2.0.3.0Hi,
The trace file will be written to the location identified by the Oracle parameter user_dump_dest. The initialization parameters can be set in the init.ora file. The trace file produced can be converted to a readable format using the tkprof program. Search google for "oracle tkprof" to have examples on how to use it.
But regarding your problem, you can also enable the debug mode. Viewing a page in Debug Mode enables you to track what the APEX engine is doing as it renders a page. You can access Debug mode by clicking the Debug link in the Developer Toolbar. This functionality displays time codes that correspond to specific APEX engine actions. This way you can see where your application is getting long to render.
You can also use f?p syntax to run an application in Debug mode. Simply call the page and set the Debug argument to YES. For example: f?p=100:1:&APP_SESSION.::YES
Paulo Vale
http://apex-notes.blogspot.com
Maybe you are looking for
-
All of a sudden I can no longer watch videos I have rented they will not stream
I have iPad 2 and Have had my apple Tv 2 for about a month. Everything has been working great. Rented movies on the iPad and have watched them thru my Apple TV with no problems. then yesterday I had trouble streaming, the movies will start playing on
-
Hello There, I have written an Outlook Add-In to add several User Properties to our incoming emails. This add-in will be installed in 100 computers in different states and our Exchange server is hosted in our datacenter in CA. Everything works great
-
How to capture the value in buffer
Hi, In VA01, when I change name of ship to party. Want to compare changed with name in ztable. But when I change the name it will be in buffer.So how to do this? Is there any function module to caputure the value in buffer. Please suggest me. Regard
-
Content Aware Fill in Photoshop CS5.5 has quit working
Content Aware Fill in Photoshop CS5.5 has quit. Was working just fine now nothing happens.
-
How To Delete/Uninstall a Program?
A visitor recently downloaded Skype to my Macbook. Now, Skype lauches every time I start up. How can i remove Skype? When I try to drag the desktop icon into the trash, the trash turns into an eject icon. When I try to find Skype in my list of Applic