JLabel painting

ok i have a simple CLass that expands JLabel which creates a class box style image on a JLabel (which makes it simple for me to drag it around on a JPanel) however i have two problems
- i am unsure of how to adapt it so that the graphic i draw takes into account newlines in the strings
- and more importantly i wish to be able to make the image be smaller depandant on a value so in other words have a small button in the top left corner of the image which specifies if the image is maximised or minimised however i obviously cant as you cannot add buttons to JLabels does any 1 havee ne idea of how i could achive this?
Below is my current paint method
public void paintComponent(Graphics g) {
          g.setFont(theFont);
          FontMetrics fm = g.getFontMetrics();
          int[] width1 = new int[2];
          int width;
          width = fm.stringWidth(name);
          width1[0] = fm.stringWidth(attributes);
          width1[1] = fm.stringWidth(methods);
          for (int i = 0; i < 2; i++)
               if (width1[i] > width)
                    width = width1;
          if (width < 50)
               width = 50;
          int height = fm.getHeight();
          g.drawRect(x, y, width, height);
          g.drawRect(x, y + height, width, height);
          g.drawRect(x, y + (height * 2), width, height);
          g.drawString(name, x + 1, y + height - 4);
          g.drawString(attributes, x + 1, y + (2 * height) - 4);
          g.drawString(methods, x + 1, y + (3 * height) - 4);

ok i have the second point working i just need some ideas how i can make the painting take into account newlines without me having to go through each string and find them.

Similar Messages

  • Repaint problem. Paint two components at different times.

    I have two labels on a panel. I want to paint them one by one after some action. However, I found that even I call the repaint method of the first label and after some time call the repaint method of the second label, stilll they change at the same time. The first label will wait until the second label repaints.
    Below is my code:
    import java.awt.event.*;
    import javax.swing.*;
    public class PaintTest extends JPanel {
         JButton paintButton = new JButton("paint");
         JLabel labelOne = new JLabel("Paint first");
         JLabel labelTwo = new JLabel("Paint second");
         public PaintTest() {
              add (paintButton);
              add (labelOne);
              add (labelTwo);
              paintButton.addActionListener(new ActionListener() {
                   public void actionPerformed (ActionEvent evt) {
                        paintButton_actionPerformed (evt);               
         void paintButton_actionPerformed(ActionEvent evt) {
              labelOne.setText("first");
              labelOne.repaint();
              labelOne.revalidate();
              this.repaint();
              this.revalidate();          
              // wait for some time.
              for (long i = 0; i < 99999999; i++) {
              labelTwo.setText("second");
              labelTwo.repaint();
         public static void main(String[] args) {
              JFrame f = new JFrame();
              f.setContentPane(new PaintTest());
              f.pack();
              f.show();
    }

    The reason its not being updated is because ur not realeasing ur current thread, ur making it work - the time it waits is actually working, so ur not allowing the painting thread to cut in and do the painting. Try this instead:
    Implement runnable with:
    public void run() {
    for (long i = 0; i < 99999999; i++) {}
         labelTwo.setText("second");
         labelTwo.repaint();
         repaint();
         revalidate();
    }and in ur actionPerformed:
    labelOne.setText("first");
    labelOne.repaint();
    labelOne.revalidate();
    repaint();
    revalidate();
    SwingUtilities.invokeLater(this);This will give the paiting thread time to repaint before u do u waiting-work....
    Stig.

  • Drawing swing components

    I should know how to do this!!
    How can I draw a swing component i.e. a JLabel, onto a panel (in this case a BufferedImage) using the Graphics package?
    Thanks!
    Alastair

    I've tried the JLabel.paint() method, but it doesn't seem to be working.
    Here is the complete code:
         public static void main(String[] args)
              BufferedImage bi = new BufferedImage(500, 400, BufferedImage.TYPE_INT_RGB);
              Graphics g = bi.getGraphics();
              Color backgroundColor = new Color(210,241,239);
              g.setColor(backgroundColor);
              g.fillRect(0,0,500,400);
              Color titleBarColor = new Color(205,251,174);
              g.setColor(titleBarColor);
              g.fillRect(0,0,500,27);
              g.setColor(Color.BLACK);
              JLabel theLabel = new JLabel();          
              theLabel.setText("Name:");
              theLabel.setLocation(100,100);
              theLabel.paint(g); 
              try
                   File outputFile = new File("c:\\output.PNG");
                   RenderedImage renderedImage = bi;
                   ImageIO.write(renderedImage, "png", outputFile);
              catch(Exception e)
                   System.out.println(e);
         }When I open the image outputed, the label doesn't seem to have been painted to it...

  • Imitate a HyperLink?

    I'm trying to create a component that has behavior that will imitate a typical hyperlink. I can initiallize it and draw it just fine, but I'm not sure how to handle events (and there are a lot of events to handle):
    mouse over - draw the link with its mouseover effects, and change cursor to a hand
    mouse out - draw the link in its original form, set cursor to default
    mouse click - generate an event that reports the action the program should complete
    and others that I should be able to figure out once I get those going. To keep things simple, it would be best for the HyperLink class to handle most of the mouse events internally (all but mouse click I assume). I have searched the forums and google, but it seems that no one has a good example of how to do this. Please offer your suggestions.
    Thanks!

    Here's another version that doesn't use HTML. It overrides the JLabel paint() method to underline the text. Also, it lets you register an ActionListener and notifies you when the link is clicked.
    import java.awt.Color;
    import java.awt.Cursor;
    import java.awt.Graphics;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.geom.Rectangle2D;
    import java.util.LinkedList;
    import javax.swing.BoxLayout;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    public class JHyperLink extends JLabel {
      protected final Color LINK_COLOR  = Color.blue;
      protected LinkedList<ActionListener> actionListenerList = new LinkedList<ActionListener>();
      protected boolean underline;
      protected MouseListener mouseListener = new MouseAdapter() {
        public void mouseEntered(MouseEvent me) {
          underline = true;
          repaint();
        public void mouseExited(MouseEvent me) {
          underline = false;
          repaint();
        public void mouseClicked(MouseEvent me)
          fireActionEvent();
      public JHyperLink()
        this("");
      public JHyperLink(String text)
        super(text);
        setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        setForeground(LINK_COLOR);
        addMouseListener( mouseListener );
      public void addActionListener(ActionListener l)
        if(!actionListenerList.contains( l )) {
          actionListenerList.add( l );
      public void removeActionListener(ActionListener l)
        actionListenerList.remove( l );   
      protected void fireActionEvent()
        ActionEvent e = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, getText());
        for(ActionListener l : actionListenerList ) {
          l.actionPerformed( e );
      public void paint(Graphics g)
        super.paint(g);
        if (underline)
            // really all this size stuff below only needs to be recalculated if font or text changes
           Rectangle2D textBounds =  getFontMetrics(getFont()).getStringBounds(getText(), g);
            //this layout stuff assumes the icon is to the left, or null
           int y = getHeight()/2 + (int)(textBounds.getHeight()/2);
           int w = (int) textBounds.getWidth();
           int x = getIcon()==null ? 0 : getIcon().getIconWidth() + getIconTextGap();
           g.setColor(getForeground());
           g.drawLine(0, y, x + w, y);
      public static void main ( String[] args )
        JFrame f = new JFrame("Test");
        JHyperLink link = new JHyperLink("This is a link");
        link.addActionListener( new ActionListener() {
          public void actionPerformed ( ActionEvent e )
            System.out.println("Link clicked: " + e);   
        f.getContentPane().setLayout( new BoxLayout( f.getContentPane(), BoxLayout.LINE_AXIS )  );
        f.getContentPane().add( link );
        f.pack();
        f.setVisible( true );
        link.setMaximumSize( link.getSize() );
    }

  • Painting GIF images/using JLabels for GIFs... Somehow, make it work!

    Ok, I am basically making an arena for a local multiplayer game for my friends, and across the top of the screen is a title ... lets call the title "Game Title". The entire game is contained in 1 JFrame, including the title, sidebars, and the actual "game" part in the middle. I paint all of the objects in the game by painting them in the JFrame's Graphics when the paint() method is called.
    Basically, the window looks like this:
    | /\./\./\./\./\....Game Title..../\./\./\./\./\ |
    |...........______________..............|
    |...........|.--.game area.--..|..............|
    |...........|_____________|..............|
    Where the /\./\./\'s are animated flames. I have tried to just make them as ImageIcons in JLabels, but no matter what I paint() after the labels are added, the window looks like this:
    | /\./\./\./\./\ .......................... /\./\./\./\./\ |
    |.........................................................|
    |.........................................................|
    |.........................................................|
    Where the flames are animated, but the "background" is always gray. I then tried to paint them as Images (g.drawImage(new ImageIcon(url).getImage(),0,0,null), but that only leaves the first frame of the animated GIF (in other words, its not animated).
    What do I do? I have been reading around the forums, but I cannot find a case where somebody needed the GIF inside a Component that they used for painting...
    Thanks for any help that you give!

    If you're going to paint use a graphic component to do your painting in and don't add any components to it. The 'paint' method in JFrame is called by swing to draw the JFrame and its components. Using it to do custom painting is tricky. You'll need to call 'super.paint' to allow the container to paint its children. See the method detail in the JFrame api (link is in the Container section of the api). Also check the 'paintComponent' and 'paint' methods in the JComponent api method details section.
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    public class Painting extends JPanel
        BufferedImage image;
        public Painting(BufferedImage image)
            this.image = image;
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            g.drawImage(image, 125, 175, this);
        private JPanel getTitlePanel()
            JLabel title = new JLabel("Game Title", JLabel.CENTER);
            JLabel flame1 = new JLabel("flames");
            JLabel flame2 = new JLabel("flames");
            JPanel panel = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.weightx = 1.0;
            panel.add(flame1, gbc);
            panel.add(title, gbc);
            panel.add(flame2, gbc);
            return panel;
        public static void main(String[] args) throws IOException
            String path = "images/Bird.gif";
            BufferedImage bi = ImageIO.read(Painting.class.getResource(path));
            Painting painting = new Painting(bi);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(painting.getTitlePanel(), "North");
            f.getContentPane().add(painting);
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    }

  • JLabel background color wont paint in JLayerPane

    I tried to use JLayeredPane to display some color label by setting a background color for the label. However, label's background never appear on the screen. I couldn't fix it. Please help!!

    Try yourLabel.setOpaque(true).
    Shaun

  • Programming a Pencil Tool on Paint?

    Here's my code for Scribble(a pencil tool) and its superclass Shape. Basically, my program remembers where the mouse has been and draws a line from the previous point to the current point. However, the scribble doesn't show up (occasionally you will see a small line at the very end) I think the problem is that each Scribble object only has one previous and one current. Therefore, there is only 1 line left at the end. How can I correct this?
    Thanks in advance!
    Note: this doesn't run since there are about 5 other classes needed. I guess can post them if you want? xD
    import java.awt.*;
    public class Scribble extends Shape{
         protected Point startpt, endpt;
         protected Point previous, current;
         int count = 0;
        public Scribble(Point start, DrawingCanvas dcanvas){
         super();
         System.out.println("SCRIBBLE CREATED!!!!!!!\n\n");
         startpt = start;
         current = start;
         endpt = start;
         canvas = dcanvas;
         bounds = new Rectangle(start);
        public void resize(Point anchor, Point end){
         super.resize(anchor, end);
         previous = current;
         startpt = anchor;
         current = end;
         endpt = end;
        public void translate(int dx, int dy){
         super.translate(dx, dy);
         previous.translate(dx, dy);
         current.translate(dx, dy);
         startpt.translate(dx, dy);
         endpt.translate(dx, dy);
        public void draw(Graphics g, Rectangle regionToDraw){
              count++;
              System.out.println(count);
         if (!bounds.intersects(regionToDraw)){
             return;
         g.setColor(super.getColor());
         g.drawLine((int)previous.getX(), (int)previous.getY(), (int)current.getX(), (int)current.getY());
         if (isSelected) { // if selected, draw the resizing knobs
                           // along the 4 corners
             Rectangle[] knobs = getKnobRects();
             for (int i = 0; i < knobs.length; i++)
              g.fillRect(knobs.x, knobs[i].y,
                   knobs[i].width, knobs[i].height);
    protected Rectangle[] getKnobRects(){
         Rectangle[] knobs = new Rectangle[2];
         knobs[0] = new Rectangle((int)startpt.getX() - KNOB_SIZE/2,
                        (int)startpt.getY() - KNOB_SIZE/2, KNOB_SIZE, KNOB_SIZE);
         knobs[1] = new Rectangle((int)endpt.getX() - KNOB_SIZE/2,
                        (int)endpt.getY()- KNOB_SIZE/2, KNOB_SIZE, KNOB_SIZE);
         return knobs;
    protected int getKnobContainingPoint(Point pt){
         if (!isSelected) return NONE;
         Rectangle[] knobs = getKnobRects();
         for (int i = 0; i < knobs.length; i++)
         if (knobs[i].contains(pt))
              return i;
         return NONE;
    }import java.awt.*;
    import java.util.*;
    import java.io.*;
    public abstract class Shape implements Serializable, Cloneable{
         private Color color;
    protected Rectangle bounds;
    protected boolean isSelected;
    public DrawingCanvas canvas;
    protected static final int KNOB_SIZE = 6;
    protected static final int NONE = -1;
    protected static final int NW = 0;
    protected static final int SW = 1;
    protected static final int SE = 2;
    protected static final int NE = 3;
         Shape(){
              color = Color.darkGray;
         public Color getColor(){
         return color;
         public Object clone(){
              try{
              Shape copy = (Shape)super.clone();
              copy.setBounds(bounds);
              return copy;
              catch(CloneNotSupportedException c){
                   return null;
         public void setColor(Color newColor){
         color = newColor;
         canvas.repaint();
         /** The "primitive" for all resizing/moving/creating operations that
         * affect the rect bounding box. The current implementation just resets
         * the bounds variable and triggers a re-draw of the union of the old &
         * new rectangles. This will redraw the shape in new size and place and
         * also "erase" if bounds are now smaller than before.
         protected void setBounds(Rectangle newBounds){
              Rectangle oldBounds = bounds;
              bounds = newBounds;
              updateCanvas(oldBounds.union(bounds));
         /** The resize operation is called when first creating a rect, as well as
         * when later resizing by dragging one of its knobs. The two parameters
         * are the points that define the new bounding box. The anchor point
         * is the location of the mouse-down event during a creation operation
         * or the opposite corner of the knob being dragged during a resize
         * operation. The end is the current location of the mouse.
         public void resize(Point anchor, Point end){
              Rectangle newRect = new Rectangle(anchor);
              // creates smallest rectange which
              // includes both anchor & end
              newRect.add(end);
              // reset bounds & redraw affected areas
              setBounds(newRect);
              canvas.repaint();
         /** The translate operation is called when moving a shape by dragging in
         * the canvas. The two parameters are the delta-x and delta-y to move
         * by. Note that either or both can be negative. Create a new rectangle
         * from our bounds and translate and then go through the setBounds()
         * primitive to change it.
         public void translate(int dx, int dy){
              Rectangle newRect = new Rectangle(bounds);
              newRect.translate(dx, dy);
              setBounds(newRect);
              canvas.repaint();
         /** Used to change the selected state of the shape which will require
         * updating the affected area of the canvas to add/remove knobs.
         public void setSelected(boolean newState){
              isSelected = newState;
              // need to erase/add knobs
              // including extent of extended bounds
              updateCanvas(bounds, true);
              canvas.repaint();
         /** The updateCanvas() methods are used when the state has changed
         * in such a way that it needs to be refreshed in the canvas to properly
         * reflect the new settings. The shape should take responsibility for
         * messaging the canvas to properly update itself. The appropriate AWT/JFC
         * way to re-draw a component is to send it the repaint() method with the
         * rectangle that needs refreshing. This will cause an update() event to
         * be sent to the component which in turn will call paint(), where the
         * real drawing implementation goes. See the paint() method in
         * DrawingCanvas to see how it is implemented.
         protected void updateCanvas(Rectangle areaOfChange, boolean enlargeForKnobs){
                   System.out.println("canvas2 updated");
              Rectangle toRedraw = new Rectangle(areaOfChange);
              if (enlargeForKnobs)
              toRedraw.grow(KNOB_SIZE/2, KNOB_SIZE/2);
              canvas.repaint(toRedraw);
         protected void updateCanvas(Rectangle areaOfChange){
                   System.out.println("canvas updated");
              updateCanvas(areaOfChange, isSelected);
              public Rectangle getBounds(){
                   return bounds;
         /** When the DrawingCanvas needs to determine which shape is under
         * the mouse, it asks the shape to determine if a point is "inside".
         * This method should returns true if the given point is inside the
         * region for this shape. For a rectangle, any point within the
         * bounding box is inside the shape.
         public boolean inside(Point pt){
              return bounds.contains(pt);
         /** When needed, we create the array of knob rectangles on demand. This
         * does mean we create and discard the array and rectangles repeatedly.
         * These are small objects, so perhaps it is not a big deal, but
         * a valid alternative would be to store the array of knobs as an
         * instance variable of the Shape and and update the knobs as the bounds
         * change. This means a little more memory overhead for each Shape
         * (since it is always storing the knobs, even when not being used) and
         * having that redundant data opens up the possibility of bugs from
         * getting out of synch (bounds move but knobs didn't, etc.) but you may
         * find that a more appealing way to go. Either way is fine with us.
         * Note this method provides a nice unified place for one override from
         * a shape subclass to substitute fewer or different knobs.
         protected Rectangle[] getKnobRects(){
                   System.out.println("knobs gotten");
              Rectangle[] knobs = new Rectangle[4];
              knobs[NW] = new Rectangle(bounds.x - KNOB_SIZE/2,
                             bounds.y - KNOB_SIZE/2, KNOB_SIZE, KNOB_SIZE);
              knobs[SW] = new Rectangle(bounds.x - KNOB_SIZE/2,
                             bounds.y + bounds.height - KNOB_SIZE/2,
                             KNOB_SIZE, KNOB_SIZE);
              knobs[SE] = new Rectangle(bounds.x + bounds.width - KNOB_SIZE/2,
                             bounds.y + bounds.height - KNOB_SIZE/2,
                             KNOB_SIZE, KNOB_SIZE);
              knobs[NE] = new Rectangle(bounds.x + bounds.width - KNOB_SIZE/2,
                             bounds.y - KNOB_SIZE/2,
                             KNOB_SIZE, KNOB_SIZE);
              return knobs;
         /** Helper method to determine if a point is within one of the resize
         * corner knobs. If not selected, we have no resize knobs, so it can't
         * have been a click on one. Otherwise, we calculate the knob rects and
         * then check whether the point falls in one of them. The return value
         * is one of NW, NE, SW, SE constants depending on which knob is found,
         * or NONE if the click doesn't fall within any knob.
         protected int getKnobContainingPoint(Point pt){
                   System.out.println("resize knobs");
              // if we aren't selected, the knobs
              // aren't showing and thus there are no knobs to check
              if (!isSelected) return NONE;
              Rectangle[] knobs = getKnobRects();
              for (int i = 0; i < knobs.length; i++)
              if (knobs[i].contains(pt))
                   return i;
              return NONE;
         /** Method used by DrawingCanvas to determine if a mouse click is starting
         * a resize event. In order for it to be a resize, the click must have
         * been within one of the knob rects (checked by the helper method
         * getKnobContainingPoint) and if so, we return the "anchor" ie the knob
         * opposite this corner that will remain fixed as the user drags the
         * resizing knob of the other corner around. During the drag actions of a
         * resize, that fixed anchor point and the current mouse point will be
         * passed to the resize method, which will reset the bounds in response
         * to the movement. If the mouseLocation wasn't a click in a knob and
         * thus not the beginning of a resize event, null is returned.
    public Point getAnchorForResize(Point mouseLocation){
              System.out.println("is it a resize?");
    int whichKnob = getKnobContainingPoint(mouseLocation);
    if (whichKnob == NONE) // no resize knob is at this location
    return null;
    Rectangle[] knobs = getKnobRects();
    whichKnob = Math.abs(whichKnob - (int)(knobs.length / 2));
    return (new Point(knobs[whichKnob].x + knobs[whichKnob].width /2,
    knobs[whichKnob].y + knobs[whichKnob].height/2));
    public abstract void draw(Graphics g, Rectangle regionToDraw);

    line left at the end. How can I correct this?java.awt.Polygon (or Polygon2D)
    Here are a few of my thoughts
    #1 There is a Shape interface in core java already, as well as plenty of very useful shapes (Rectangle, Ellipse2D, Area). Shape has some really nice features like contains(...) and intersects(...). By creating a separate class for your Shape objects, you ensure that the two will be incompatible.
    #2 As tempting as it is, it is a bad idea to include a Color with a shape. What if you want it to have more than one Color? What if you want the insides of the shape to be filled by an Image? I just created and posted a class on the java forums called Renderable, which combines a java.awt.Shape with a java.awt.Paint.
    #3 Below is my PaintArea class. It "scribbles" on an Image. Maybe this will give you some ideas. To compile it, you will either have to find my MathUtils class (which I've posted here before) or reimplement the distance and angle methods. There is also a reference to WIndowUtilities... find that or remove it and put the PaintArea in a Frame and do setVisible(true)
    You are welcome to use and modify this code, but please don't change the package and please make sure that you add attribution if you submit this in an academic setting.
    * Created on Jun 15, 2005 by @author Tom Jacobs
    package tjacobs.ui.ex;
    import java.awt.image.BufferedImage;
    import java.awt.*;
    import java.awt.event.*;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import javax.swing.ImageIcon;
    import javax.swing.JComboBox;
    import javax.swing.JComponent;
    import javax.swing.JPanel;
    import javax.swing.JToolBar;
    import tjacobs.MathUtils;
    import tjacobs.ui.util.WindowUtilities;
    * PaintArea is a component that you can draw in similar to but
    * much simpler than the windows paint program.
    public class PaintArea extends JComponent {
         private static final long serialVersionUID = 0;
         BufferedImage mImg; //= new BufferedImage();
         int mBrushSize = 1;
         private boolean mSizeChanged = false;
         private Color mColor1, mColor2;
         static class PaintIcon extends ImageIcon {
              public static final long serialVersionUID = 0;
              int mSize;
              public PaintIcon(Image im, int size) {
                   super(im);
                   mSize = size;
         public PaintArea() {
              super();
              setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
              addComponentListener(new CListener());
              MListener ml = new MListener();
              addMouseListener(ml);
              addMouseMotionListener(ml);
              setBackground(Color.WHITE);
              setForeground(Color.BLACK);
         public void paintComponent(Graphics g) {
              if (mSizeChanged) {
                   handleResize();
              //g.drawImage(mImg, mImg.getWidth(), mImg.getHeight(), null);
              g.drawImage(mImg, 0, 0, null);
              //super.paintComponent(g);
              //System.out.println("Image = " + mImg);
              //System.out.println("Size: " + mImg.getWidth() + "," + mImg.getHeight());
         public void setBackground(Color c) {
              super.setBackground(c);
              if (mImg != null) {
                   Graphics g = mImg.getGraphics();
                   g.setColor(c);
                   g.fillRect(0, 0, mImg.getWidth(), mImg.getHeight());
                   g.dispose();
         public void setColor1(Color c) {
              mColor1 = c;
         public void setColor2(Color c) {
              mColor2 = c;
         public Color getColor1() {
              return mColor1;
         public Color getColor2() {
              return mColor2;
         class ToolBar extends JToolBar {
              private static final long serialVersionUID = 1L;
              ToolBar() {
                   final ColorButton fore = new ColorButton();
                   fore.setToolTipText("Foreground Color");
                   final ColorButton back = new ColorButton();
                   back.setToolTipText("Background Color");
                   JComboBox brushSize = new JComboBox();
                   //super.createImage(1, 1).;
                   FontMetrics fm = new FontMetrics(getFont()) {
                        private static final long serialVersionUID = 1L;};
                   //int ht = fm.getHeight();
                   int useheight = fm.getHeight() % 2 == 0 ? fm.getHeight() + 1 : fm.getHeight();
                   final BufferedImage im1 = new BufferedImage(useheight, useheight, BufferedImage.TYPE_INT_RGB);
                   Graphics g = im1.getGraphics();
                   g.setColor(Color.WHITE);
                   g.fillRect(0, 0, useheight, useheight);
                   g.setColor(Color.BLACK);
                   g.fillOval(useheight / 2, useheight / 2, 1, 1);
                   g.dispose();
                   //im1.setRGB(useheight / 2 + 1, useheight / 2 + 1, 0xFFFFFF);
                   final BufferedImage im2 = new BufferedImage(useheight, useheight, BufferedImage.TYPE_INT_RGB);
                   g = im2.getGraphics();
                   g.setColor(Color.WHITE);
                   g.fillRect(0, 0, useheight, useheight);
                   g.setColor(Color.BLACK);
                   g.fillOval(useheight / 2 - 1, useheight / 2 - 1, 3, 3);
                   g.dispose();
    //               im2.setRGB(useheight / 2 - 1, useheight / 2 - 1, 3, 3, new int[] {     0, 0xFFFFFF, 0,
    //                                                            0xFFFFFF, 0xFFFFFFF, 0xFFFFFF,
    //                                                            0, 0xFFFFFF, 0}, 0, 1);
                   final BufferedImage im3 = new BufferedImage(useheight, useheight, BufferedImage.TYPE_INT_RGB);
                   g = im3.getGraphics();
                   g.setColor(Color.WHITE);
                   g.fillRect(0, 0, useheight, useheight);
                   g.setColor(Color.BLACK);
                   g.fillOval(useheight / 2 - 2, useheight / 2 - 2, 5, 5);
                   g.dispose();
    //               im3.setRGB(useheight / 2 - 2, useheight / 2 - 2, 5, 5, new int[] {     0, 0, 0xFFFFFF, 0, 0, 
    //                                                            0, 0xFFFFFF, 0xFFFFFFF, 0xFFFFFF, 0,
    //                                                            0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF,
    //                                                            0, 0xFFFFFF, 0xFFFFFFF, 0xFFFFFF, 0,
    //                                                            0, 0, 0xFFFFFF, 0, 0}, 0, 1);
                   //JLabel l1 = new JLabel("1 pt", new ImageIcon(im1), JLabel.LEFT);
                   //JLabel l2 = new JLabel("3 pt", new ImageIcon(im2), JLabel.LEFT);
                   //JLabel l3 = new JLabel("5 pt", new ImageIcon(im3), JLabel.LEFT);
                   brushSize.addItem(new PaintIcon(im1, 1));
                   brushSize.addItem(new PaintIcon(im2, 3));
                   brushSize.addItem(new PaintIcon(im3, 5));
                   //brushSize.addItem("Other");
                   add(fore);
                   add(back);
                   add(brushSize);
                   PropertyChangeListener pl = new PropertyChangeListener() {
                        public void propertyChange(PropertyChangeEvent ev) {
                             Object src = ev.getSource();
                             if (src != fore && src != back) {
                                  return;
                             Color c = (Color) ev.getNewValue();
                             if (ev.getSource() == fore) {
                                  mColor1 = c;
                             else {
                                  mColor2 = c;
                   fore.addPropertyChangeListener("Color", pl);
                   back.addPropertyChangeListener("Color", pl);
                   fore.changeColor(Color.BLACK);
                   back.changeColor(Color.WHITE);
                   brushSize.addItemListener(new ItemListener() {
                        public void itemStateChanged(ItemEvent ev) {
                             System.out.println("ItemEvent");
                             if (ev.getID() == ItemEvent.DESELECTED) {
                                  return;
                             System.out.println("Selected");
                             Object o = ev.getItem();
                             mBrushSize = ((PaintIcon) o).mSize;
                   //Graphics g = im1.getGraphics();
                   //g.fillOval(0, 0, 1, 1);
                   //BufferedImage im1 = new BufferedImage();
                   //BufferedImage im1 = new BufferedImage();
         protected class MListener extends MouseAdapter implements MouseMotionListener {
              Point mLastPoint;
              public void mouseDragged(MouseEvent me) {
                   Graphics g = mImg.getGraphics();
                   if ((me.getModifiers() & InputEvent.BUTTON1_MASK) != 0) {
                        g.setColor(mColor1);
                   } else {
                        g.setColor(mColor2);
                   Point p = me.getPoint();
                   if (mLastPoint == null) {
                        g.fillOval(p.x - mBrushSize / 2, p.y - mBrushSize / 2, mBrushSize, mBrushSize);
                        //g.drawLine(p.x, p.y, p.x, p.y);
                   else {
                        g.drawLine(mLastPoint.x, mLastPoint.y, p.x, p.y);
                        //g.fillOval(p.x - mBrushSize / 2, p.y - mBrushSize / 2, mBrushSize, mBrushSize);
                        double angle = MathUtils.angle(mLastPoint, p);
                        if (angle < 0) {
                             angle += 2 * Math.PI;
                        @SuppressWarnings("unused")
                        double distance = MathUtils.distance(mLastPoint, p) * 1.5;
                        if (angle < Math.PI / 4 || angle > 7 * Math.PI / 4 || Math.abs(Math.PI - angle) < Math.PI / 4) {
                             for (int i = 0; i < mBrushSize / 2; i ++) {
                                  g.drawLine(mLastPoint.x, mLastPoint.y + i, p.x, p.y + i);
                                  g.drawLine(mLastPoint.x, mLastPoint.y - i, p.x, p.y - i);
    //                              System.out.println("y");
    //                              System.out.println("angle = " + angle / Math.PI * 180);
                        else {
                             for (int i = 0; i < mBrushSize / 2; i ++) {
                                  g.drawLine(mLastPoint.x + i, mLastPoint.y, p.x + i, p.y);
                                  g.drawLine(mLastPoint.x  - i, mLastPoint.y, p.x - i, p.y);
    //                              System.out.println("x");
    //                    System.out.println("new = " + PaintUtils.printPoint(p));
    //                    System.out.println("last = " + PaintUtils.printPoint(mLastPoint));
                        //System.out.println("distance = " + distance);
                        //Graphics2D g2 = (Graphics2D) g;
                        //g2.translate(mLastPoint.x + mBrushSize / 2, mLastPoint.y);
                        //g2.rotate(angle);
                        //g2.fillRect(0, 0, (int) Math.ceil(distance), mBrushSize);
                        //g2.rotate(-angle);
                        //g2.translate(-mLastPoint.x + mBrushSize / 2, -mLastPoint.y);
    //                    g.setColor(Color.RED);
    //                    g.drawRect(p.x, p.y, 1, 1);
                   mLastPoint = p;
                   g.dispose();
                   repaint();
              public void mouseMoved(MouseEvent me) {}
              public void mouseReleased(MouseEvent me) {
                   mLastPoint = null;
         private void handleResize() {
              Dimension size = getSize();
              mSizeChanged = false;
              if (mImg == null) {
                   mImg = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB);
                   Graphics g = mImg.getGraphics();
                   g.setColor(getBackground());
                   g.fillRect(0, 0, mImg.getWidth(), mImg.getHeight());
                   g.dispose();
              else {
                   int newWidth = Math.max(mImg.getWidth(),getWidth());
                   int newHeight = Math.max(mImg.getHeight(),getHeight());
                   if (newHeight == mImg.getHeight() && newWidth == mImg.getWidth()) {
                        return;
                   BufferedImage bi2 = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
                   Graphics g = bi2.getGraphics();
                   g.setColor(getBackground());
                   g.fillRect(0, 0, bi2.getWidth(), bi2.getHeight());
                   g.drawImage(mImg, mImg.getWidth(), mImg.getHeight(), null);
                   g.dispose();
                   mImg = bi2;
         public JToolBar getToolBar() {
              if (mToolBar == null) {
                   mToolBar = new ToolBar();
              return mToolBar;
         private ToolBar mToolBar;
         public static void main (String args[]) {
              PaintArea pa = new PaintArea();
              JPanel parent = new JPanel();
              parent.setLayout(new BorderLayout());
              parent.add(pa, BorderLayout.CENTER);
              pa.setPreferredSize(new Dimension(150, 150));
              parent.add(pa.getToolBar(), BorderLayout.NORTH);
              WindowUtilities.visualize(parent);
         protected class CListener extends ComponentAdapter {
              public void componentResized(ComponentEvent ce) {
                   mSizeChanged = true;
    }

  • Problem with HTML in a JLabel

    Is it possible to use styles when using HTML in a JLabel?
    Example:
    <html><hr style="height: 1px; color: black;"></html>Doesn't work correctly as this should give a solid 1px high hr, but doesn't. Instead it gives a black hr with a white shade...
    The JLabel it is used in is not customized in any way.

    I too am interested in getting color on an HR to work. Can you summarize what you have done to date? Sample code?
    Note: An easy way to correct it in a Nonframe instance of html is to subclass HTMLEditor to implement your own ViewFactory and own HRuleView which checks the attribute tag color for the color. I've got this to work, but frames don't work since you can call FrameView (not public) and thus have to use the super class - which then by-passes the ViewFactory from then on.
    So a NON-FRAME Solution to give HR color is... Anybody have a better global solution?
    Here is the one line fix to HRuleView .setProperties. So if you subclass HRuleView specifically to do
    public class MyHTMLEditorKit extends HTMLEditorKit { // StyledEditorKit
        private static final ViewFactory defaultFactory = new MyHTMLFactory();
        public static class MyHTMLFactory extends HTMLFactory {//implements ViewFactory {
             public View create(Element elem) {
             Object o = elem.getAttributes().getAttribute(StyleConstants.NameAttribute);
             if (o instanceof HTML.Tag) {
              HTML.Tag kind = (HTML.Tag) o;
              if (kind == HTML.Tag.HR) {
                  return new MyHRuleView(elem);
           return super.create(elem);
    class MyHRuleView extends View  {
         private Color color = null;
         public void setPropertiesFromAttributes() {
              super.setPropertiesFromAttributes();
              try {color = new Color(Integer.decode((String)attr.getAttribute("color")).intValue());} catch (Exception e) {}
         public void paint(Graphics g, Shape a) {
              if (color != null) g.setColor(color);
              super.paint(g, a);
    }

  • Problem with painting/threads/ProgressMonitor

    Hello,
    I'll try to be clear, ask me anything if it isn't. I have two threads, one that downloads some selected webpages, and the other that reads them. In the thread that reads, there is a ProgressMonitor object, which indicate how many webpages have been read.
    I created a JUnit test which works as expected. One thread downloads, the other reads and a nice little progress monitor appears and everything works.
    I transfered the code (the part of the code starting the thread that reads, which starts the thread that downloads) into the main application. The threads are working and the ProgressMonitor appears, but it does not draw the components (there is no label, progress bar, button etc...). I can't seem to find the problem. I think it is caused by the threads or synchronized methods, I am not sure as I am no expert with threads. Once the threads have finished running, the components of the ProgressMonitor appears. So I guess that the threads are blocking the (re)painting of the application, but I can't figure why. Im using Thread.yield() quite often. Priorities problem ? Here some parts of the code :
    JUnit Test code :
         public synchronized void testHarvest() {
              JFrame frame = new JFrame("Super");
              frame.setVisible(true);
              Harvester harvester = new Harvester(
                        frame,
                        new Rule());
              Thread harvest = new Thread(harvester);
              harvest.start();
              try {
                   harvest.join();
              } catch (InterruptedException ie) {}
    ...Main application :
    Code:
    public class Gui extends JFrame implements ComponentListener {
       private static JFrame mMotherFrame = null;
        public Gui() {
            mMotherFrame = this;
        private class GuiActionRealize {
              public synchronized void getFromWeb() {
                   Harvester harvester = new Harvester(
                             mMotherFrame,
                             new Rule());
                   Thread harvest = new Thread(harvester);
                   harvest.start();               
                   try {                    
                        harvest.join();
                   } catch (InterruptedException ie) {}
    }Harvester :
    Code:
    public class Harvester implements Runnable {
      private JFrame mMotherFrame;
      private ProgressMonitor mMonitor;
    public Harvester(JFrame owner, IRule subjectRule) {
       mMotherFrame = owner;
        public void find() {
        mMonitor = new ProgressMonitor(mMotherFrame, "Downloading from the Internet.", "", 1, mAcceptedURLs.size());
         mMonitor.setMillisToDecideToPopup(0);
         mMonitor.setMillisToPopup(0);
    public void run() {
      find();
      mHarvested = harvest();
      mFinished = true;
      Thread.yield();
    public List harvest() {
      download = new DownloadThread(this, mAcceptedURLs);
      Thread downthread = new Thread(download);
      downthread.start(); int i = 0;
      while (!mMonitor.isCanceled()) {
          while (download.getDownloadedDocuments().isEmpty()) {
               try {
                       Thread.yield();
                       Thread.sleep(300);
                } catch (InterruptedException ie) {}
           mMonitor.setNote("Downloading decision " + i);
           mMonitor.setProgress(mMonitor.getMinimum()+ ++i);
           } // end while(!cancel)
           download.kill();
           return mHarvested;
    }I'm very puzzled by the fact that it worked in the JUnit Case and not in the application.
    I can see that the thread that is responsible for drawing components is not doing his job, since that the mother frame (Gui class) is not being repainted while the harvest/download threads are working. That's not the case in the JUnit case, where the frame is being repainted and everything is fine. This is the only place in the application that I'm using threads/runnable objects.
    I also tried making the Gui class a thread by implementing the Runnable interface, and creating the run method with only a repaint() statement.
    And I tried setting the priority of the harvest thread to the minimum. No luck.
    If you need more info/code, let me know, Ill try to give as much info as I can.
    Thank you

    Why are you painting the values yourself? Why don't you just add the selected values to a JList, or create a container with a GridLayout and add a JLabel with the new text to the container.
    Every time you call the paintComponent() method the painting gets done from scratch so you would need to keep a List of selected items and repaint each item every time. Maybe this [url http://forum.java.sun.com/thread.jsp?forum=57&thread=304939]example will give you ideas.

  • Bug: IconUIResource doesn't paint an animated ImageIcon

    I was recently playing with Icons and found that javax.swing.plaf.IconUIResource doesn't paint an ImageIcon that contains an animated GIF. Found the reason in these bug fixes.
    [http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4215118]
    [http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4215118]
    From that, I could arrive at a workaround: extend ImageIcon to implement the UIResource marker interface and use this class instead of wrapping an ImageIcon in a IconUIResource. Interestingly, NetBeans autocomplete revealed the existance of sun.swing.ImageIconUIResource which I determined to be a direct subclass of ImageIcon, with two constructors that take an Image and byte[] respectively.
    Test SSCCE: import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.MalformedURLException;
    import java.net.URL;
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JOptionPane;
    import javax.swing.UIManager;
    import javax.swing.plaf.IconUIResource;
    import javax.swing.plaf.UIResource;
    public class IconUIResourceBug {
      public static void main(String[] args) {
        try {
          URL imageURL = new URL("http://www.smiley-faces.org/smiley-faces/smiley-face-rabbit.gif");
          InputStream is = imageURL.openStream();
          ByteArrayOutputStream baos = new ByteArrayOutputStream();
          int n;
          byte[] data = new byte[1024];
          while ((n = is.read(data, 0, data.length)) != -1) {
            baos.write(data, 0, n);
          baos.flush();
          byte[] bytes = baos.toByteArray();
          ImageIcon imageIcon = new ImageIcon(bytes);
          Icon icon = new IconUIResource(imageIcon);
          UIManager.put("OptionPane.errorIcon", icon);
          JOptionPane.showMessageDialog(null, "javax.swing.plaf.IconUIResource", "Icon not shown",
                  JOptionPane.ERROR_MESSAGE);
          icon = new ImageIconUIResource(bytes);
          UIManager.put("OptionPane.errorIcon", icon);
          JOptionPane.showMessageDialog(null, "ImageIconUIResource", "Icon shown",
                  JOptionPane.ERROR_MESSAGE);
          icon = new sun.swing.ImageIconUIResource(bytes);
          UIManager.put("OptionPane.errorIcon", icon);
          JOptionPane.showMessageDialog(null, "sun.swing.ImageIconUIResource", "Icon shown",
                  JOptionPane.ERROR_MESSAGE);
        } catch (MalformedURLException ex) {
          ex.printStackTrace();
        } catch (IOException ex) {
          ex.printStackTrace();
    class ImageIconUIResource extends ImageIcon implements UIResource {
      public ImageIconUIResource(byte[] bytes) {
        super(bytes);
    }I can't see any alternative fix for the one carried out in response to the quoted bug reports, so have held off on making a bug report. Any ideas?
    Thanks for reading, Darryl
    I'm also posting this to JavaRanch for wider discussion, and shall post the link here as soon as possible. I'll also keep both threads updated with all significant suggestions received.
    edit [http://www.coderanch.com/t/498351/GUI/java/Bug-IconUIResource-doesn-paint-animated]
    Edited by: DarrylBurke

    Animated gif is working fine for me.
    You can check the delay time between the images in the gif, to see that it's not too short.
    Here's a simple example:import java.net.URL;
    import javax.imageio.ImageIO;
    import javax.imageio.stream.ImageInputStream;
    import javax.swing.ImageIcon;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import com.sun.imageio.plugins.gif.GIFImageMetadata;
    import com.sun.imageio.plugins.gif.GIFImageReader;
    public class AnimatedGifTest {
        public static void main(String[] args) {
            try {
                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JDialog.EXIT_ON_CLOSE);
                URL url = new URL("http://www.gifanimations.com/action/SaveImage?path=/Image/Animations/Cartoons/~TS1176984655857/Bart_Simpson_2.gif");
                frame.add(new JLabel(new ImageIcon(url)));
                frame.pack();
                frame.setVisible(true);
                // Read the delay time for the first frame in the animated gif
                GIFImageReader reader = (GIFImageReader) ImageIO.getImageReadersByFormatName("GIF").next();
                ImageInputStream iis = ImageIO.createImageInputStream(url.openStream());
                reader.setInput(iis);
                GIFImageMetadata md = (GIFImageMetadata) reader.getImageMetadata(0);           
                System.out.println("Time Delay = " + md.delayTime);
                reader.dispose();
                iis.close();
            } catch (Exception e) {e.printStackTrace();}
    }

  • JLabel + Animated GIF: replacing the image

    Hi, folks.
    I've run into what looks like an interesting glitch, not necessarily functionality-wise but purely cosmetic.
    I have a JLabel which needs to be switched between a static image and an animated image at different times of execution. I'm doing this more or less like this:
        private JLabel label = new JLabel();
        private ImageIcon inactiveIcon;
        private ImageIcon activeIcon;
        public MyClass()
            inactiveIcon = Utils.loadIcon(...);
            activeIcon = Utils.loadIcon(...);
            setActive(false);
        public void setActive(boolean active)
            label.setIcon(active ? activeIcon : inactiveIcon);
        }It starts up fine and shows the inactive image, which is not animated.
    However, calling setActive(true) seems to cause a flash of grey before showing any animation. The interesting thing is at this point, the image should be completely loaded, so nothing should be blank for any period of time. The other interesting thing is that calling setActive(false) does not cause the flash of grey.
    I've checked the image to make sure all the frames are present and that none are blank.
    I've tried doing this a number of different ways, by Icon.setImage(Image), also by using two labels and setVisible(boolean).
    Has anyone else seen this before? The particular thing which worries me is there isn't a grey flash going the other way. Otherwise I wouldn't think a workaround existed. :-)

    Update. I changed the code to this:
    label = new JLabel() {
    public void update(Graphics g) {
    paint(g);
    public void paint(Graphics g) {
    paintComponent(g);
    protected void paintComponent(Graphics g) {
    ImageIcon icon = (ImageIcon) getIcon();
    icon.paintIcon(this, g, 0, 0);
    };It still greys out. :-/
    I tried label.setUI(new LabelUI() { ... }) with a
    custom paint method also, and it didn't draw anything
    at all, for either label.I'm not sure if you accounted for this but the paint method in the UI is different then the 'public void paintComponent(Graphics g)' method and paint (Graphics g) method in components. The method is 'public void paint(Graphics g, JComponent c)'. Overwriting 'public void paint (Graphics g)' in a UI, is like defining a new method alltogether.
    Did you also make sure to avoid calling 'super.paintComponent()' when overwriting your 'paintComponent(...)' methods? If you did call it, you aren't preventing drawing of previous shapes. This worked for me when I had to do something similar.
    You could also try to draw your icon in your UI, if you haven't done so already.
    Regards,
    Devyn

  • How to print JTextPane containing JTextFields, JLabels and JButtons?

    Hi!
    I want to print a JTextPane that contains components like JTextFields, JLabels and JButtons but I do not know how to do this. I use the print-method that is available for JTextComponent since Java 1.6. My problem is that the text of JTextPane is printed but not the components.
    I wrote this small programm to demonstrate my problem:
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.*;
    import java.awt.print.PrinterException;
    public class TextPaneTest2 extends JFrame {
         private void insertStringInTextPane(String text,
                   StyledDocument doc) {
              try {
                   doc.insertString(doc.getLength(), text, new SimpleAttributeSet());
              catch (BadLocationException x) {
                   x.printStackTrace();
         private void insertTextFieldInTextPane(String text,
                   JTextPane tp) {
              JTextField tf = new JTextField(text);
              tp.setCaretPosition(tp.getDocument().getLength());
              tp.insertComponent(tf);
         private void insertButtonInTextPane(String text,
                   JTextPane tp) {
              JButton button = new JButton(text) {
                   public Dimension getMaximumSize() {
                        return this.getPreferredSize();
              tp.setCaretPosition(tp.getDocument().getLength());
              tp.insertComponent(button);
         private void insertLabelInTextPane(String text,
                   JTextPane tp) {
              JLabel label = new JLabel(text) {
                   public Dimension getMaximumSize() {
                        return this.getPreferredSize();
              tp.setCaretPosition(tp.getDocument().getLength());
              tp.insertComponent(label);
         public TextPaneTest2() {
              StyledDocument doc = new DefaultStyledDocument();
              StyledDocument printDoc = new DefaultStyledDocument();
              JTextPane tp = new JTextPane(doc);
              JTextPane printTp = new JTextPane(printDoc);
              this.insertStringInTextPane("Text ", doc);
              this.insertStringInTextPane("Text ", printDoc);
              this.insertTextFieldInTextPane("Field", tp);
              this.insertTextFieldInTextPane("Field", printTp);
              this.insertStringInTextPane(" Text ", doc);
              this.insertStringInTextPane(" Text ", printDoc);
              this.insertButtonInTextPane("Button", tp);
              this.insertButtonInTextPane("Button", printTp);
              this.insertStringInTextPane(" Text ", doc);
              this.insertStringInTextPane(" Text ", printDoc);
              this.insertLabelInTextPane("Label", tp);
              this.insertLabelInTextPane("Label", printTp);
              this.insertStringInTextPane(" Text Text", doc);
              this.insertStringInTextPane(" Text Text", printDoc);
              tp.setEditable(false);
              printTp.setEditable(false);
              this.getContentPane().add(tp);
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              this.setSize(400,400);
              this.setVisible(true);
              JOptionPane.showMessageDialog(tp, "Start printing");
              try {
                   tp.print();
              } catch (PrinterException e) {
                   e.printStackTrace();
              try {
                   printTp.print();
              } catch (PrinterException e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              new TextPaneTest2();
    }First the components are shown correctly in JTextPane, but when printing is started they vanish. So I created another textPane just for printing. But this does not work either. The components are not printed. Does anybody know how to solve this?
    Thanks!

    I do not know how I should try printComponent. From the API-Doc of JComponent of printComponent: This is invoked during a printing operation. This is implemented to invoke paintComponent on the component. Override this if you wish to add special painting behavior when printing. The method print() in JTextComponent is completely different, it starts the print-job. I do not understand how to try printComponent. It won't start a print-job.

  • How to open a BMP file in a JLabel???

    Hi all,
    My problem is that I want to set a BMP file as icon of a JLabel, but the Class ImageIcon doesn't support BMP files.
    Thank you all.
    Marco Aur�lio
    from Brazil
    we'll win the FIFA World Cup!!

    The easiest way to do that is to get a graphics package that can convert a BMP file to a JPG file. Some versions of Microsoft Paint will do that, but you should be able to find another one if you need it.
    I hope Brazil wins, but if they don't it will be because the referees give it to Korea.

  • JLabel in Rules class won't display

    import java.awt.Dimension;
    import java.awt.Toolkit;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.SwingConstants;
    import Graphics.DrawFrame;
    public class Caller { //driver class
         public static void main(String[] args) { //main method
              int width = 350; //sets width to 350 pixels
              int height = 150; //sets height to 150 pixels
              Toolkit toolkit = Toolkit.getDefaultToolkit(); //creates a Toolkit object
              Dimension dim = toolkit.getScreenSize(); //creates a Dimension object and stores the screen size
              do {
                   //DrawFrame.setDefaultLookAndFeelDecorated(true); //decorates the look and feel
                   DrawFrame frame = new DrawFrame((dim.width-width)/2, (dim.height-height)/2, width, height, "How to Play"); //creates an instance of DrawFrame and sets it in the center of the screen with a height of 300 and a width of 300
                   JButton rules = new JButton("Play"); //creates a newJButton with the text "play"
                   JLabel label = new JLabel("<html>Press ENTER to call a new number.<br>Press R to reset game.<br> The game resets if all 75 numbers have been called.<br> Press H to see this screen again.<br> Click the button or press ENTER to start.", SwingConstants.CENTER); //creates a JLabel that explains the game and centers it in the frame
                   frame.panel.add(label); //adds the label to the frame
                   label.setOpaque(true); //sets the label as opaque
                   label.setVisible(true); //makes the label visible
                   frame.panel.add(rules); //adds the button to the frame
                   rules.setOpaque(true); //sets the button to opaque
                   rules.setVisible(true); //makes the button visible
                   ButtonListener button = new ButtonListener(); //creates instance of ButtonListener class
                   rules.addActionListener(button); //adds an Action Listener to the button
                   frame.getRootPane().setDefaultButton(rules); //sets button as default button (clicks button when user hits ENTER
                   frame.setVisible(true);
                   while (button.source != rules) {//loops if the source of the ActionEvent wasn't the button
                        label.repaint(); //repaints the label
                        rules.repaint(); //repaints the button
                   frame.dispose(); //deletes the frame when the button is clicked
                   Bingo.bingoCaller(); //calls the method in the bingo class
              } while(true); //loops indefinitely
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    public class ButtonListener implements ActionListener { //class implements ActionListener interface
              public Object source; //creates an object of type Object
              public void actionPerformed(ActionEvent e) { //actionPerformed method that has an ActionEvent ofject as an argument
                   source = e.getSource(); //sets the source of the ActionEvent to source
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.Toolkit;
    import java.awt.event.KeyEvent;
    import Graphics.*;
    public class Bingo {
         static Ball balls[][] = new Ball[5][15]; //creates a 2D 5 by 15 array
         public static void bingoCaller() {
              //DrawFrame.setDefaultLookAndFeelDecorated(true); //decorates the look and feel
              int width = 1250; //sets width to 1250 pixels
              int height = 500; //sets height to 500 pixels
              Toolkit toolkit = Toolkit.getDefaultToolkit(); //creates a Toolkit object
              Dimension dim = toolkit.getScreenSize(); //creates a Dimension object and sets the it as the screen size
              DrawFrame frame = new DrawFrame((dim.width-width)/2, (dim.height-height)/2, width, height, "Automated BINGO Caller"); //creates instance of DrawFrame that is 1250 pixel wide and 500 pixels high at the center of the screen
              Graphics g = frame.getGraphicsEnvironment(); //calls the getGraphicsEnvironment method in the DrawFrame class
              Keys key = new Keys(); //creates instance of the Keys class
              frame.addKeyListener(key); //adds a KeyListener called Key
              for (int x = 0; x < 5; x++) { //fills rows
                   for (int y = 0; y < 15; y++) { //fills columns
                        balls[x][y] = new Ball(x, y+1); //fills array
              frame.pack(); //adjusts the size of the frame so everything fits
              g.setColor(Color.black); //sets the font color of the letters to black
              g.setFont(new Font("MonoSpace", Font.BOLD, 50)); //creates new font
              for(int y=0;y<balls.length;y++){ //draws all possible balls
                   g.drawString(balls[y][0].s, 0, y*100+50); //draws numbers
                   for(int x=0;x<balls[y].length;x++){ //draws all possible balls
                        g.drawString(Integer.toString(balls[y][x].i), (x+1)*75, y*100+50); //draws letters
              frame.repaint(); //repaints numbers
              do {
                   int x, y; //sets variables x and y as integers
                   int count = 0; //sets a count for the number of balls called
                   boolean exit; //sets a boolean to the exit variable
                   do {
                        exit = false; //exit is set to false
                        x = (int)(Math.random() * 5); //picks a random number between 0 and 4 and stores it as x
                        y = (int)(Math.random() * 15); //picks a random number between 0 and 14 stores it as y
                        if (!balls[x][y].called) { //checks to see if a value is called
                             exit = true; //changes exit to true if it wasn't called
                             balls[x][y].called = true; //sets called in the Ball class to true if it wasn't called
                   } while (!exit&&count<5*15); //if exit is false, and count is less than 75returns to top of loop
                   for(int z=0;z<balls.length;z++){ //looks at balls
                        g.setColor(Color.black); //displays in black
                        g.drawString(balls[z][0].s, 0, z*100+50); //draws balls as a string
                        for(int a=0;a<balls[z].length;a++){ //looks at all balls
                             if (balls[z][a].called){ //if a ball is called
                                  g.setColor(Color.red); //change color to red
                                  count++; //increments count
                             } else {
                                  g.setColor(Color.white); //if it isn't called stay white
                             g.drawString(Integer.toString(balls[z][a].i), (a+1)*75, z*100+50); //draws balls as string
                   boolean next=false; //initiates boolean value next and sets it to false
                   frame.repaint(); //repaints the balls when one is called
                   while(!next) {
                        try {
                             Thread.sleep(100); //pauses the thread for 0.1 seconds so it can register the key pressed
                        } catch (InterruptedException e) {
                             e.printStackTrace(); //if it is interrupted it throws an exception and it is caught and the stack trace is printed
                        if(key.keyPressed==KeyEvent.VK_ENTER){ //if Enter is pressed
                             next=true; //next is set to true
                             key.keyPressed=0; //keypressed value is reset to 0
                        }else if (key.keyPressed == KeyEvent.VK_H) {
                             new Rules();
                             key.keyPressed = 0;
                        } else if (key.keyPressed == KeyEvent.VK_R) { //if R is pressed
                             key.keyPressed=0; //keypressed is reset to 0
                             next=true; //next is set to true
                             count=5*15; //changes count to 5*15
                             for(int z=0;z<balls.length;z++){ //recreates rows
                                  g.setColor(Color.white); //sets color to white
                                  g.drawString(balls[z][0].s, 0, z*100+50); //redraws rows
                                  for(int a=0;a<balls[z].length;a++){ //recreates columns
                                       balls[z][a] = new Ball(z, a+1); //fills array
                                       g.drawString(Integer.toString(balls[z][a].i), (a+1)*75, z*100+50); //redraws columns
                   if (count==5*15) { //if count = 5*15
                        for(int z=0;z<balls.length;z++){ //recreates rows
                             g.setColor(Color.white); //sets color to white
                             g.drawString(balls[z][0].s, 0, z*100+50); //redraws rows
                             for(int a=0;a<balls[z].length;a++){ //recreates columns
                                  balls[z][a] = new Ball(z, a+1); //fills array
                                  g.drawString(Integer.toString(balls[z][a].i), (a+1)*75, z*100+50); //redraws columns
              } while (true); //infinite loop only terminates program when the close button is clicked
    package Graphics;
    import java.awt.Graphics;
    import javax.swing.JFrame;
    public class DrawFrame extends JFrame{
         public Panel panel; //creates a variable called panel of type Panel
         public DrawFrame(int width, int height, String s) { //constructor for size and title
              super(s); //gets s from class that calls it
              this.setBounds(0, 0, width, height); //sets size of component
              initial(); //calls method initial
         public DrawFrame(int x, int y, int width, int height, String s) { //second constructor for size, title, and where on the screen it appears
              super(s); //gets title from the class that calls it
              this.setBounds(x, y, width, height);     //sets size of component     
              initial(); //calls method initial
         void initial() {
              this.setResizable(false); //disables resizing of window
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //terminates program if close button is pressed
              this.setPreferredSize(getSize()); //gets the size and set the preferred size
              panel = this.getPanel(); //gets the an instance of the Panel class and store the reference in panel
              this.getContentPane().add(panel); //adds panel to the frame
              this.setVisible(true); //makes the frame visible
              panel.init(); //calls the init method form the Panel class
         public Graphics getGraphicsEnvironment(){ //return type of Panel for method getGraphicsEnvironment
              return panel.getGraphicsEnvironment(); //returns the GraphicsEnvironment from class Panel
         Panel getPanel(){ //method getPanel with return type of Panel
              return new Panel(); //returns a new instance of the Panel class
    package Graphics;
    import java.awt.Graphics;
    import javax.swing.JFrame;
    public class DrawFrame2 extends JFrame{
         public Panel panel; //creates a variable called panel of type Panel
         public DrawFrame2(int width, int height, String s) { //constructor for size and title
              super(s); //gets s from class that calls it
              this.setBounds(0, 0, width, height); //sets size of component
              initial(); //calls method initial
         public DrawFrame2(int x, int y, int width, int height, String s) { //second constructor for size, title, and where on the screen it appears
              super(s); //gets title from the class that calls it
              this.setBounds(x, y, width, height);     //sets size of component     
              initial(); //calls method initial
         void initial() {
              this.setResizable(false); //disables resizing of window
              this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); //terminates program if close button is pressed
              this.setPreferredSize(getSize()); //gets the size and set the preferred size
              panel = this.getPanel(); //gets the an instance of the Panel class and store the reference in panel
              this.getContentPane().add(panel); //adds panel to the frame
              this.setVisible(true); //makes the frame visible
              panel.init(); //calls the init method form the Panel class
         public Graphics getGraphicsEnvironment(){ //return type of Panel for method getGraphicsEnvironment
              return panel.getGraphicsEnvironment(); //returns the GraphicsEnvironment from class Panel
         Panel getPanel(){ //method getPanel with return type of Panel
              return new Panel(); //returns a new instance of the Panel class
    package Graphics;
    import javax.swing.JPanel;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Image;
    public class Panel extends JPanel{
         Graphics g; //initiates variable g as type Graphics
         Image image; //initiates variable image as type Image
         public void init() {
              image = this.createImage(this.getWidth(), this.getHeight()); //creates the image with the specified height and stores it as image
              g = image.getGraphics(); //uses the getGraphics method from the Image class and stores it as g
              g.setColor(Color.white); //sets the color of g to white
              g.fillRect(0, 0, this.getWidth(), this.getHeight()); //fills the rectangle
         Graphics getGraphicsEnvironment() { //method getGraphicsEnvironment with return type Graphics
              return g; //returns g
         public void paint(Graphics graph) { //overrides the paint method and passes the argument graph of type Graphics
              if (graph == null) //if there is nothing in graph
                   return; //return
              if (image == null) { //if there is nothing in image
                   return; //return
              graph.drawImage(image, 0, 0, this); //draws the image
    package Graphics;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    public class Keys extends KeyAdapter{
    public int keyPressed; //creates a variable keyPressed that stores an integer
    public void keyPressed(KeyEvent e) { //creates a KeyEvent from a KeyListner
              keyPressed = e.getKeyCode(); //gets the key from the keyboard
    public class Ball {
         String s; //initiates s that can store data type String
         int i; //initiates i that can store data as type integer
         boolean called = false; //initiates called as a boolean value and sets it to false
         public Ball(int x, int y) {
              i = (x * 15) + y; //stores number as i to be passed to be printed
              switch (x) { //based on x value chooses letter
              case 0: //if x is 0
                   s = "B"; //sets s to B
                   break; //breaks out of switch case
              case 1: //if x is 1
                   s = "I"; //sets s to I
                   break; //breaks out of switch case
              case 2: //if x is 2
                   s = "N"; //sets s to N
                   break; //breaks out of switch case
              case 3: //if x is 3
                   s = "G"; //sets s to G
                   break; //breaks out of switch case
              case 4: //if x is 4
                   s = "O"; //sets s to O
         public String toString() { //overrides toString method, converts answer to String
              return s + " " + i; //returns to class bingo s and i
    import java.awt.Dimension;
    import java.awt.Toolkit;
    import javax.swing.JLabel;
    import javax.swing.SwingConstants;
    import Graphics.DrawFrame2;
    public class Rules {
         public Rules() {
         int width = 350;
         int height = 150;
         Toolkit toolkit = Toolkit.getDefaultToolkit();
         Dimension dim = toolkit.getScreenSize();
         DrawFrame2 frame = new DrawFrame2((dim.width-width)/2, (dim.height-height)/2, width, height, "How to Play");
         JLabel label = new JLabel("<html>Press ENTER to call a new number.<br> Press R to reset game.<br> The game resets if all 75 numbers have been called.<br> Press H to see this scrern again.", SwingConstants.CENTER);
         frame.panel.add(label);
         label.setOpaque(true);
         label.setVisible(true);
         frame.setVisible(true);
    I created this program to call bingo numbers. When you start the program a small frame appears that tells you how to use the program. When you click the button that frame is disposed and a new one appears that call the numbers. Both of these frames have code in them that will find the dimensions of your screen and put the frames in the center. When you press enter a new number is called by changing the number from white (same color as background) to red. Once all 75 numbers have been called it resets the game. If you press R at anytime during the game the game resets. I had wanted to create a new frame that would display how to play in the middle of the game. It had to be different than the one at the beginning where it doesn't have the button and it isn't in the driver class (class Caller). If you press H at anytime after it starts calling numbers the new frame will be displayed. I have a class (DrawFrame) that extends JFrame but that had the default close operation set to EXIT_ON_CLOSE and I didn't want the program to terminate when the user clicked the x in the how to play frame. I created DrawFrame2 to solve this problem where the only line of code that is different is that the default close operation is DISPOSE_ON_CLOSE. The name of the class I used for the new how to play frame is Rules. The code in this class should work but for some reason the JLabel isn't displaying. Can someone please help me out?

    I just copied the code from class Caller into Rules and reworked it a bit and it worked.

  • Need help in displaying an Image in a JLabel

    Hi everyone,
    I am using a JLabel to display images on a particular screen. I am facing some problem while doing so..
    On my screen there are images of some garments. When the users select colors from a particular list, i should color this garment images and load it on the screen again with the colors. I have a floodfill class for filling the colors in the images. The problem I am facing is I am able to color the image properly with my floodfill class but when displaying the image on the same jlabel, the image gets distorted somehow.
    Everytime I color the image, I create an ImageIcon of the image and use the seticon method from the JLabel class. First I set the icon to null and then set it to the imageicon created. here is the code I use.
    If 'image' is the the image i have to load
    ImageIcon imgicon = new ImageIcon(image);
    jlabel.setIcon(null);
    jlabel.setIcon(imgicon);I am setting the icon to null because I have not found any other method to clear the previous image from the jlabel.
    Can anyone who has worked on images before and faced a similar situation help me with this?? Is there some other container I can use besides the JLabel to display the images perhaps?
    Thanks in advance.....
    Bharat

    And the thing is when I first go into that screen with the selected colors it is displaying the images perfectly.
    It is only giving problems when I pick different colors on the screenit really sounds like the problem is in your floodfill class.
    I have no idea what's in floodfill, but if you were e.g. using a JPanel and paintComponent,
    you would need to have as the first line in paintComponent()
    super.paintComponent(..);
    to clear the previous painting.
    if not, you would be just drawing over the top of the previous paintComponent(), and if the calculation of the
    painting area is not 100% exact, you may get the odd pixel not painted-over, meaning those pixels will display
    the old color.

Maybe you are looking for

  • Aio remote can't find printer

    I have a HP Envy 4507. My AiO Remote app can't find it. This is not a compatibility issue as I have been selling 4507's which I demonstrate by connecting to them. I originally was able to connect on the one at home but not lately. I keep on seeing th

  • Office jet Pro 8600, Multiple Printers on same nenwork need to change printer name ID

    How do I Change the default Printer ID /name  on a Office Jet Pro 8600 AI1  using OS x 10.8 on a home network . To prevent other computers from accessing multiple  8600's set as delivered, on the same  network?

  • How do I upgrade my 2009 Macbook from Leopard 10.5.8 to Maverick?

    One discussion indicated that the Aluminum 5.1 model from 2009 should be compatible with Maverick. App Store screen states that one needs 10.6.6 or higher to download from App Store. So how do I upgrade?

  • Biztalk log error

    I received this error in my application log, all my ports are enabled and bound to an orchestration. A message received by adapter "FILE" on receive location "ReceiveFiles" with URI "C:\Receive\*.*" is suspended.   Error details: The published messag

  • Help needed with configuring D-Link DSL-320T

    My home network consists of 2 Aiport Express using WDS, 2 PowerBooks and a WiFi HP printer. I recently had to replace my trusty Aztech DSL modem/router when it died, and bought a D-Link DSL-320T. This is a DSL modem but NOT ROUTER with a built in DHC