Swing Icons
Hello,
in the book Java Look and Feel Design Guidelines, there's an iconset (page 19 and next) with icons representing jfc components.
Are those icons available somewhere ? I developp an gui "wysiwyg" builder and want to use them.
Thanks
Is it what you're looking for ?
http://java.sun.com/developer/techDocs/hi/repository/
Similar Messages
-
Hi,
I'm doing a sort of a progress dialog showing the phases progress to the user.
Are there any standard icons/images in Swing?
in particular, I'm looking for images that show:
"Done" - might be something like a checked CheckBox
"Error" - Something like a red "X" image
"Processed now" - Something like an arrow "<-"
Thanks!I Think you could use dialogs with JOptionPane and JProgressBar.
Have a look at:
http://java.sun.com/docs/books/tutorial/uiswing/components/dialog.html
and
http://java.sun.com/docs/books/tutorial/uiswing/components/progress.html
-Puce -
Where can i download the standard swing icon and images!
I remember that sun has provided a lot of resources for swing gui, who can tell me the link
Many thanks!You're talking about this?
http://developer.java.sun.com/developer/techDocs/hi/repository/ -
Adding an Icon to a JButton Component - Not working
Hi all,
Please help me by saying, why the below gevon SSCE doesnt work.
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.AbstractButton;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
public class CreateWindow {
public CreateWindow(String module, String id){
if(module.equals("mail")){
JPanel mail = new JPanel(null);
mail.setPreferredSize(new Dimension(500, 350));
//Color colr = new Color(222, 236, 255);
mail.setBackground(Color.WHITE);
JLabel file = new JLabel("File Name:");
file.setBounds(18,25,75,50);
// Retrieve the icon
Icon icon = new ImageIcon("ei0021-48.gif");
// Create an action with an icon
Action action = new AbstractAction("Button Label", icon) {
// This method is called when the button is pressed
public void actionPerformed(ActionEvent evt) {
// Perform action
// Create the button; the icon will appear to the left of the label
JButton button = new JButton(action);
mail.add(button);
buildGUI(mail,500, 350);
public void buildGUI(JPanel panel, int width, int height)
JFrame.setDefaultLookAndFeelDecorated(true);
UIManager.put("activeCaption", new javax.swing.plaf.ColorUIResource(Color.LIGHT_GRAY));
JFrame f = new JFrame("Propri�t�s:");
f.setIconImage(new ImageIcon("save.gif").getImage());//need an image file with black background
changeButtonColor(f.getComponents());
f.getContentPane().setBackground(Color.WHITE);
f.getContentPane().add(panel);
f.getRootPane().setBorder(BorderFactory.createLineBorder(Color.PINK,2));
f.setSize(width,height);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setVisible(true);
public void changeButtonColor(Component[] comps)
for(int x = 0, y = comps.length; x < y; x++)
if(comps[x] instanceof AbstractButton)
((AbstractButton)comps[x]).setBackground(Color.LIGHT_GRAY);
((AbstractButton)comps[x]).setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
else if (comps[x] instanceof Container)
changeButtonColor(((Container)comps[x]).getComponents());
}I call the above given class constructor as given
public class Test {
public static void main(String args[]){
CreateWindow cw = new CreateWindow("mail","Test.doc");
}RonyRonyFederer wrote:
I have the images and class files inside
F:\Testing3\Application\src\booodrive
Do you have the class files or java files here?
You should put the gif where the .class files are located, and use getResource as Encephalopathic wrote, or:
Icon icon = new ImageIcon(ClassLoader.getSystemResource("ei0021-48.gif"));
When I did as you said using System.out.println(new File("ei0021-48.gif").getAbsolutePath());, I got the following output.
F:\Testing3\Application\ei0021-48.gif
That's the current running directory. -
How to change The Standard JOptionPane Icon?
in this simple code
i want to change the Standard JOptionPane icon to a different icon
how could it be?
thank you
import java.awt.*;
import javax.swing.*;
import java.awt.event.WindowListener;
import java.awt.event.WindowEvent;
import javax.sound.sampled.*;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.ImageIcon;
import javax.swing.Icon;
import java.awt.event.*;
public class MyFrame extends JFrame
JLabel label=new JLabel("Hello");
MyInner inner;
MyFrame ()
setupGUI();
private void setupGUI()
JFrame f =new JFrame();
// f.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
f.setTitle("Window Event");
f.setSize(550,350);
f.setResizable(false);
f.setLayout(new BorderLayout());
f.add("Center",label);
f.show(true);
inner=new MyInner();
f.addWindowListener(inner);
class MyInner extends WindowAdapter
public void windowClosing(WindowEvent ee)
Toolkit tool = Toolkit.getDefaultToolkit();
tool.beep();
JOptionPane.showMessageDialog(null, "Nice Work! " );
System.exit(0);
public static void main(String[]args)
MyFrame frame=new MyFrame ();
}For instance:
class MyInner extends WindowAdapter
public void windowClosing(WindowEvent ee)
Toolkit tool = Toolkit.getDefaultToolkit();
tool.beep();
JOptionPane.showMessageDialog(null, "Nice Work! ");
ImageIcon myImageIcon = new ImageIcon("myPic.jpg"); // needs proper path here
JOptionPane.showMessageDialog(null, "Better Work!", "Dang, I'm smart!", JOptionPane.ERROR_MESSAGE, myImageIcon);
System.exit(0);
} -
Hello ,
I'm working with eclipse to prgram mu project
I want to add for a button an icon and when I press this button this icon will be drawed.
this is my code :
import javax.swing.Icon ;
public class Fenetre extends JFrame
Icon img = new Icon("medias/img1.gif");
public Fenetre ()
super();
this.setTitle("Menu");
this.setSize(500,500);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenu initial = new JMenu (new InitialAction(this, "initial"));
initial.setIcon(img);
I am sorry for my english is bad :sNa prima. Du hast in dem anderen Thread gute Antworten bekommen, also gibt es keinen Grund einen neuen Thread zu starten, obwohl dieses Forum für Deine Frage besser gewesen wäre. Ich mache hier mal dicht, wenn noch Fragen sind, stell sie in Deinem anderen Thread.
Gruß, Phil -
Jtree Select node and change leafs icon problem
Hi All,
i create a tree and implement a TreeSelectionListener:
my mission is whenever i select a node i need to change the icon of this node (for now.later i will have to find if it have childrens).
import java.awt.Color;
import java.awt.Component;
import java.util.Enumeration;
import java.util.NoSuchElementException;
import java.util.Vector;
import javax.swing.ImageIcon;
import javax.swing.JTree;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
public class TreeView{
DefaultMutableTreeNode top;
JTree tree ;
Color frameColor;
public static ImageIcon NoTSelIcon;
public static ImageIcon SelIcon;
public static String[] name= new String[8];
public TreeView(Color BackColor) {
// TODO Auto-generated constructor stub
top = new DefaultMutableTreeNode("Diagnostics");
this.frameColor=BackColor;
SelIcon = createImageIcon("../Resource/Images/Select.gif");
if (SelIcon == null)
System.err.println("Tutorial icon missing; using default.");
NoTSelIcon = createImageIcon("../Resource/Images/NotSelc.gif");
if (NoTSelIcon == null)
System.err.println("Tutorial icon missing; using default.");
public Component createTreeComponents(){
//Create the nodes.
createNodes(top);
//Create a tree that allows one selection at a time.
tree = new JTree(top);
//TREE LISTENERS
//Treeselction listener
Handler hObject = new Handler();
tree.addTreeSelectionListener(hObject);
//Tree expand/collapse listener
HandlerExpansionListener hObjectExpan = new HandlerExpansionListener();
tree.addTreeExpansionListener(hObjectExpan);
// tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
//set tree background
tree.setBackground(frameColor);
tree.setCellRenderer(new OverrideTreeCellRenderer(frameColor,SelIcon,NoTSelIcon));
return tree;
private void createNodes(DefaultMutableTreeNode top) {
DefaultMutableTreeNode category = null;
DefaultMutableTreeNode SubCategory = null;
DefaultMutableTreeNode SubCategoryBasee = null;
DefaultMutableTreeNode SubSubCategoryBasee = null;
category = new DefaultMutableTreeNode("Dfe");
top.add(category);
//Sub test visible
SubCategory = new DefaultMutableTreeNode("Test Visible");
category.add(SubCategory);
SubCategory.add(new DefaultMutableTreeNode("Son 1"));
SubCategory.add(new DefaultMutableTreeNode("Son 2"));
SubSubCategoryBasee = new DefaultMutableTreeNode("Test Base");
SubSubCategoryBasee.add(new DefaultMutableTreeNode("Grandson 1"));
SubSubCategoryBasee.add(new DefaultMutableTreeNode("Grandson 2"));
SubCategory.add(SubSubCategoryBasee);
class Handler implements TreeSelectionListener {
public void valueChanged(TreeSelectionEvent arg0) {
// TODO Auto-generated method stub
System.out.println("treeSelect event ");
TreePath trph;
trph=arg0.getNewLeadSelectionPath();
int count=trph.getPathCount();
DefaultMutableTreeNode Selnode = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
String Name = (String)Selnode.getUserObject();
setSelected(Selnode,true);
int number_ofnodes=getNodeCountBelow((TreeModel)tree.getModel() , Selnode, false);
System.out.println("The Number of nodes under "+Name+"="+number_ofnodes);
tree.setCellRenderer(new IconRenderer(SelIcon,NoTSelIcon,frameColor));
class HandlerExpansionListener implements TreeExpansionListener {
public void valueChanged(TreeSelectionEvent arg0) {
// TODO Auto-generated method stub
DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
if (node == null) return;
} // The inner class
public void treeCollapsed(TreeExpansionEvent arg0) {
// TODO Auto-generated method stub
System.out.println("treeCollapsed event ");
public void treeExpanded(TreeExpansionEvent arg0) {
// TODO Auto-generated method stub
System.out.println("treeExpanded event ");
/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path) {
//ImageIcon imcon= new ImageIcon(path);
//return imcon;
java.net.URL imgURL = TreeView.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
DefaultMutableTreeNode newnode;
public void setSelected(DefaultMutableTreeNode Selnode ,boolean isSelected)
Enumeration Enchilds=Selnode.children();//ENUMRATE ALL CHILDS FOR THIS NODE
if (Enchilds != null)
while (Enchilds.hasMoreElements())
newnode=(DefaultMutableTreeNode)Enchilds.nextElement();
String NameSel = (String)newnode.getUserObject();
setSelected(newnode,isSelected);
//GETTING THE TREE DEPTH
public int getNodeCountBelow(TreeModel model, Object node, boolean includeInitialNode)
int n = includeInitialNode ? 1 : 0;
for (int i = 0; i < model.getChildCount(node); i ++)
n += getNodeCountBelow(model, model.getChild(node, i), true);
return n;
import java.awt.Color;
import java.awt.Component;
import java.util.Enumeration;
import java.util.NoSuchElementException;
import javax.swing.Icon;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
public class IconRenderer extends DefaultTreeCellRenderer {
private static final long serialVersionUID = 1L;
Icon SelectedIcon;
Icon NotSelectedIcon;
Color BackgroundColor;
boolean Selected=false;
boolean Leaf=false;
boolean IsItaChild=false;
DefaultMutableTreeNode SelctedNode=null;
public IconRenderer(Icon SelIcon,Icon NoTSelIcon,Color Bacground) {
SelectedIcon = SelIcon;
NotSelectedIcon = NoTSelIcon;
BackgroundColor=Bacground;
setBackgroundNonSelectionColor(BackgroundColor);
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);
Selected=sel;
Leaf=leaf;
DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
String s2 = (String)node.getUserObject();
return this;
}my problem is :
when i select a node the the method "getTreeCellRendererComponent"
start to run on the entire tree from buttom to top and than from top to buttom.
for me it waste of time because if has say 100 nodes it wont botthers me.
but i have 20000 nodes and more its take a time.
and for all this nodes i have to make compares.
is there a way to force the DefaultTreeCellRenderer to not run the entire tree???
ThanksYou need to make sure that your TreeModel interprets your group nodes to be non-leaf nodes (one of the methods in the TreeModel interface is called isLeaf). If you are using a DefaultTreeModel with DefaultMutableTreeNode objects, you can use the askAllowsChildren property of DefaultTreeModel and the allowsChildren property of DefaultMutableTreeNode to control this. See the API for more details:
http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/tree/DefaultTreeModel.html
http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/tree/DefaultMutableTreeNode.html -
Ok, so I was trying to get a JTabbedPane with 'X' icons on each tab. Searched this site, and found no answers, but loads of questions on how to do it. I've done it now, and here's my code.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
* A JTabbedPane which has a close ('X') icon on each tab.
* To add a tab, use the method addTab(String, Component)
* To have an extra icon on each tab (e.g. like in JBuilder, showing the file type) use
* the method addTab(String, Component, Icon). Only clicking the 'X' closes the tab.
public class JTabbedPaneWithCloseIcons extends JTabbedPane implements MouseListener {
public JTabbedPaneWithCloseIcons() {
super();
addMouseListener(this);
public void addTab(String title, Component component) {
this.addTab(title, component, null);
public void addTab(String title, Component component, Icon extraIcon) {
super.addTab(title, new CloseTabIcon(extraIcon), component);
public void mouseClicked(MouseEvent e) {
int tabNumber=getUI().tabForCoordinate(this, e.getX(), e.getY());
if (tabNumber < 0) return;
Rectangle rect=((CloseTabIcon)getIconAt(tabNumber)).getBounds();
if (rect.contains(e.getX(), e.getY())) {
//the tab is being closed
this.removeTabAt(tabNumber);
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
* The class which generates the 'X' icon for the tabs. The constructor
* accepts an icon which is extra to the 'X' icon, so you can have tabs
* like in JBuilder. This value is null if no extra icon is required.
class CloseTabIcon implements Icon {
private int x_pos;
private int y_pos;
private int width;
private int height;
private Icon fileIcon;
public CloseTabIcon(Icon fileIcon) {
this.fileIcon=fileIcon;
width=16;
height=16;
public void paintIcon(Component c, Graphics g, int x, int y) {
this.x_pos=x;
this.y_pos=y;
Color col=g.getColor();
g.setColor(Color.black);
int y_p=y+2;
g.drawLine(x+1, y_p, x+12, y_p);
g.drawLine(x+1, y_p+13, x+12, y_p+13);
g.drawLine(x, y_p+1, x, y_p+12);
g.drawLine(x+13, y_p+1, x+13, y_p+12);
g.drawLine(x+3, y_p+3, x+10, y_p+10);
g.drawLine(x+3, y_p+4, x+9, y_p+10);
g.drawLine(x+4, y_p+3, x+10, y_p+9);
g.drawLine(x+10, y_p+3, x+3, y_p+10);
g.drawLine(x+10, y_p+4, x+4, y_p+10);
g.drawLine(x+9, y_p+3, x+3, y_p+9);
g.setColor(col);
if (fileIcon != null) {
fileIcon.paintIcon(c, g, x+width, y_p);
public int getIconWidth() {
return width + (fileIcon != null? fileIcon.getIconWidth() : 0);
public int getIconHeight() {
return height;
public Rectangle getBounds() {
return new Rectangle(x_pos, y_pos, width, height);
}You can also specify an extra icon to put on each tab. Read my comments on how to do it.With the following code you'll be able to have use SCROLL_TAB_LAYOUT and WRAP_TAB_LAYOUT. With setCloseIcons() you'll be able to set images for the close-icons.
The TabbedPane:
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JTabbedPane;
import javax.swing.JViewport;
import javax.swing.SwingUtilities;
import java.awt.Color;
import java.awt.Component;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.event.EventListenerList;
import javax.swing.plaf.basic.BasicTabbedPaneUI;
import javax.swing.plaf.metal.MetalTabbedPaneUI;
* A JTabbedPane which has a close ('X') icon on each tab.
* To add a tab, use the method addTab(String, Component)
* To have an extra icon on each tab (e.g. like in JBuilder, showing the file
* type) use the method addTab(String, Component, Icon). Only clicking the 'X'
* closes the tab.
public class CloseableTabbedPane extends JTabbedPane implements MouseListener,
MouseMotionListener {
* The <code>EventListenerList</code>.
private EventListenerList listenerList = null;
* The viewport of the scrolled tabs.
private JViewport headerViewport = null;
* The normal closeicon.
private Icon normalCloseIcon = null;
* The closeicon when the mouse is over.
private Icon hooverCloseIcon = null;
* The closeicon when the mouse is pressed.
private Icon pressedCloseIcon = null;
* Creates a new instance of <code>CloseableTabbedPane</code>
public CloseableTabbedPane() {
super();
init(SwingUtilities.LEFT);
* Creates a new instance of <code>CloseableTabbedPane</code>
* @param horizontalTextPosition the horizontal position of the text (e.g.
* SwingUtilities.TRAILING or SwingUtilities.LEFT)
public CloseableTabbedPane(int horizontalTextPosition) {
super();
init(horizontalTextPosition);
* Initializes the <code>CloseableTabbedPane</code>
* @param horizontalTextPosition the horizontal position of the text (e.g.
* SwingUtilities.TRAILING or SwingUtilities.LEFT)
private void init(int horizontalTextPosition) {
listenerList = new EventListenerList();
addMouseListener(this);
addMouseMotionListener(this);
if (getUI() instanceof MetalTabbedPaneUI)
setUI(new CloseableMetalTabbedPaneUI(horizontalTextPosition));
else
setUI(new CloseableTabbedPaneUI(horizontalTextPosition));
* Allows setting own closeicons.
* @param normal the normal closeicon
* @param hoover the closeicon when the mouse is over
* @param pressed the closeicon when the mouse is pressed
public void setCloseIcons(Icon normal, Icon hoover, Icon pressed) {
normalCloseIcon = normal;
hooverCloseIcon = hoover;
pressedCloseIcon = pressed;
* Adds a <code>Component</code> represented by a title and no icon.
* @param title the title to be displayed in this tab
* @param component the component to be displayed when this tab is clicked
public void addTab(String title, Component component) {
addTab(title, component, null);
* Adds a <code>Component</code> represented by a title and an icon.
* @param title the title to be displayed in this tab
* @param component the component to be displayed when this tab is clicked
* @param extraIcon the icon to be displayed in this tab
public void addTab(String title, Component component, Icon extraIcon) {
boolean doPaintCloseIcon = true;
try {
Object prop = null;
if ((prop = ((JComponent) component).
getClientProperty("isClosable")) != null) {
doPaintCloseIcon = (Boolean) prop;
} catch (Exception ignored) {/*Could probably be a ClassCastException*/}
super.addTab(title,
doPaintCloseIcon ? new CloseTabIcon(extraIcon) : null,
component);
if (headerViewport == null) {
for (Component c : getComponents()) {
if ("TabbedPane.scrollableViewport".equals(c.getName()))
headerViewport = (JViewport) c;
* Invoked when the mouse button has been clicked (pressed and released) on
* a component.
* @param e the <code>MouseEvent</code>
public void mouseClicked(MouseEvent e) {
processMouseEvents(e);
* Invoked when the mouse enters a component.
* @param e the <code>MouseEvent</code>
public void mouseEntered(MouseEvent e) { }
* Invoked when the mouse exits a component.
* @param e the <code>MouseEvent</code>
public void mouseExited(MouseEvent e) {
for (int i=0; i<getTabCount(); i++) {
CloseTabIcon icon = (CloseTabIcon) getIconAt(i);
if (icon != null)
icon.mouseover = false;
repaint();
* Invoked when a mouse button has been pressed on a component.
* @param e the <code>MouseEvent</code>
public void mousePressed(MouseEvent e) {
processMouseEvents(e);
* Invoked when a mouse button has been released on a component.
* @param e the <code>MouseEvent</code>
public void mouseReleased(MouseEvent e) { }
* Invoked when a mouse button is pressed on a component and then dragged.
* <code>MOUSE_DRAGGED</code> events will continue to be delivered to the
* component where the drag originated until the mouse button is released
* (regardless of whether the mouse position is within the bounds of the
* component).<br/>
* <br/>
* Due to platform-dependent Drag&Drop implementations,
* <code>MOUSE_DRAGGED</code> events may not be delivered during a native
* Drag&Drop operation.
* @param e the <code>MouseEvent</code>
public void mouseDragged(MouseEvent e) {
processMouseEvents(e);
* Invoked when the mouse cursor has been moved onto a component but no
* buttons have been pushed.
* @param e the <code>MouseEvent</code>
public void mouseMoved(MouseEvent e) {
processMouseEvents(e);
* Processes all caught <code>MouseEvent</code>s.
* @param e the <code>MouseEvent</code>
private void processMouseEvents(MouseEvent e) {
int tabNumber = getUI().tabForCoordinate(this, e.getX(), e.getY());
if (tabNumber < 0) return;
CloseTabIcon icon = (CloseTabIcon) getIconAt(tabNumber);
if (icon != null) {
Rectangle rect= icon.getBounds();
Point pos = headerViewport == null ?
new Point() : headerViewport.getViewPosition();
Rectangle drawRect = new Rectangle(
rect.x - pos.x, rect.y - pos.y, rect.width, rect.height);
if (e.getID() == e.MOUSE_PRESSED) {
icon.mousepressed = e.getModifiers() == e.BUTTON1_MASK;
repaint(drawRect);
} else if (e.getID() == e.MOUSE_MOVED || e.getID() == e.MOUSE_DRAGGED ||
e.getID() == e.MOUSE_CLICKED) {
pos.x += e.getX();
pos.y += e.getY();
if (rect.contains(pos)) {
if (e.getID() == e.MOUSE_CLICKED) {
int selIndex = getSelectedIndex();
if (fireCloseTab(selIndex)) {
if (selIndex > 0) {
// to prevent uncatchable null-pointers
Rectangle rec = getUI().getTabBounds(this, selIndex - 1);
MouseEvent event = new MouseEvent((Component) e.getSource(),
e.getID() + 1,
System.currentTimeMillis(),
e.getModifiers(),
rec.x,
rec.y,
e.getClickCount(),
e.isPopupTrigger(),
e.getButton());
dispatchEvent(event);
//the tab is being closed
//removeTabAt(tabNumber);
remove(selIndex);
} else {
icon.mouseover = false;
icon.mousepressed = false;
repaint(drawRect);
} else {
icon.mouseover = true;
icon.mousepressed = e.getModifiers() == e.BUTTON1_MASK;
} else {
icon.mouseover = false;
repaint(drawRect);
* Adds an <code>CloseableTabbedPaneListener</code> to the tabbedpane.
* @param l the <code>CloseableTabbedPaneListener</code> to be added
public void addCloseableTabbedPaneListener(CloseableTabbedPaneListener l) {
listenerList.add(CloseableTabbedPaneListener.class, l);
* Removes an <code>CloseableTabbedPaneListener</code> from the tabbedpane.
* @param l the listener to be removed
public void removeCloseableTabbedPaneListener(CloseableTabbedPaneListener l) {
listenerList.remove(CloseableTabbedPaneListener.class, l);
* Returns an array of all the <code>SearchListener</code>s added to this
* <code>SearchPane</code> with addSearchListener().
* @return all of the <code>SearchListener</code>s added or an empty array if
* no listeners have been added
public CloseableTabbedPaneListener[] getCloseableTabbedPaneListener() {
return listenerList.getListeners(CloseableTabbedPaneListener.class);
* Notifies all listeners that have registered interest for notification on
* this event type.
* @param tabIndexToClose the index of the tab which should be closed
* @return true if the tab can be closed, false otherwise
protected boolean fireCloseTab(int tabIndexToClose) {
boolean closeit = true;
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
for (Object i : listeners) {
if (i instanceof CloseableTabbedPaneListener) {
if (!((CloseableTabbedPaneListener) i).closeTab(tabIndexToClose)) {
closeit = false;
break;
return closeit;
* The class which generates the 'X' icon for the tabs. The constructor
* accepts an icon which is extra to the 'X' icon, so you can have tabs
* like in JBuilder. This value is null if no extra icon is required.
class CloseTabIcon implements Icon {
* the x position of the icon
private int x_pos;
* the y position of the icon
private int y_pos;
* the width the icon
private int width;
* the height the icon
private int height;
* the additional fileicon
private Icon fileIcon;
* true whether the mouse is over this icon, false otherwise
private boolean mouseover = false;
* true whether the mouse is pressed on this icon, false otherwise
private boolean mousepressed = false;
* Creates a new instance of <code>CloseTabIcon</code>
* @param fileIcon the additional fileicon, if there is one set
public CloseTabIcon(Icon fileIcon) {
this.fileIcon = fileIcon;
width = 16;
height = 16;
* Draw the icon at the specified location. Icon implementations may use the
* Component argument to get properties useful for painting, e.g. the
* foreground or background color.
* @param c the component which the icon belongs to
* @param g the graphic object to draw on
* @param x the upper left point of the icon in the x direction
* @param y the upper left point of the icon in the y direction
public void paintIcon(Component c, Graphics g, int x, int y) {
boolean doPaintCloseIcon = true;
try {
// JComponent.putClientProperty("isClosable", new Boolean(false));
JTabbedPane tabbedpane = (JTabbedPane) c;
int tabNumber = tabbedpane.getUI().tabForCoordinate(tabbedpane, x, y);
JComponent curPanel = (JComponent) tabbedpane.getComponentAt(tabNumber);
Object prop = null;
if ((prop = curPanel.getClientProperty("isClosable")) != null) {
doPaintCloseIcon = (Boolean) prop;
} catch (Exception ignored) {/*Could probably be a ClassCastException*/}
if (doPaintCloseIcon) {
x_pos = x;
y_pos = y;
int y_p = y + 1;
if (normalCloseIcon != null && !mouseover) {
normalCloseIcon.paintIcon(c, g, x, y_p);
} else if (hooverCloseIcon != null && mouseover && !mousepressed) {
hooverCloseIcon.paintIcon(c, g, x, y_p);
} else if (pressedCloseIcon != null && mousepressed) {
pressedCloseIcon.paintIcon(c, g, x, y_p);
} else {
y_p++;
Color col = g.getColor();
if (mousepressed && mouseover) {
g.setColor(Color.WHITE);
g.fillRect(x+1, y_p, 12, 13);
g.setColor(Color.black);
g.drawLine(x+1, y_p, x+12, y_p);
g.drawLine(x+1, y_p+13, x+12, y_p+13);
g.drawLine(x, y_p+1, x, y_p+12);
g.drawLine(x+13, y_p+1, x+13, y_p+12);
g.drawLine(x+3, y_p+3, x+10, y_p+10);
if (mouseover)
g.setColor(Color.GRAY);
g.drawLine(x+3, y_p+4, x+9, y_p+10);
g.drawLine(x+4, y_p+3, x+10, y_p+9);
g.drawLine(x+10, y_p+3, x+3, y_p+10);
g.drawLine(x+10, y_p+4, x+4, y_p+10);
g.drawLine(x+9, y_p+3, x+3, y_p+9);
g.setColor(col);
if (fileIcon != null) {
fileIcon.paintIcon(c, g, x+width, y_p);
* Returns the icon's width.
* @return an int specifying the fixed width of the icon.
public int getIconWidth() {
return width + (fileIcon != null ? fileIcon.getIconWidth() : 0);
* Returns the icon's height.
* @return an int specifying the fixed height of the icon.
public int getIconHeight() {
return height;
* Gets the bounds of this icon in the form of a <code>Rectangle<code>
* object. The bounds specify this icon's width, height, and location
* relative to its parent.
* @return a rectangle indicating this icon's bounds
public Rectangle getBounds() {
return new Rectangle(x_pos, y_pos, width, height);
* A specific <code>BasicTabbedPaneUI</code>.
class CloseableTabbedPaneUI extends BasicTabbedPaneUI {
* the horizontal position of the text
private int horizontalTextPosition = SwingUtilities.LEFT;
* Creates a new instance of <code>CloseableTabbedPaneUI</code>
public CloseableTabbedPaneUI() {
* Creates a new instance of <code>CloseableTabbedPaneUI</code>
* @param horizontalTextPosition the horizontal position of the text (e.g.
* SwingUtilities.TRAILING or SwingUtilities.LEFT)
public CloseableTabbedPaneUI(int horizontalTextPosition) {
this.horizontalTextPosition = horizontalTextPosition;
* Layouts the label
* @param tabPlacement the placement of the tabs
* @param metrics the font metrics
* @param tabIndex the index of the tab
* @param title the title of the tab
* @param icon the icon of the tab
* @param tabRect the tab boundaries
* @param iconRect the icon boundaries
* @param textRect the text boundaries
* @param isSelected true whether the tab is selected, false otherwise
protected void layoutLabel(int tabPlacement, FontMetrics metrics,
int tabIndex, String title, Icon icon,
Rectangle tabRect, Rectangle iconRect,
Rectangle textRect, boolean isSelected) {
textRect.x = textRect.y = iconRect.x = iconRect.y = 0;
javax.swing.text.View v = getTextViewForTab(tabIndex);
if (v != null) {
tabPane.putClientProperty("html", v);
SwingUtilities.layoutCompoundLabel((JComponent) tabPane,
metrics, title, icon,
SwingUtilities.CENTER,
SwingUtilities.CENTER,
SwingUtilities.CENTER,
//SwingUtilities.TRAILING,
horizontalTextPosition,
tabRect,
iconRect,
textRect,
textIconGap + 2);
tabPane.putClientProperty("html", null);
int xNudge = getTabLabelShiftX(tabPlacement, tabIndex, isSelected);
int yNudge = getTabLabelShiftY(tabPlacement, tabIndex, isSelected);
iconRect.x += xNudge;
iconRect.y += yNudge;
textRect.x += xNudge;
textRect.y += yNudge;
* A specific <code>MetalTabbedPaneUI</code>.
class CloseableMetalTabbedPaneUI extends MetalTabbedPaneUI {
* the horizontal position of the text
private int horizontalTextPosition = SwingUtilities.LEFT;
* Creates a new instance of <code>CloseableMetalTabbedPaneUI</code>
public CloseableMetalTabbedPaneUI() {
* Creates a new instance of <code>CloseableMetalTabbedPaneUI</code>
* @param horizontalTextPosition the horizontal position of the text (e.g.
* SwingUtilities.TRAILING or SwingUtilities.LEFT)
public CloseableMetalTabbedPaneUI(int horizontalTextPosition) {
this.horizontalTextPosition = horizontalTextPosition;
* Layouts the label
* @param tabPlacement the placement of the tabs
* @param metrics the font metrics
* @param tabIndex the index of the tab
* @param title the title of the tab
* @param icon the icon of the tab
* @param tabRect the tab boundaries
* @param iconRect the icon boundaries
* @param textRect the text boundaries
* @param isSelected true whether the tab is selected, false otherwise
protected void layoutLabel(int tabPlacement, FontMetrics metrics,
int tabIndex, String title, Icon icon,
Rectangle tabRect, Rectangle iconRect,
Rectangle textRect, boolean isSelected) {
textRect.x = textRect.y = iconRect.x = iconRect.y = 0;
javax.swing.text.View v = getTextViewForTab(tabIndex);
if (v != null) {
tabPane.putClientProperty("html", v);
SwingUtilities.layoutCompoundLabel((JComponent) tabPane,
metrics, title, icon,
SwingUtilities.CENTER,
SwingUtilities.CENTER,
SwingUtilities.CENTER,
//SwingUtilities.TRAILING,
horizontalTextPosition,
tabRect,
iconRect,
textRect,
textIconGap + 2);
tabPane.putClientProperty("html", null);
int xNudge = getTabLabelShiftX(tabPlacement, tabIndex, isSelected);
int yNudge = getTabLabelShiftY(tabPlacement, tabIndex, isSelected);
iconRect.x += xNudge;
iconRect.y += yNudge;
textRect.x += xNudge;
textRect.y += yNudge;
}The Listener:
import java.util.EventListener;
* The listener that's notified when an tab should be closed in the
* <code>CloseableTabbedPane</code>.
public interface CloseableTabbedPaneListener extends EventListener {
* Informs all <code>CloseableTabbedPaneListener</code>s when a tab should be
* closed
* @param tabIndexToClose the index of the tab which should be closed
* @return true if the tab can be closed, false otherwise
boolean closeTab(int tabIndexToClose);
} -
Learning Swing - Can't get JLabel to appear in JFrame
Hi,
I'm a complete beginner to Java. I'm taking a course that's moving way too fast, in my opinion, and we're currently studying Swing. I've likely missed a lot of basic basic Java fundamentals due to the speed of this class, so if I'm making a ridiculous mistake, please let me know.
I'm trying to create the following:
+"Create a GUI interface using the Swing API. Use the JOptionPane class to create a dialog box to ask the+
+user for the University Name. Create a JFrame that has a label with the University name and create your+
+own logo. The window should have the capability of inputting first name , last name, and id for a student+
+in text fields. Once the id is entered open another dialog box with the student information."+
I'm pretty much done, I'm just having issues getting the output from the first JFrame to appear in the second JFrame. When I create a new JFrame, the title I specify appears, but the normal syntax for a JLabel just isn't working and I'm not sure why.
I suspect it has something to do with the general structure of my program rather than my syntax. ...I know I'm missing a lot of fundamentals that I should have developed, thanks to the way the course I'm in is structured.
I'm posting two .java files. The first, called GUIFrame.java is the class that basically does everything, it calls JOptionPane, opens the first and second JFrames, and uses ActionEvent and ActionListener to read text from the text fields. The second .java file is called GUITest.java and all it does is instantiate GUIFrame and sets the JFrame parameters.
If anyone has any suggestions, at all, about how to fix this, or especially how to structure these better... Any suggestion would be greatly appreciated.
CODE:
import javax.swing.JFrame; //provides basic window features
import javax.swing.JOptionPane; //simple GUI input/output
import javax.swing.JLabel; //displays text and images
import javax.swing.Icon; //interface used to manipulate images
import javax.swing.ImageIcon; //loads images
import java.awt.FlowLayout; // specifies how components are arranged
import javax.swing.SwingConstants; //common constants used with Swing
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class GUIFrame extends JFrame
private JLabel line1;
private JLabel line2;
private JLabel line3;
private JLabel line4;
private JTextField textField1;
private JTextField textField2;
private JTextField textField3;
//This method prompts the user in a JOptionPane for the university's name.
public static String obtainUniversityName()
//Obtain user input from JOptionPane input dialog for universityName.
String uName = JOptionPane.showInputDialog(null,"Enter the University's name","University Name",JOptionPane.QUESTION_MESSAGE);
return uName;
//This method creates an image icon if possible, or it will print an error and return null
protected ImageIcon createImageIcon(String path,String description)
java.net.URL imgURL = getClass().getResource(path);
if (imgURL != null)
return new ImageIcon(imgURL, description);
} else {
System.err.println("Couldn't find file: " + path);
return null;
public GUIFrame()
//Create a new JFrame for the university info to be placed in
//The title of the window is also declared here
super(obtainUniversityName());
//Sets way things are arranged
setLayout(new FlowLayout());
//Grabs logo and aligns it with "Welcome to the University"
ImageIcon logo = createImageIcon("girl.gif","This is a logo");
line1 = new JLabel("Welcome to the University", logo, JLabel.CENTER);
add(line1);
//"First Name" + Text Field
line2 = new JLabel("First Name");
add(line2);
textField1 = new JTextField(10);
add(textField1);
//"Last Name" + Text Field
line3 = new JLabel("Last Name");
add(line3);
textField2 = new JTextField(10);
add(textField2);
//"Student ID" + Text Field
line4 = new JLabel("Student ID");
add(line4);
textField3 = new JTextField(10);
add(textField3);
//Register event handlers
TextFieldHandler handler = new TextFieldHandler();
textField1.addActionListener(handler);
textField2.addActionListener(handler);
textField3.addActionListener(handler);
private class TextFieldHandler implements ActionListener
public void actionPerformed(ActionEvent event)
String fname = "";
String lname = "";
String stuid = "";
//When user presses enter in any text field, these set values for input into text field
if(event.getSource()==textField1)
fname = String.format("First Name: %s", event.getActionCommand());
else if(event.getSource()==textField2)
lname=String.format("Last Name: %s", event.getActionCommand());
else if(event.getSource()==textField3)
stuid=String.format("Student ID: %s", event.getActionCommand());
else
System.out.println("ERROR! You didn't fill in atleast one of the text boxes...");
//Creates a new JFrame with title "Student Info"
JFrame frame2 = new JFrame("Student Info");
//Sets way things are arranged
setLayout(new FlowLayout());
//Temporary - Tests to see that processing of text field events occurs correctly
System.out.println(fname);
System.out.println(lname);
System.out.println(stuid);
//Puts data into JLabels for display in new JFrame
JLabel label1=new JLabel(fname);
add(label1);
JLabel label2=new JLabel("Can you see this!?");
add(label2);
JLabel label3=new JLabel(stuid);
add(label3);
//Sets parameters, size, close, visibility, etc, for new JFrame
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame2.setSize(275,210);
frame2.setVisible(true);
}//end void actionPerformed
}//end TextFieldHandler
}//end GUIFrame
==================================================================================
import javax.swing.JFrame; //provides basic window features
public class GUITest
public static void main(String args[])
//Calls on GUIFrame class. Instantiates.
GUIFrame guiFrame = new GUIFrame();
//Set the window to exit when closed
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Size the window
guiFrame.setSize(275,210);
//Center the window on the screen
guiFrame.setLocationRelativeTo(null);
//Make the window visible
guiFrame.setVisible(true);
}Thanks so much for the quick response. Yeah, I guess I'm a bit oblivious, I guess I missed that it was supposed to be another JOptionPane.
I fixed that and got rid of all the second JFrame stuff. Thank you.
And you're right, now that I can see my output, it's obvious I have serious issues in the actionPerformed() method with the ActionListener. I guess it's just a simple question of how to take what's in all three boxes and output to JOptionPane. Simple logic I guess.
I don't completely understand the ActionListener. I've read my textbook about it and looked at a few online resources, but I don't have a complete understanding.
How then, would I be able to use the ActionListener to get the text from all three text fields?
The way it is now, as you correctly predicted, it waits for enter to be inputted from each text field and whichever text field you hit enter in, despite what's in the other text fields, is the only thing that is outputted to the string in the JOptionPane.
Do you have a suggestion for that?
Thanks again.
CODE:
import javax.swing.JFrame; //provides basic window features
import javax.swing.JOptionPane; //simple GUI input/output
import javax.swing.JLabel; //displays text and images
import javax.swing.Icon; //interface used to manipulate images
import javax.swing.ImageIcon; //loads images
import java.awt.FlowLayout; // specifies how components are arranged
import javax.swing.SwingConstants; //common constants used with Swing
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class GUIFrame extends JFrame
private JLabel line1;
private JLabel line2;
private JLabel line3;
private JLabel line4;
private JTextField textField1;
private JTextField textField2;
private JTextField textField3;
//This method prompts the user in a JOptionPane for the university's name.
public static String obtainUniversityName()
//Obtain user input from JOptionPane input dialog for universityName.
String uName = JOptionPane.showInputDialog(null,"Enter the University's name","University Name",JOptionPane.QUESTION_MESSAGE);
return uName;
//This method creates an image icon if possible, or it will print an error and return null
protected ImageIcon createImageIcon(String path,String description)
java.net.URL imgURL = getClass().getResource(path);
if (imgURL != null)
return new ImageIcon(imgURL, description);
} else {
System.err.println("Couldn't find file: " + path);
return null;
public GUIFrame()
//Create a new JFrame for the university info to be placed in
//The title of the window is also declared here
super(obtainUniversityName());
//Sets way things are arranged
setLayout(new FlowLayout());
//Grabs logo and aligns it with "Welcome to the University"
ImageIcon logo = createImageIcon("girl.gif","This is a logo");
line1 = new JLabel("Welcome to the University", logo, JLabel.CENTER);
add(line1);
//"First Name" + Text Field
line2 = new JLabel("First Name");
add(line2);
textField1 = new JTextField(10);
add(textField1);
//"Last Name" + Text Field
line3 = new JLabel("Last Name");
add(line3);
textField2 = new JTextField(10);
add(textField2);
//"Student ID" + Text Field
line4 = new JLabel("Student ID");
add(line4);
textField3 = new JTextField(10);
add(textField3);
//Register event handlers
TextFieldHandler handler = new TextFieldHandler();
textField1.addActionListener(handler);
textField2.addActionListener(handler);
textField3.addActionListener(handler);
private class TextFieldHandler implements ActionListener
public void actionPerformed(ActionEvent event)
String fname = "";
String lname = "";
String stuid = "";
//When user presses enter in any text field, these set values for input into text field
if(event.getSource()==textField1)
fname = String.format("First Name: %s", event.getActionCommand());
else if(event.getSource()==textField2)
lname=String.format("Last Name: %s", event.getActionCommand());
else if(event.getSource()==textField3)
stuid=String.format("Student ID: %s", event.getActionCommand());
else
System.out.println("ERROR! You didn't fill in atleast one of the text boxes...");
String out = fname + "\n" + lname + "\n" + stuid;
JOptionPane.showMessageDialog(null,out);
}//end void actionPerformed
}//end TextFieldHandler
}//end GUIFrame
import javax.swing.JFrame; //provides basic window features
public class GUITest
public static void main(String args[])
//Calls on GUIFrame class. Instantiates.
GUIFrame guiFrame = new GUIFrame();
//Set the window to exit when closed
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Size the window
guiFrame.setSize(275,210);
//Center the window on the screen
guiFrame.setLocationRelativeTo(null);
//Make the window visible
guiFrame.setVisible(true);
}Edited by: heathercmiller on Apr 5, 2008 8:56 AM -
GIF icon wont display in JList
Hello.
During development of a single application I've encountered a strange bug:
I am unable to display a gif icon in JList using JLabel as the cell renderer. Png icons work.
Could someone please point me to the obvious flaw in my example? :)
Example as netbeans project:
http://www.megaupload.com/?d=GVCDVO1F
Example code:
* GifIconInList.java
* Created on 28. srpen 2008, 11:03
package gificoninlist;
import java.awt.Color;
import java.awt.Component;
import java.net.URL;
import javax.swing.DefaultListModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
* @author Bedla
public class GifIconInList extends javax.swing.JFrame {
DefaultListModel listModel = new DefaultListModel();
/** Creates new form GifIconInList */
public GifIconInList() {
initComponents();
class labelCellRenderer extends JLabel implements ListCellRenderer {
public labelCellRenderer() {
setOpaque(true);
public Component getListCellRendererComponent(JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
if (value instanceof JLabel) {
JLabel label = (JLabel) value;
if (isSelected) {
label.setBackground(list.getSelectionBackground());
label.setForeground(list.getSelectionForeground());
} else {
label.setBackground(Color.white);
label.setForeground(Color.black);
return label;
return this;
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jList = new javax.swing.JList();
addPngButton = new javax.swing.JButton();
addGifButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jList.setModel(listModel);
jList.setCellRenderer(new labelCellRenderer());
jScrollPane1.setViewportView(jList);
addPngButton.setText("Add PNG");
addPngButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addPngButtonActionPerformed(evt);
addGifButton.setText("Add GIF");
addGifButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addGifButtonActionPerformed(evt);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 287, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(addPngButton)
.addComponent(addGifButton))
.addContainerGap())
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(31, 31, 31)
.addComponent(addPngButton)
.addGap(37, 37, 37)
.addComponent(addGifButton))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 278, Short.MAX_VALUE)))
.addContainerGap())
pack();
}// </editor-fold>
private void addPngButtonActionPerformed(java.awt.event.ActionEvent evt) {
URL iconURL = GifIconInList.class.getResource("otevren.PNG");
Icon icon = new ImageIcon(iconURL);
JLabel label = new JLabel("PNG icon: " + icon, icon, JLabel.CENTER);
listModel.addElement(label);
private void addGifButtonActionPerformed(java.awt.event.ActionEvent evt) {
URL iconURL = GifIconInList.class.getResource("otevrenblik.gif");
Icon icon = new ImageIcon(iconURL);
JLabel label = new JLabel("GIF icon: " + icon, icon, JLabel.CENTER);
listModel.addElement(label);
* @param args the command line arguments
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new GifIconInList().setVisible(true);
// Variables declaration - do not modify
private javax.swing.JButton addGifButton;
private javax.swing.JButton addPngButton;
private javax.swing.JList jList;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration
}I had write a program to display gif images inside a JList.
Here is the code
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class ImageList
BufferedImage[] images;
JList list;
public ImageList()
loadImages();
list = new JList(images);
list.setCellRenderer(new ImageRenderer());
private void loadImages()
String[] fileNames = {
"1", "2", "3", "4"
images = new BufferedImage[fileNames.length];
for(int i = 0; i < images.length; i++)
try
String path = "images/" + fileNames + ".gif";
URL url = getClass().getResource(path);
images[i] = ImageIO.read(url);
catch(MalformedURLException mue)
System.out.println("url: " + mue.getMessage());
catch(IOException ioe)
System.out.println("read: " + ioe.getMessage());
public static void main(String[] args)
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new JScrollPane(new ImageList().list));
f.setSize(400,400);
f.setLocation(200,200);
f.setVisible(true);
class ImageRenderer extends DefaultListCellRenderer
public Component getListCellRendererComponent(JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus)
// for default cell renderer behavior
Component c = super.getListCellRendererComponent(list, value,
index, isSelected, cellHasFocus);
// set icon for cell image
((JLabel)c).setIcon(new ImageIcon((BufferedImage)value));
((JLabel)c).setText("");
return c;
Here is netbeans project:
[http://www.mediafire.com/?nl29dl4tteu]
Note: If you check image 2.gif inside the src/images dir you will found that it is an animated gif but JList is displaying it as static image.
Bedla if you want both image and text then create a class like thisclass ListItem {
private BufferedImage image;
private String value;
public ListItem(
BufferedImage c, String s) {..}
public Color getImage() {..}
public String getValue() {..} -
Icons disapear after fullscreen MSDOS window
Hi there,
I'm currently experiencing problems with Swing Icons under Windows with jdk1.4.1 !
They suddenly disappear or are corrupted if I maximize and then minimize the DOS Window. I've read in the bug database that there is this problem with a specific grafic chip - but this is not my case ! I'm experiencing this both on a Compaq Notebook with Win2000 and a graf
chip ATI RAGE Mobility AGP Driver 5.0.2195.4045 and with a Windows XP Notebook (currently don't know graf chip).
To be sure the problem wasn't me and my code I downloaded and tested this with the "ButtonDemo.java" Code I got from the How to Use Buttons,... - Tutorial. With same result !!
Here is a further description of what I do: I first start ButtonDemo.java from a Dos Shell with java. I maximize the DOS shell to fullscreen, hit Enter a few times and then minimize it. Now I push one of the buttons or pass another application window over the ButtonDemo. The Button(s) are gone, corrupted or look strange !!
Now I do the following: Maximise once again the DOS Shell and minimize it again. Hey ! The buttons are back !!! BUT -- pass an application window over it or hit a button and - OH NO!!!!! They are corrupted again !
Does anyone have the same problem or an explanaton for this ? What is happening here ? Should I report this as a bug ?
Thanks
ClaudioAnother update:
The problem with the DOS Window exists also on a Yakumo Notebook with Windows XP and a SIS 630/730 S-VGA Graph Chipset.
Once again: does anyone else ever had these porblems ? -
Own definition of Icon for JMenuItem
Every time I try to add ColorIcon to JMenuItem it eats name space. How can I separate name from icon?
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import javax.swing.AbstractAction;
import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
public class Test extends JFrame {
public Test() {
JMenuBar menu = new JMenuBar();
JMenu mFile = new JMenu("File");
menu.add(mFile);
JMenu mColor = new JMenu("Color");
mFile.add(mColor);
mColor.add(new TakeAction(Color.RED, "This is red"));
setJMenuBar(menu);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setPreferredSize(new Dimension(screenSize.width/2, screenSize.height/2));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
public static void main(String[] args) {
new Test();
public class TakeAction extends AbstractAction implements ActionListener{
public TakeAction (Color color, String name) {
super(name);
putValue(SMALL_ICON, new ColorIcon(color));
@Override
public void actionPerformed(ActionEvent e) {
public class ColorIcon implements Icon {
private int width = 15;
private int height = 15;
private Color color;
public ColorIcon(Color color) {
this.color = color;
@Override
public int getIconHeight() {
return 0;
@Override
public int getIconWidth() {
return 0;
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(color);
g2d.fillOval(3, 3, width-3, height-3);
g2d.dispose();
}Edited by: Giraphant on Dec 30, 2010 3:23 AM
Edited by: Giraphant on Dec 30, 2010 3:24 AMprivate int width = 15;
private int height = 15;
@Override
public int getIconHeight() {
return 0;
@Override
public int getIconWidth() {
return 0;
}Does this make sense to you? -
Hi,
I using FileSystemView to get file type icon. But the icon dimension i am getting is either 16x16 or 32x32.
Can any one tell me, how to get bigger icons like windows vista have large icons view. upto 256x256Mayby this code can help:
FileSystemView view = FileSystemView.getFileSystemView();
ShellFolder shellFolder = ShellFolder.getShellFolder(new File("xx.gif"));
import java.io.File;
import java.io.IOException;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.BoxLayout;
import javax.swing.filechooser.FileSystemView;
import sun.awt.shell.ShellFolder;
public class FileIconExtractor extends JFrame implements ActionListener{
private JButton getIconBtn = new JButton("get Icon");
private JPanel iconPanel = new JPanel();
private JTextField extField = new JTextField();
private JLabel smallIconLabel = new JLabel("small Icon here");
private JLabel bigIconLabel = new JLabel("big Icon here");
public FileIconExtractor() {
this.setSize(200, 150);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new BorderLayout());
getIconBtn.setActionCommand("GETICON");
getIconBtn.addActionListener(this);
iconPanel.setLayout(new BoxLayout(iconPanel, BoxLayout.Y_AXIS));
iconPanel.add(smallIconLabel);
iconPanel.add(bigIconLabel);
this.add(extField, BorderLayout.NORTH);
this.add(iconPanel, BorderLayout.CENTER);
this.add(getIconBtn, BorderLayout.SOUTH);
this.setVisible(true);
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("GETICON")) {
String ext = extField.getText();
File file;
try
file = File.createTempFile("icon", "." + ext);
FileSystemView view = FileSystemView.getFileSystemView();
Icon smallIcon = view.getSystemIcon(file);
ShellFolder shellFolder = ShellFolder.getShellFolder(file);
Icon bigIcon = new ImageIcon(shellFolder.getIcon(true));
setIconLabel(smallIcon, bigIcon);
file.delete();
catch (IOException ioe)
ioe.printStackTrace();
private void setIconLabel(Icon smallIcon, Icon bigIcon) {
smallIconLabel.setIcon(smallIcon);
bigIconLabel.setIcon(bigIcon);
public static void main(String[] args) {
FileIconExtractor fie = new FileIconExtractor();
} -
Change The Icon Of JOptionPane
Can anybody tell me how can I chnage the Icon of JOptionPane ,
I would like to chnage the default Icons come with Java, I want my own Icons to be displayed
Thanx in advance
priteshhi,
just use those static showXXXDialog() methods that expect a javax.swing.Icon as parameter, such as:
JOptionPane.showMessageDialog(null, "My message", "My title", JOptionPane.INFORMATION_MESSAGE, new ImageIcon("info.gif"));
Or use the showOptionDialog() method that provides similar features.
sincerely Michael -
JButton with auto resizing icon
Hi,
I want to extend the JButon in order to make it auto resize the icon image to the button size itself.
I tried somethink like the following code and it work but there is some recursive side effect I cannot understand becouse I get a 100% CPU usage and from the print() I see the paint() method is called continuosly.
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
public class IconButton extends JButton {
private static final long serialVersionUID = 4049919355141829686L;
int cntr;
public IconButton(ImageIcon icon) {
super(icon);
public void paintComponent(Graphics g) {
System.out.println(cntr++);
Icon icn = getIcon();
if (icn instanceof ImageIcon) {
ImageIcon ii = (ImageIcon)icn;
Image img = ii.getImage();
img = img.getScaledInstance(getWidth(), getHeight(), Image.SCALE_AREA_AVERAGING);
icn = new ImageIcon(img);
super.setIcon(icn);
super.paintComponent(g);
Maybe there's a better way... for example by changing the icon only when the button size change: but how?
Thank in advance,
Carlo.ok,
the question is:
how to have a Button with the icon automatically resized to the button size? Is it right to extends JButton or is better extends AbstractButton?
thanks.
Maybe you are looking for
-
FIle Content Conversion Problem in IDOC-XI-File Scenario
Dear All, I am doing IDOC-XI-FILE scenario. I am facing one problem related to File Content Coversion.My requirement was to generate a dynamic file like <b>%store_code%_%current_date%_sitemaster.xml</b> , I have completed the dynamic generation succe
-
Third-generation iPod appears in "My Computer" but not iTunes
I am sure this problem has been brought up many times before, but my iPod is not showing up in my iTunes but does appear in my My Computer folder. I have tried the troubleshooting options available on the Apple support page and have done other web se
-
How to Include in Customer Exit to select max of the date
Hi, Every Employee will have a health Insurance Policy which is valid for 6 six months. From Source System i am getting Employee and his policy Start date,Based on Policy Start Date in Transformations i am calculacting the Policy Expiry date (Policy
-
So here I am, all hyped up by Adobe's message in my inbox about all the new features. Err, Download Error. Please! Any other Mac users grinding their teeth? Come on Adobe, I'm paying almost £50 a month for this...
-
How do I get Active X control for flash player registered?
I have been having problems with flashplayer. I continue to get different messages when I try to download. The latest message is: Active X control for flash player could not be registered. What do I do to get the system working?