Component repaint

I have a custom component in which I have overwritten the update() function to look somthing like this:
public void update(Graphics g) {
paint(g);
this function works fine but everytime the components container(Frame) is resized the screen is cleared. what other function do I have to overwrite to stop this happening?

yes, but when the frame resizes it somehow clears the Graphics of each component and then repaints them. This method is not the repaint method of the component as I have overwritten the update method and every time I call repaint it doesnt clear the screen. do you know what method the frame calls to clear the graphics of the component when it resizes?

Similar Messages

  • Component repaint() method changed?

    Did the Component repaint() method used to clear the Component pane as well as painting it again?
    I ask because I think my textbook is assuming that repaint() clears the pane and then paints again but when I implement the code that I've written, I see all previously painted objects.
    Thanks.

    The job of repaint is just to queue a request for the repainting of the object. It sounds like the problem is in your actual painting code. You also haven't said what framework you are using? AWT? Swing? SWT?
    In Swing, you typically override paintComponent like so:
    @Override protected void paintComponent(Graphics g) {
         super.paintComponent(g);
         //do you painting here:
    }The call to super.paintComponent is what clears the component.
    In future, Swing questions should go tot the Swing forum: [http://forums.sun.com/forum.jspa?forumID=57]

  • How to get time spent in the repaint(long delay) method of component?

    Hi,
    I'm trying to get the time spent in the repaint method of Component. I tried to surround the method with time information:
    long time = System.getTime();
    component.repaint(400);
    time = System.getTime() - time;
    System.out.println("Time spent in repaint is: " + time);
    But, the method seem to return about immediatly after call, whereas the display do not seem to be completly redrawn. I think that this is because repaint method is done in a separate thread....
    I thought to catch the event that could be thrown when redrawn is completed but could not find this event....
    Do you have an idea how I could perform this?
    Thanks a lot
    Tanguy

    repant() posts an event to the Event Queue so that sometime soon the component's paint() mehtod will be called. It will be called by the Event Thread.

  • Repaint() is not thread-safe?

    I saw a description that says repaint() is thread-safe in an old swing tutorial, but not in the current tutorial and its javadoc. So can I assume repaint() is not thread-safe and I should call it from EDT? ... Or if they are thread-safe, why does Sun not document it?

    repaint() calls paint() on EDT... but it calculates dirty region on the current thread and does not get AWTTreeLock.I don't think so.
    repaint() is a java.awt.Component method and doesn't know about Swing's RepaintManager and dirty regions. There may be somthing similar at the AWT level that escaped me, but looking at the JDK1.6 source code, java.awt.Component.repaint() just repaints the whole component.
    Now repaint(long, int, int, int, int) has two versions.
    At the AWT level, it just posts a paint event for the specified region. No race condition, and no risk that he region be wrong, but possibility to invoke multiple paint(Graphics) that overlap, that is, to paint several times the same area - it may be an optimization problem, but it doesn't jeopardize the consistency of the drawing.
    At the Swing level, it does compute dirty regions. In Repaint manageer, the call to extendDirtyRegion(...) is protected within a synchronized block, but the code before that is not. From a quick look, that code is:
    1) walking up the component hierarchy to find the root, which may not be thread-safe, but a well-behaved application shouldn't change the hierarchy from outside the EDT.
    2) walking up a chain of "delegate" RepaintManager, which I knew nothing about... Apparently it's a sun's implementation specific construct, each JComponent can be assigne d a delegate RepaintManager. Again I would claim that such things should not happen outside of the EDT, but I haven't found documentation about this.
    Edited by: jduprez on Jul 20, 2009 2:37 PM
    so no, technically, I can't prove repaint(long, int,int,int,int) is thread-safe.
    But a well-behaved application that updates its widgets on the EDT shouldn't worry (that is, repaint(...) calls can still be invoked outside of the EDT).
    Edited by: jduprez on Jul 21, 2009 7:04 PM - typos

  • Repaint a canvas

    Hi everybody,
    I have to implement a frame in which you can draw some lines. Those lines are the edges of cells for a mobile network.
    But when I drew a line, it disappeared immediately. How can I resolve this ?
    The schematic is heavy to load, so I want to save it in a "virtual canvas", to make it easy to repaint the canvas. I don't know how do that.
    Here is my code for the frame :
    public class FAPShowMap extends Canvas implements MouseListener {
         private Graphics gr ;
         private Frame frame ;
         public FAPShowMap(Vector ed) {
              super() ;
              frame = new Frame("Carte des cellules et antennes") ;
              frame.setSize(600,600) ;
              frame.setResizable(false) ;
              frame.addWindowListener(new GenericWindowListener()) ;
              frame.add(this) ;
              frame.pack() ;
              this.addMouseListener(this) ;
              frame.setVisible(true) ;
              this.addNotify() ;
              paint(new Vector()) ;
         public void paint(Vector ed) {
              gr = this.getGraphics() ;
              gr.drawLine(3,3,200,200) ;
              this.paint(gr) ;
         public void mouseClicked(MouseEvent e) {
              this.repaint() ;
              gr.drawLine(50,50,600,100) ;
              this.paint(gr) ;
         public void mousePressed(MouseEvent e) {}
         public void mouseReleased(MouseEvent e) {}
         public void mouseEntered(MouseEvent e) {}
         public void mouseExited(MouseEvent e) {}
         public static void main(String[] args) {
              new FAPShowMap(null) ;
    I will be very glad if you can help me
    Thank you
    Agni

    Hi Agni,
    Reread my previous post. In particular, it mentions the probable cause of your problem. Note that it's not caused by overloading the paint method; it's what you're doing inside the overloaded method.
    Changing your overloaded paint method to be:public void paint(Vector ed)
       gr = this.getGraphics() ;
       gr.setColor(java.awt.Color.black);
       gr.drawLine(3,3,200,200) ;
    }should work, but with a problem. Namely, when the component repaints itself, the line will be erased. Take a look at the tutorials for the explanation of why this happens and how to correct for it.
    I strongly recommend seeking a definitive source for Java programming if you are just starting. The "Core" series from Sun MicroSystems Press is very good. Jumping in (especially with graphics) may cause more aggrevation than progress.
    Regards,
    Nick

  • Knowing Completion of Repaint

    Hi Folks,
    I am having a JPanel and I will be adding button to it on the fly
    and removing too.
    My problem is when I add a button, I want to know the button's width.
    This I cannot do because I tried the code in a ContainerListener.containerAdded() and ContainerListener.containerRemoved()
    Just after I had added the button and called revalidate() and repaint() on the JPanel.
    The width of the just added button I get is 0. I guess it is because my peice of code runs BEFORE the repaint is finished its job.
    Am I right? If yes, then how can I know when a component repaint() has finishe doing its job??

    <b>Code: </b>
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    import java.util.Vector;
    public class ButtonScroller extends JPanel {
         FlowLayout flow = new FlowLayout(FlowLayout.LEFT);
         JPanel rightPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
         JPanel buttonPanel = new JPanel(flow);
         JPanel o1;
         Vector bv = new Vector();
         int buttonGap = 0;
         JButton lb, rb;
         public ButtonScroller() {
              BorderLayout layout = new BorderLayout();
              layout.setVgap(0);
              layout.setHgap(0);
              BorderLayout layout1 = new BorderLayout();
              layout1.setVgap(0);
              layout1.setHgap(0);
              BorderLayout layout2 = new BorderLayout();
              layout2.setVgap(0);
              layout2.setHgap(0);
              BorderLayout layout3 = new BorderLayout();
              layout3.setVgap(0);
              layout3.setHgap(0);
              setLayout(layout);
              flow.setHgap(5);
              buttonGap = flow.getHgap();
              o1 = new JPanel(layout1);
              JPanel i1 = new JPanel(layout2);
              JPanel i2 = new JPanel(layout3);
              o1.add(i1, BorderLayout.CENTER);
              o1.add(i2, BorderLayout.EAST);
              i1.add(buttonPanel, BorderLayout.NORTH);
              i2.add(rightPanel, BorderLayout.NORTH);
              //add(buttonPanel, BorderLayout.CENTER);
              //add(rightPanel, BorderLayout.EAST);
              add(o1, BorderLayout.CENTER);
              rightPanel.setBorder(new SoftBevelBorder(BevelBorder.RAISED));
              buttonPanel.setBorder(new SoftBevelBorder(BevelBorder.RAISED));
              setup();
              buttonPanel.addContainerListener(new ContainerListener() {
                   public void componentAdded(ContainerEvent ce) {
                        areBMTA();     
                   public void componentRemoved(ContainerEvent ce) {
                        areBMTA();
         void setup() {
              lb = new JButton("L");
              rightPanel.add(lb);
              rb = new JButton("R");
              rightPanel.add(rb);
              lb.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent ae) {
                        System.out.println("Left Button Clicked");
              rb.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent ae) {
                        System.out.println("Right Button Clicked");
              rb.addMouseListener(new MouseAdapter() {
                   public void mouseClicked(MouseEvent me) {
                        if (SwingUtilities.isRightMouseButton(me)) {
                             System.out.println("Right Click on right button");
                             JButton button = new JButton("(- " + (bv.size() + 10) + "-)");
                             //button.setBorder(new EmptyBorder(0,0,0,0));
                             buttonPanel.add(button);
                             button.addComponentListener(new ComponentAdapter() {
                                  public void componentShown(ComponentEvent ce) {
                                       System.out.println("The button is now visible");
                             bv.add(button);
                             buttonPanel.revalidate();
                             buttonPanel.repaint(0);
              lb.addMouseListener(new MouseAdapter() {
                   public void mouseClicked(MouseEvent me) {
                        if (SwingUtilities.isRightMouseButton(me)) {
                             System.out.println("Right Click on left button");
                             int size = bv.size();
                             if (size == 0) return;
                             JButton button = (JButton) bv.elementAt(0);
                             buttonPanel.remove(button);
                             bv.remove(button);
                             buttonPanel.revalidate();
                             buttonPanel.repaint(0);
         private boolean areBMTA() {
              int pWidth = buttonPanel.getSize().width;
              int bWidth = 0;
              int totButtons = buttonPanel.getComponentCount();
              int totalButtonWidth = 0;
              if (totButtons ==0 ) return false;
              for(int i=0; i<totButtons; i++) {
                   JButton button = (JButton)buttonPanel.getComponent(i);
                   System.out.println("The Width of the button at [" + i +"] is " + button.getWidth());
                   if (button.isVisible()) {
                        //bWidth = button.getSize().width;
                        bWidth = button.getWidth();
                        System.out.println("We found a button that was visible and its width is " + bWidth);
                        break;
              System.out.println("Button Gap :" + buttonGap);
              System.out.println("Button Width :" + bWidth);
              int extraWidth = (totButtons + 1) * buttonGap;
              totalButtonWidth += extraWidth;
              totalButtonWidth += (totButtons * bWidth);
              System.out.println("TBW:" + totalButtonWidth + "And Panel Width: " + pWidth);
              System.out.println("Right Panel Width is " + rightPanel.getSize().width);
              System.out.println("o1 Panel Width is " + o1.getSize().width);
              if (totalButtonWidth > pWidth)
                   return true;
              else
                   return false;
         private boolean scroll(char ch) {
              return false;

  • Paint Component

    Hi all
    i have four classes plot , plot3d, plotsurface and test
    plot is derived from JPanel and plot3d and plotsurface extend plot class
    i am trying to do a very simple operation . just making a tool bar with 2 buttons to switch between plots .
    the 2 plot classes plot3d and plotsurface just draw a line on the screen
    problem is that when the user clicks one button it doesnot show up on the screen but when the window is resized it does call paint component of the corresponding class
    can Any one explain why this is happening......
    package test;
    import javax.swing.*;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    public abstract class plot extends JPanel {
    plot()
    public void paintComponent(Graphics g)
    Graphics2D graphics2D=(Graphics2D)g;
    super.paintComponent(g);
    package test;
    import javax.swing.*;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    public class plot3d extends plot {
    plot3d(boolean resizable)
    public void paintComponent(Graphics g)
    Graphics2D graphics2D=(Graphics2D)g;
    super.paintComponent(g);
    graphics2D.drawLine(200,200,320,320);
    package test;
    import javax.swing.*;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    public class plotsurface extends plot {
    plotsurface(boolean resizable)
    public void paintComponent(Graphics g)
    Graphics2D graphics2D=(Graphics2D)g;
    super.paintComponent(g);
    graphics2D.drawLine(120,120,140,140);
    package test;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.Graphics2D.*;
    import java.applet.*;
    public class Test extends javax.swing.JApplet {
    private Container container;
    public Rectangle rect;
    JPanel toolBar;
    JButton contourButton;
    JButton surfaceButton;
    JPanel toolPanel;
    public Graphics g;
    public test.plot3d graph3D;
    public test.plotsurface graphSurface;
    private int plotType=0;
    private void graph3D(Graphics2D g2)
    graph3D=new plot3d(false);
    public void graphSurface(Graphics2D g2)
              graphSurface=new plotsurface(false);
    private void changeplottoContour()
    if(plotType==0)
    return;
    plotType=0;
    g=container.getGraphics();
    Graphics2D g2=(Graphics2D)g;
    container.removeAll();
    repaint();
    graphSurface=null;
    System.gc();
    graph3D(g2);
    container.add(toolPanel,BorderLayout.NORTH);
    container.add(graph3D,BorderLayout.CENTER);
    private void changeplottoSurface()
    if(plotType==1)
    return;
    plotType=1;
    g=container.getGraphics();
    Graphics2D g2=(Graphics2D)g;
    container.removeAll();
    repaint();
    graph3D=null;
    System.gc();
    graphSurface(g2);
    container.add(toolPanel,BorderLayout.NORTH);
    container.add(graphSurface,BorderLayout.CENTER);
    private void surfaceButtonActionPerformed(java.awt.event.ActionEvent evt)
         changeplottoSurface();
         repaint();
    private void contourButtonActionPerformed(java.awt.event.ActionEvent evt)
         changeplottoContour();
         repaint();
    public void init()
         container=getContentPane();
    g=container.getGraphics();
    Graphics2D g2=(Graphics2D)g;
    Rectangle r1= new Rectangle();
    rect=new Rectangle();
    //r1=container.getBounds();
    toolPanel= new JPanel(new BorderLayout());
    toolBar = new JPanel();
    contourButton = new JButton("Contour");
    toolBar.add(contourButton);
    contourButton.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    contourButtonActionPerformed(evt);
    surfaceButton = new JButton("Surface Plot");
    toolBar.add(surfaceButton);
    surfaceButton.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    surfaceButtonActionPerformed(evt);
    toolBar.setBackground(Color.white);
    toolPanel.add(toolBar,BorderLayout.NORTH);
    container.add(toolPanel,BorderLayout.NORTH);
    Rectangle r2= toolPanel.getBounds();
    Dimension appletSize = this.getSize();
    int appletHeight= appletSize.height;
    int appletWidth= appletSize.width;
              rect.setBounds(0,(int)r2.getHeight(),appletWidth,appletHeight-(int)r2.getHeight());
    plotType=0;
         graph3D(g2);
         container.add(graph3D,BorderLayout.CENTER);

    in your button action listeneres (e.g. contourButtonActionPerformed()) don't only call repaint(), but update(this.getGraphics());
    this should help in most cases. other refreshing methods are:
    java -Dsun.java2d.noddraw=true HelloWorld
    java.awt.Component.repaint()
    java.awt.Component.update(Graphics) (e.g. c.update(c.getGraphics());)
    java.awt.Component.validate()
    javax.swing.JComponent.revalidate()
    javax.swing.JComponent.updateUI()
    javax.swing.SwingUtilities.updateComponentTreeUI(java.awt.Component)

  • Custom graphics in java.awt.ScrollPane

    Hi all,
    I have to draw a custom created image in a scroll pane. As the image is very large I want to display it in a scroll pane. As parts of the image may change within seconds, and drawing the whole image is very time consuming (several seconds) I want to draw only the part of the image that is currently visible to the user.
    My idea: creating a new class that extends from java.awt.ScrollPane, overwrite the paint(Graphics) method and do the drawings inside. Unfortunately, it does not work. The background of the scoll pane is blue, but it does not show the red box (the current viewport is not shown in red).
    Below please find the source code that I am using:
    package graphics;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.ScrollPane;
    import java.awt.event.AdjustmentEvent;
    public class CMyComponent extends ScrollPane {
         /** <p>Listener to force a component to repaint when a scroll bar changes its
          * position.</p>
         private final class ScrollBarAdjustmentListener implements java.awt.event.AdjustmentListener {
              /** <p>The component to force to repaint.</p> */
              private final Component m_Target;
              /** <p>Default constructor.</p>
               * @param Target The component to force to repaint.
              private ScrollBarAdjustmentListener(Component Target) { m_Target = Target; }
              /** <p>Forces to component to repaint upon adjustment of the scroll bar.</p>
               *  @see java.awt.event.AdjustmentListener#adjustmentValueChanged(java.awt.event.AdjustmentEvent)
              public void adjustmentValueChanged(AdjustmentEvent e) { m_Target.paint(m_Target.getGraphics()); }
         public CMyComponent() {
              // Ensure that the component repaints upon changing of the scroll bars
              ScrollBarAdjustmentListener sbal = new ScrollBarAdjustmentListener(this);
              getHAdjustable().addAdjustmentListener(sbal);
              getVAdjustable().addAdjustmentListener(sbal);
         public void paint(Graphics g) {
              setBackground(Color.BLUE);
              g.setColor(Color.RED);
              g.fillRect(getScrollPosition().x, getScrollPosition().y, getViewportSize().width, getViewportSize().height);
         public final static void main(String[] args) {
              java.awt.Frame f = new java.awt.Frame();
              f.add(new CMyComponent());
              f.pack();
              f.setVisible(true);
    }

    Dear all,
    I used the last days and tried several things. I think now I have a quite good working solution (just one bug remains) and it is very performant. To give others a chance to see what I have done I post the source code of the main class (a canvas drawing and implementing scrolling) here. As soon as the sourceforge project is accepted, I will publish the whole sources at there. Enjoy. And if you have some idea for my last bug in getElementAtPixel(Point), then please tell me.
    package internetrail.graphics.hexgrid;
    import java.awt.Canvas;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.Point;
    import java.awt.Polygon;
    import java.awt.event.ComponentEvent;
    import java.awt.event.ComponentListener;
    import java.awt.geom.Area;
    import java.awt.image.BufferedImage;
    import java.util.WeakHashMap;
    import java.util.Map;
    /** <p>Hex grid view.</p>
    * <p>Visualizes a {@link IHexGridModel}.</p>
    * @version 0.1, 03.06.2006
    * @author Bjoern Wuest, Germany
    public final class CHexGridView extends Canvas implements ComponentListener, IHexGridElementListener {
         /** <p>Serial version unique identifier.</p> */
         private static final long serialVersionUID = -965902826101261530L;
         /** <p>Instance-constant parameter for the width of a hex grid element.</p> */
         public final int CONST_Width;
         /** <p>Instance-constant parameter for 1/4 of the width of a hex grid element.</p> */
         public final int CONST_Width1fourth;
         /** <p>Instance-constant parameter for 3/4 of the width of a hex grid element.</p> */
         public final int CONST_Width3fourth;
         /** <p>Instance-constant parameter for 1.5 times of the width of a hex grid element.</p> */
         public final int CONST_Width1dot5;
         /** <p>Instance-constant parameter for 4 times of the width of a hex grid element.</p> */
         public final int CONST_Widthquad;
         /** <p>Instance-constant parameter for the height of a hex grid element.</p> */
         public final int CONST_Height;
         /** <p>Instance-constant parameter for 1/2 of the height of a hex grid element.</p> */
         public final int CONST_Heighthalf;
         /** <p>Instance-constant parameter for the double height of a hex grid element.</p> */
         public final int CONST_Heightdouble;
         /** <p>The steepness of a side of the hex grid element (calculated for the upper left arc).</p> */
         public final double CONST_Steepness;
         /** <p>The model of this hex grid </p> */
         private final IHexGridModel m_Model;
         /** <p>A cache for already created images of the hex map.</p> */
         private final Map<Point, Image> m_Cache = new WeakHashMap<Point, Image>();
         /** <p>The graphical area to draw the selection ring around a hex element.</p> */
         private final Area m_SelectionRing;
         /** <p>The image of the selection ring around a hex element.</p> */
         private final BufferedImage m_SelectionRingImage;
         /** <p>The current position of the hex grid in pixels (top left visible corner).</p> */
         private Point m_ScrollPosition = new Point(0, 0);
         /** <p>Flag to define if a grid is shown ({@code true}) or not ({@code false}).</p> */
         private boolean m_ShowGrid = true;
         /** <p>Flag to define if the selected hex grid element should be highlighted ({@code true}) or not ({@code false}).</p> */
         private boolean m_ShowSelected = true;
         /** <p>The offset of hex grid elements shown on the screen, measured in hex grid elements.</p> */
         private Point m_CurrentOffset = new Point(0, 0);
         /** <p>The offset of the image shown on the screen, measured in pixels.</p> */
         private Point m_PixelOffset = new Point(0, 0);
         /** <p>The index of the currently selected hex grid element.</p> */
         private Point m_CurrentSelected = new Point(0, 0);
         /** <p>The width of a buffered pre-calculated image in pixel.</p> */
         private int m_ImageWidth;
         /** <p>The height of a buffered pre-calculated image in pixel.</p> */
         private int m_ImageHeight;
         /** <p>The maximum number of columns of hex grid elements to be shown at once on the screen.</p> */
         private int m_MaxColumn;
         /** <p>The maximum number of rows of hex grid elements to be shown at once on the screen.</p> */
         private int m_MaxRow;
         /** <p>Create a new hex grid view.</p>
          * <p>The hex grid view is bound to a {@link IHexGridModel} and registers at
          * that model to listen for {@link IHexGridElement} updates.</p>
          * @param Model The model backing this view.
         public CHexGridView(IHexGridModel Model) {
              // Set the model
              m_Model = Model;
              CONST_Width = m_Model.getElementsWidth();
              CONST_Height = m_Model.getElementsHeight();
              CONST_Width1fourth = CONST_Width/4;
              CONST_Width3fourth = CONST_Width*3/4;
              CONST_Width1dot5 = CONST_Width*3/2;
              CONST_Heighthalf = CONST_Height/2;
              CONST_Widthquad = CONST_Width*4;
              CONST_Heightdouble = CONST_Height*2;
              CONST_Steepness = (double)CONST_Heighthalf / CONST_Width1fourth;
              m_ImageWidth = getSize().width+CONST_Widthquad;
              m_ImageHeight = getSize().height+CONST_Heightdouble;
              m_MaxColumn = m_ImageWidth / CONST_Width3fourth;
              m_MaxRow = m_ImageHeight / CONST_Height;
              // Register this canvas for various notifications
              m_Model.addElementListener(this);
              addComponentListener(this);
              // Create the selection ring to highlight hex grid elements
              m_SelectionRing = new Area(new Polygon(new int[]{-1, CONST_Width1fourth-1, CONST_Width3fourth+1, CONST_Width+1, CONST_Width3fourth+1, CONST_Width1fourth-1}, new int[]{CONST_Heighthalf, -1, -1, CONST_Heighthalf, CONST_Height+1, CONST_Height+1}, 6));
              m_SelectionRing.subtract(new Area(new Polygon(new int[]{2, CONST_Width1fourth+2, CONST_Width3fourth-2, CONST_Width-2, CONST_Width3fourth-2, CONST_Width1fourth+2}, new int[]{CONST_Heighthalf, 2, 2, CONST_Heighthalf, CONST_Height-2, CONST_Height-2}, 6)));
              m_SelectionRingImage = new BufferedImage(CONST_Width, CONST_Height, BufferedImage.TYPE_INT_ARGB);
              Graphics2D g = m_SelectionRingImage.createGraphics();
              g.setColor(Color.WHITE);
              g.fill(m_SelectionRing);
         @Override public synchronized void paint(Graphics g2) {
              // Caculate the offset of indexes to show
              int offsetX = 2 * (m_ScrollPosition.x / CONST_Width1dot5) - 2;
              int offsetY = (int)(Math.ceil(m_ScrollPosition.y / CONST_Height) - 1);
              m_CurrentOffset = new Point(offsetX, offsetY);
              // Check if the image is in the cache
              Image drawing = m_Cache.get(m_CurrentOffset);
              if (drawing == null) {
                   // The image is not cached, so draw it
                   drawing = new BufferedImage(m_ImageWidth, m_ImageHeight, BufferedImage.TYPE_INT_ARGB);
                   Graphics2D g = ((BufferedImage)drawing).createGraphics();
                   // Draw background
                   g.setColor(Color.BLACK);
                   g.fillRect(0, 0, m_ImageWidth, m_ImageHeight);
                   // Draw the hex grid
                   for (int column = 0; column <= m_MaxColumn; column += 2) {
                        for (int row = 0; row <= m_MaxRow; row++) {
                             // Draw even column
                             IHexGridElement element = m_Model.getElementAt(offsetX + column, offsetY + row);
                             if (element != null) { g.drawImage(element.getImage(m_ShowGrid), (int)(column*(CONST_Width3fourth-0.5)), CONST_Height*row, null); }
                             // Draw odd column
                             element = m_Model.getElementAt(offsetX + column+1, offsetY + row);
                             if (element!= null) { g.drawImage(element.getImage(m_ShowGrid), (int)(column*(CONST_Width3fourth-0.5)+CONST_Width3fourth), CONST_Heighthalf*(row*2+1), null); }
                   // Put the image into the cache
                   m_Cache.put(m_CurrentOffset, drawing);
              // Calculate the position of the image to show
              offsetX = CONST_Width1dot5 + (m_ScrollPosition.x % CONST_Width1dot5);
              offsetY = CONST_Height + (m_ScrollPosition.y % CONST_Height);
              m_PixelOffset = new Point(offsetX, offsetY);
              g2.drawImage(drawing, -offsetX, -offsetY, null);
              // If the selected element should he highlighted, then do so
              if (m_ShowSelected) {
                   // Check if the selected element is on screen
                   if (isElementOnScreen(m_CurrentSelected)) {
                        // Correct vertical offset for odd columns
                        if ((m_CurrentSelected.x % 2 == 1)) { offsetY -= CONST_Heighthalf; }
                        // Draw the selection circle
                        g2.drawImage(m_SelectionRingImage, (m_CurrentSelected.x - m_CurrentOffset.x) * CONST_Width3fourth - offsetX - ((m_CurrentSelected.x + 1) / 2), (m_CurrentSelected.y - m_CurrentOffset.y) * CONST_Height - offsetY, null);
         @Override public synchronized void update(Graphics g) { paint(g); }
         public synchronized void componentResized(ComponentEvent e) {
              // Upon resizing of the component, adjust several pre-calculated values
              m_ImageWidth = getSize().width+CONST_Widthquad;
              m_ImageHeight = getSize().height+CONST_Heightdouble;
              m_MaxColumn = m_ImageWidth / CONST_Width3fourth;
              m_MaxRow = m_ImageHeight / CONST_Height;
              // And flush the cache
              m_Cache.clear();
         public void componentMoved(ComponentEvent e) { /* do nothing */ }
         public void componentShown(ComponentEvent e) { /* do nothing */ }
         public void componentHidden(ComponentEvent e) { /* do nothing */ }
         public synchronized void elementUpdated(IHexGridElement Element) {
              // Clear cache where the element may be contained at
              for (Point p : m_Cache.keySet()) { if (isElementInScope(Element.getIndex(), p, new Point(p.x + m_MaxColumn, p.y + m_MaxRow))) { m_Cache.remove(p); } }
              // Update the currently shown image if the update element is shown, too
              if (isElementOnScreen(Element.getIndex())) { repaint(); }
         /** <p>Returns the model visualized by this grid view.</p>
          * @return The model visualized by this grid view.
         public IHexGridModel getModel() { return m_Model; }
         /** <p>Returns the current selected hex grid element.</p>
          * @return The current selected hex grid element.
         public IHexGridElement getSelected() { return m_Model.getElementAt(m_CurrentSelected.x, m_CurrentSelected.y); }
         /** <p>Sets the current selected hex grid element by its index.</p>
          * <p>If the selected hex grid element should be highlighted and is currently
          * shown on the screen, then this method will {@link #repaint() redraw} this
          * component automatically.</p>
          * @param Index The index of the hex grid element to become the selected one.
          * @throws IllegalArgumentException If the index refers to a non-existing hex
          * grid element.
         public synchronized void setSelected(Point Index) throws IllegalArgumentException {
              // Check that the index is valid
              if ((Index.x < 0) || (Index.y < 0) || (Index.x > m_Model.getXElements()) || (Index.y > m_Model.getYElements())) { throw new IllegalArgumentException("There is no hex grid element with such index."); }
              m_CurrentSelected = Index;
              // If the element is on screen and should be highlighted, then repaint
              if (m_ShowSelected && isElementOnScreen(m_CurrentSelected)) { repaint(); }
         /** <p>Moves the visible elements to the left by the number of pixels.</p>
          * <p>To move the visible elements to the left by one hex grid element, pass
          * {@link #CONST_Width3fourth} as the parameter. The component will
          * automatically {@link #repaint()}.</p>
          * @param Pixels The number of pixels to move to the left.
          * @return The number of pixels moved to the left. This is always between 0
          * and {@code abs(Pixels)}.
         public synchronized int moveLeft(int Pixels) {
              int delta = m_ScrollPosition.x - Math.max(0, m_ScrollPosition.x - Math.max(0, Pixels));
              if (delta != 0) {
                   m_ScrollPosition.x -= delta;
                   repaint();
              return delta;
         /** <p>Moves the visible elements up by the number of pixels.</p>
          * <p>To move the visible elements up by one hex grid element, pass {@link
          * #CONST_Height} as the parameter. The component will automatically {@link
          * #repaint()}.</p>
          * @param Pixels The number of pixels to move up.
          * @return The number of pixels moved up. This is always between 0 and {@code
          * abs(Pixels)}.
         public synchronized int moveUp(int Pixels) {
              int delta = m_ScrollPosition.y - Math.max(0, m_ScrollPosition.y - Math.max(0, Pixels));
              if (delta != 0) {
                   m_ScrollPosition.y -= delta;
                   repaint();
              return delta;
         /** <p>Moves the visible elements to the right by the number of pixels.</p>
          * <p>To move the visible elements to the right by one hex grid element, pass
          * {@link #CONST_Width3fourth} as the parameter. The component will
          * automatically {@link #repaint()}.</p>
          * @param Pixels The number of pixels to move to the right.
          * @return The number of pixels moved to the right. This is always between 0
          * and {@code abs(Pixels)}.
         public synchronized int moveRight(int Pixels) {
              int delta = Math.min(m_Model.getXElements() * CONST_Width3fourth + CONST_Width1fourth - getSize().width, m_ScrollPosition.x + Math.max(0, Pixels)) - m_ScrollPosition.x;
              if (delta != 0) {
                   m_ScrollPosition.x += delta;
                   repaint();
              return delta;
         /** <p>Moves the visible elements down by the number of pixels.</p>
          * <p>To move the visible elements down by one hex grid element, pass {@link
          * #CONST_Height} as the parameter. The component will automatically {@link
          * #repaint()}.</p>
          * @param Pixels The number of pixels to move down.
          * @return The number of pixels moved down. This is always between 0 and
          * {@code abs(Pixels)}.
         public synchronized int moveDown(int Pixels) {
              int delta = Math.min(m_Model.getYElements() * CONST_Height + CONST_Heighthalf - getSize().height, m_ScrollPosition.y + Math.max(0, Pixels)) - m_ScrollPosition.y;
              if (delta != 0) {
                   m_ScrollPosition.y += delta;
                   repaint();
              return delta;
         /** <p>Checks if the hex grid element of the given index is currently
          * displayed on the screen (even just one pixel).</p>
          * <p>The intention of this method is to check if a {@link #repaint()} is
          * necessary or not.</p>
          * @param ElementIndex The index of the element to check.
          * @return {@code true} if the hex grid element of the given index is
          * displayed on the screen, {@code false} if not.
         public synchronized boolean isElementOnScreen(Point ElementIndex) { return isElementInScope(ElementIndex, m_CurrentOffset, new Point(m_CurrentOffset.x + m_MaxColumn, m_CurrentOffset.y + m_MaxRow)); }
         /** <p>Checks if the hex grid element of the given index is within the given
          * indexes.</p>
          * <p>The intention of this method is to check if a {@link #repaint()} is
          * necessary or not.</p>
          * @param ElementIndex The index of the element to check.
          * @param ReferenceIndexLeftTop The left top index of the area to check.
          * @param ReferenceIndexRightBottom The right bottom index of the area to check.
          * @return {@code true} if the hex grid element of the given index is within
          * the given area, {@code false} if not.
         public synchronized boolean isElementInScope(Point ElementIndex, Point ReferenceIndexLeftTop, Point ReferenceIndexRightBottom) { if ((ElementIndex.x >= ReferenceIndexLeftTop.x) && (ElementIndex.x <= ReferenceIndexRightBottom.x) && (ElementIndex.y >= ReferenceIndexLeftTop.y) && (ElementIndex.y <= (ReferenceIndexRightBottom.y))) { return true; } else { return false; } }
         /** <p>Return the {@link IHexGridElement hex grid element} shown at the given
          * pixel on the screen.</p>
          * <p><b>Remark: There seems to be a bug in retrieving the proper element,
          * propably caused by rounding errors and unprecise pixel calculations.</p>
          * @param P The pixel on the screen.
          * @return The {@link IHexGridElement hex grid element} shown at the pixel.
         public synchronized IHexGridElement getElementAtPixel(Point P) {
              // @FIXME Here seems to be some bugs remaining
              int dummy = 0; // Variable for warning to indicate that there is something to do :)
              // Calculate the pixel on the image, not on the screen
              int px = P.x + m_PixelOffset.x;
              int py = P.y + m_PixelOffset.y;
              // Determine the x-index of the column (is maybe decreased by one)
              int x = px / CONST_Width3fourth + m_CurrentOffset.x;
              // If the column is odd, then shift the y-pixel by half element height
              if ((x % 2) == 1) { py -= CONST_Heighthalf; }
              // Determine the y-index of the row (is maybe decreased by one)
              int y = py / CONST_Height + m_CurrentOffset.y;
              // Normative coordinates to a single element
              px -= (x - m_CurrentOffset.x) * CONST_Width3fourth;
              py -= (y - m_CurrentOffset.y) * CONST_Height;
              // Check if the normative pixel is in the first quarter of a column
              if (px < CONST_Width1fourth) {
                   // Adjustments to the index may be necessary
                   if (py < CONST_Heighthalf) {
                        // We are in the upper half of a hex-element
                        double ty = CONST_Heighthalf - CONST_Steepness * px;
                        if (py < ty) { x--; }
                   } else {
                        // We are in the lower half of a hex-element
                        double ty = CONST_Heighthalf + CONST_Steepness * px;
                        if (py > ty) {
                             x--;
                             y++;
              return m_Model.getElementAt(x, y);
    }Ah, just to give you some idea: I use this component to visualize a hex grid map with more than 1 million grid elements. And it works, really fast, and requires less than 10 MByte of memory.

  • Problem with findComponentAt highlighting wrong JLabel

    I've got a small 6 by 7 grid of jlabels that I would like to turn red if clicked on. In the japplet shown below, this works, sort of: it turns the label to its left red but not the label under the mouse. Any ideas on what I'm doing wrong? Thanks!
    MyApplet.java
    import javax.swing.JApplet;
    public class MyApplet extends JApplet
        MyPane2 pane = new MyPane2();
        public void init()
            getContentPane().add(pane);
    }MyPane2.java
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class MyPane2 extends JPanel implements MouseListener
        private static final int MAX_ROW = 6;
        private static final int MAX_COL = 7;
        private String whiteDot = ".\\petes\\brief3\\whiteDot.jpg";
        private String redDot = ".\\petes\\brief3\\redDot.jpg";
        private JLabel[][] myLabelGrid;
        private JPanel gridPane = new JPanel();
        public MyPane2()
            super();
            add(createLabelGridPane());
        private JPanel createLabelGridPane()
            gridPane = new JPanel();
            GridLayout myGridLO = new GridLayout(MAX_ROW, MAX_COL);
            myGridLO.setHgap(5);
            myGridLO.setVgap(5);
            gridPane.setLayout(myGridLO);
            gridPane.addMouseListener(this);
            myLabelGrid = new JLabel[MAX_COL][MAX_ROW];
            for (int row = 0; row < MAX_ROW; row++)
                for (int col = 0; col < MAX_COL; col++)
                    //myLabelGrid[col][row] = new JLabel(new ImageIcon(whiteDot));
                    myLabelGrid[col][row] = new JLabel("W");
                    gridPane.add(myLabelGrid[col][row]);
            return gridPane;
        public void mouseClicked(MouseEvent me)
            JPanel myPanel = (JPanel)me.getSource();
            System.out.println(findComponentAt(me.getX(), me.getY()));
            Component myComponent = findComponentAt(me.getX(), me.getY());
            if (myComponent instanceof JLabel)
                //((JLabel)myComponent).setIcon(new ImageIcon(redDot));
                ((JLabel)myComponent).setText("R");
            repaint();
        public void mouseEntered(MouseEvent arg0){}
        public void mouseExited(MouseEvent arg0){}
        public void mousePressed(MouseEvent arg0){}
        public void mouseReleased(MouseEvent arg0){}
    }[edited to use a label with "W" or "R" rather than images]
    Message was edited by:
    petes1234

    //  <applet code="FindComponentApplet" width="400" height="400"></applet>
    //      No html file necessary, just type
    //  appletviewer FindComponentApplet.java
    //      at the prompt and press enter.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class FindComponentApplet extends JApplet
        public void init()
            getContentPane().setLayout(new BorderLayout());
            getContentPane().add(new FindComponentPane());
    class FindComponentPane extends JPanel implements MouseListener
        private static final int MAX_ROW = 6;
        private static final int MAX_COL = 7;
        Component lastSelected;
        public FindComponentPane()
            super(new BorderLayout());
            add(createLabelGridPane());
        private JPanel createLabelGridPane()
            JPanel gridPane = new JPanel(new GridLayout(MAX_ROW, MAX_COL, 5, 5));
            gridPane.addMouseListener(this);
            JLabel[][] myLabelGrid = new JLabel[MAX_COL][MAX_ROW];
            for (int row = 0; row < MAX_ROW; row++)
                for (int col = 0; col < MAX_COL; col++)
                    JLabel label = new JLabel("W", JLabel.CENTER);
                    label.setBorder(BorderFactory.createEtchedBorder());
                    myLabelGrid[col][row] = label;
                    gridPane.add(myLabelGrid[col][row]);
            return gridPane;
        public void mouseClicked(MouseEvent me)
            JPanel panel = (JPanel)me.getSource();
            Component component = panel.findComponentAt(me.getX(), me.getY());
            System.out.println(component.getClass().getName());
            if (component instanceof JLabel)
                if(lastSelected != null)
                    ((JLabel)lastSelected).setForeground(Color.black);
                ((JLabel)component).setForeground(Color.red);
                // Since there are gaps among the labels we need this in here.
                lastSelected = component;
            repaint();
        public void mouseEntered(MouseEvent arg0){}
        public void mouseExited(MouseEvent arg0){}
        public void mousePressed(MouseEvent arg0){}
        public void mouseReleased(MouseEvent arg0){}
    }

  • GUI freezes randomly

    I am writing a program which communicates with a CLIPS database using JClips library (generally the programs asks some questions and in the end prints an answer, kind of questionnaire). The program randomly freezes. I'll try to describe exactly the proble.
    The main function calls the createAndShowGUI() method which shows an introduction screen with one button on it. The button starts the program. There are three main JPanels. First one with a TextArea (it shows the question) and two buttons (clear,confirm). Second one has a CardLayout with 4 cards (first one with radio buttons, another wict check box, one with text field, and one with a TextPane). When the program starts it adds an Observer and waits for CLIPS. Every message (in a specified format) I receive from CLIPS is precessed in the update mathod. Depending on what kind of message it is it shows apropriate card (radio buttons, check boxes, text field or text pane with an answer). If it is a question, when one selcts preferred answer (using for example radio box) and press the Confirm button a message with an answer is sent back to CLIPS. Then the database responds with another question or if it was th last one it sends an answer (a result of its deduction process).
    This is the place wher the program freezes - after pressing the Confirm button. I really don't know the reason. It doesn't happen every time I run the program (about 15% probability that it hangs ;)) and it doesn't happen in a specific moment of the questionnaire.
    This is my first Java program (and first object-oriented program) so this might be really basic problem.
    The source code: http://avatar02.republika.pl/ExpertSystem.java

    I've implemented these techniques and here is what it prints. This is the part of method responsible for printng.
    System.out.println("\t" + stackEntry.getClassName()
              + "." + stackEntry.getMethodName() + " ["
              + stackEntry.getLineNumber() + "]");And this is part of a log that these debug methods print out:
    Event [19297865] java.awt.event.MouseEvent is taking too much time on EDT (563)
    AWT-EventQueue-1 / BLOCKED
         sun.awt.AppContext.get [-1]
         javax.swing.RepaintManager.currentManager [-1]
         javax.swing.RepaintManager.currentManager [-1]
         javax.swing.RepaintManager.currentManager [-1]
         javax.swing.JComponent.repaint [-1]
         java.awt.Component.repaint [-1]
         javax.swing.plaf.basic.BasicButtonListener.stateChanged [-1]
         javax.swing.AbstractButton.fireStateChanged [-1]
         javax.swing.AbstractButton$Handler.stateChanged [-1]
         javax.swing.DefaultButtonModel.fireStateChanged [-1]
         javax.swing.DefaultButtonModel.setPressed [-1]
         javax.swing.plaf.basic.BasicButtonListener.mouseReleased [-1]
         java.awt.Component.processMouseEvent [-1]
         javax.swing.JComponent.processMouseEvent [-1]
         java.awt.Component.processEvent [-1]
         java.awt.Container.processEvent [-1]
         java.awt.Component.dispatchEventImpl [-1]
         java.awt.Container.dispatchEventImpl [-1]
         java.awt.Component.dispatchEvent [-1]
         java.awt.LightweightDispatcher.retargetMouseEvent [-1]
         java.awt.LightweightDispatcher.processMouseEvent [-1]
         java.awt.LightweightDispatcher.dispatchEvent [-1]
         java.awt.Container.dispatchEventImpl [-1]
         java.awt.Window.dispatchEventImpl [-1]
         java.awt.Component.dispatchEvent [-1]
         java.awt.EventQueue.dispatchEvent [-1]
         TracingEventQueueJMX.dispatchEvent [18]
         java.awt.EventDispatchThread.pumpOneEventForFilters [-1]
         java.awt.EventDispatchThread.pumpEventsForFilter [-1]
         java.awt.EventDispatchThread.pumpEventsForHierarchy [-1]
         java.awt.EventDispatchThread.pumpEvents [-1]
         java.awt.EventDispatchThread.pumpEvents [-1]
         java.awt.EventDispatchThread.run [-1Could you please help me analyse this output? ;)
    Thanks for replies.
    Edited by: Avatar on Nov 29, 2007 10:26 AM

  • Fatal bug in LAF project code

    I found a fatal error which causes the Java applet to freeze in forms 10.1.2.0.2 on both Solaris and Windows XP. I tested laf versions 1.3.3, 1.3.3.1 and 1.3.4 as well as Java versions 1.4.2 and 1.5 and 1.6. The bug is caused when you use the implementation class, oracle.forms.fd.LAF_XP_Button, on a button, then call another form, then exit the called form but the original form sets one of the buttons to disabled (as in a pre-record trigger of a block). This causes the java code to go into an infinite loop trying to repaint a button it apparently has no access to. The applet then freezes. The only errors I was able to get were in the java console. They always start with java.lang.StackOverFlow Error and then vary as to which component got the errors (Java.awt.component.repaint, java.awt.ContainerOrderFocusTraversalPolicy, java.lang.character.ToLowerCase) etc.
    I don't know whether this can be fixed or not but I wanted to warn everyone since this is a tough bug to find.
    Everything else I've tested in the laf project works great. Hats off to Francois Degrelle for all of his hard work!

    Francois,
    Here are some more details. I have a form, call it A, with a data grid. When a user clicks on say the 4th row, I check one of the columns to see if it is populated. If it is not populated, a button with a call_form is enabled. The user presses the button and goes into form B. When they exit form B, form A's data grid is repopulated and the navigation brings them to the first record. In my case, the first record has the field populated which sets the button to disabled via a pre-record trigger on the form. The java applet then hangs when it tries to repaint the buttons. All of the buttons on both screens use the implementation class. When I remove the implementation class for the buttons on Form A, there are no errors.
    Thanks,

  • Set text in table cell to bold

    I am trying to get the text in a table cell to alternate between plain and bold on a ctrl-click.
    The setFont() statements seeming have no effect.
    Can anyone help?
    Self Contained thing here:
    package boldTableCell;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.Point;
    import java.awt.event.ActionEvent;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTable;
    import javax.swing.UIManager;
    import javax.swing.table.DefaultTableModel;
    public class MyTable extends JTable implements MouseListener {
         private boolean isBold = false;
         private String[] columnNames = {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"};
         private Object[][] data = {
                   {"Mary", "Campione", "Snowboarding", new Integer(5), new Boolean(false)},
                   {"Alison", "Huml", "Rowing", new Integer(3), new Boolean(true)},
                   {"Kathy", "Walrath", "Knitting", new Integer(2), new Boolean(false)},
                   {"Sharon", "Zakhour", "Speed reading", new Integer(20), new Boolean(true)},
                   {"Philip", "Milne", "Pool", new Integer(10), new Boolean(false)},
          * constructor
         public MyTable() {
              super();
              DefaultTableModel defaultTableModel = new DefaultTableModel(data, columnNames);
              this.setModel(defaultTableModel);
              this.setName("My Table");
              setListeners();
          * set listeners
         private void setListeners() {
              addMouseListener(this);
         // on ctrl-click in variable column, flip bold/not bold
         @Override
         public void mouseClicked(MouseEvent event) {
              System.out.println ("mouseClicked(): # of clicks: " + event.getClickCount());
              // ctrl -click
              if ((event.getModifiers() & ActionEvent.CTRL_MASK) > 0) {
                   System.out.println("ctrl-click");
                   Point point = event.getPoint();
                   int row = rowAtPoint(point);
                   int column = columnAtPoint(point);
                   // if not valid then return
                   if ( row < 0 || column < 0) {
                        return;
                   // if this click was on the variable column
                   if (column == 0) {
                        System.out.println("ctrl-click on column 0 ");
                        Component component = super.prepareRenderer(this.getCellRenderer(row, column), row, column);
                        // now get the current font used for this cell
                        Font font = component.getFont();
                        isBold = ! isBold; // flip boolean
                        if (isBold) {
                             System.out.println ("ctrl-click: bold: " + isBold);
                             component.setFont(font.deriveFont(Font.BOLD));
                             component.setForeground(getForeground()); // otherwise text disappears
                             //     (JLabel)t.getHeaderRenderer()).setFont(new Font(("Courier", Font.BOLD, 12));
                        else { // not bold
                             System.out.println ("ctrl-click: not bold: " + isBold);
                             component.setFont(font.deriveFont(Font.PLAIN));
                             component.setForeground(getForeground()); // otherwise text disappears
                        component.invalidate();
                        component.repaint();
                        this.invalidate();
                        this.repaint();
                   } // end if click on definition column
         } // end mouseClicked
         @Override
         public void mouseEntered(MouseEvent arg0) {
         @Override
         public void mouseExited(MouseEvent arg0) {
         @Override
         public void mousePressed(MouseEvent arg0) {
         @Override
         public void mouseReleased(MouseEvent arg0) {
          * @param args
         public static void main(String[] args) {
              try {
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              catch (Exception e){
                   e.printStackTrace();
              final JPanel jPanel = new JPanel();
              final MyTable myTable = new MyTable();
              jPanel.add(myTable);
              final JFrame frame = new JFrame();
              frame.add(jPanel, BorderLayout.CENTER);
              frame.setTitle("My Panel");
              frame.setPreferredSize(new Dimension(400, 150));
              frame.addWindowListener(new WindowAdapter(){
                   @Override
                   public void windowClosing(WindowEvent e) {
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              frame.setLocation(300, 200);
              frame.pack();
              frame.setVisible(true);
    }Edited by: allelopath on Jul 8, 2010 11:06 AM
    Edited by: allelopath on Jul 8, 2010 11:07 AM

    got it
    package boldTableCell;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.Point;
    import java.awt.event.ActionEvent;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.util.ArrayList;
    import java.util.List;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTable;
    import javax.swing.UIManager;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellRenderer;
    public class MyTableWithCustomRenderer extends JTable implements MouseListener {
         private boolean isBold = false;
        private List<Boolean> isBoldList;
         private String[] columnNames = {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"};
         private Object[][] data = {
                   {"Mary", "Campione", "Snowboarding", new Integer(5), new Boolean(false)},
                   {"Alison", "Huml", "Rowing", new Integer(3), new Boolean(true)},
                   {"Kathy", "Walrath", "Knitting", new Integer(2), new Boolean(false)},
                   {"Sharon", "Zakhour", "Speed reading", new Integer(20), new Boolean(true)},
                   {"Philip", "Milne", "Pool", new Integer(10), new Boolean(false)},
          * constructor
         public MyTableWithCustomRenderer() {
              super();
              // initialize bold for each row to false
              isBoldList = new ArrayList<Boolean>(5);
              for (int row = 0; row < 5; row++) {
                   isBoldList.add(row, false);     
              DefaultTableModel defaultTableModel = new DefaultTableModel(data, columnNames);
              this.setModel(defaultTableModel);
              this.setName("My Table");
              setListeners();
          * set listeners
         private void setListeners() {
              addMouseListener(this);
         // on ctrl-click in column 0 , flip bold/not bold
         @Override
         public void mouseClicked(MouseEvent event) {
              // ctrl -click
              if ((event.getModifiers() & ActionEvent.CTRL_MASK) > 0) {
                   System.out.println("mouseClicked(): ctrl-click");
                   Point point = event.getPoint();
                   int row = rowAtPoint(point);
                   int column = columnAtPoint(point);
                   // if not valid then return
                   if ( row < 0 || column < 0) {
                        return;
                   // if this click was on column 0
                   if (column == 0) {
                        isBoldList.set(row, ! isBoldList.get(row)); // flip boolean for this row
                        this.invalidate();
                        this.repaint();
         } // end mouseClicked
         @Override
         public void mouseEntered(MouseEvent arg0) {
         @Override
         public void mouseExited(MouseEvent arg0) {
         @Override
         public void mousePressed(MouseEvent arg0) {
         @Override
         public void mouseReleased(MouseEvent arg0) {
        @Override
        public Component prepareRenderer (TableCellRenderer renderer,int row, int column) {
            Component component = super.prepareRenderer(renderer, row, column);
            // now get the current font used for this cell
            Font font = component.getFont();
            if (column == 0) {
                 if (isBoldList.get(row)) {
                      System.out.println ("prepareRenderer(): ctrl-click: bold: " + isBold);
                      component.setFont(font.deriveFont(Font.BOLD));
                      component.setForeground(getForeground()); // otherwise text disappears
                 else { // not bold
                      System.out.println ("prepareRenderer(): ctrl-click: not bold: " + isBold);
                      component.setFont(font.deriveFont(Font.PLAIN));
                      component.setForeground(getForeground()); // otherwise text disappears
              return component;
          * @param args
         public static void main(String[] args) {
              try {
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              catch (Exception e){
                   e.printStackTrace();
              final JPanel jPanel = new JPanel();
              final MyTableWithCustomRenderer myTable = new MyTableWithCustomRenderer();
              jPanel.add(myTable);
              final JFrame frame = new JFrame();
              frame.add(jPanel, BorderLayout.CENTER);
              frame.setTitle("My Panel - Custom Renderer");
              frame.setPreferredSize(new Dimension(400, 150));
              frame.addWindowListener(new WindowAdapter(){
                   @Override
                   public void windowClosing(WindowEvent e) {
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              frame.setLocation(300, 200);
              frame.pack();
              frame.setVisible(true);
    }Edited by: allelopath on Jul 8, 2010 2:07 PM

  • Draw a line after zoom in

    Hi All,
    I want to draw a line after zooming in/out the image. If the image is not scaled, then ever thing is fine. But once I scaled the image and draw the line, the position is not coming correctly. Can you correct me, what's my mistake?
    package imagetest;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class ZoomAndDraw extends JPanel
        private java.awt.image.BufferedImage image = null;
        private Line2D.Double line = null;
        private double scale = 1.0;
        private int value = 16;
        private double translateX = 0.0;
        private double translateY = 0.0;
        private MouseManager manager = null;
        public ZoomAndDraw()
            line = new Line2D.Double();
            readImage();
            manager = new MouseManager(this);
            addMouseListener(manager);
            addMouseMotionListener(manager);
        private void readImage()
            try
                image = javax.imageio.ImageIO.read(new java.io.File("D:/IMG.JPG"));
            catch (Exception ex)
        @Override
        public Dimension getPreferredSize()
            if (image != null)
                int w = (int) (scale * image.getWidth());
                int h = (int) (scale * image.getHeight());
                return new Dimension(w, h);
            return new Dimension(640, 480);
        @Override
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
            if (image == null)
                return;
            double x = (getWidth() - scale * image.getWidth()) / 2;
            double y = (getHeight() - scale * image.getHeight()) / 2;
            g2.translate(x, y); // move to center of image
            g2.scale(scale, scale); // scale
            translateX = 0 - x * (1 / scale);
            translateY = 0 - y * (1 / scale);
            g2.translate(translateX, translateY); // move back
            g2.drawImage(image, 0, 0, this);
            g2.setColor(Color.RED);
            g2.draw(line);
            g.dispose();
        public void setLine(Point start, Point end)
            line.setLine(start, end);
            repaint();
        public void addLine(Point start, Point end)
            line.setLine(start, end);
            repaint();
        public void ZoomIn()
            value++;
            scale = (value + 4) / 20.0;
            revalidate();
            repaint();
        public void ZoomOut()
            if (value <= -3)
                return;
            value--;
            scale = (value + 4) / 20.0;
            revalidate();
            repaint();
        class MouseManager extends MouseAdapter
            ZoomAndDraw component;
            Point start;
            boolean dragging = false;
            public MouseManager(ZoomAndDraw displayPanel)
                component = displayPanel;
            @Override
            public void mousePressed(MouseEvent e)
                start = e.getPoint();
                dragging = true;
            @Override
            public void mouseReleased(MouseEvent e)
                if (dragging)
                    component.addLine(start, e.getPoint());
                    component.repaint();
                dragging = false;
            @Override
            public void mouseDragged(MouseEvent e)
                Point end = e.getPoint();
                if (dragging)
                    component.setLine(start, end);
                    component.repaint();
                else
                    start = end;
        public static void main(String[] args)
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            ZoomAndDraw zoomAndDraw = new ZoomAndDraw();
            //Zoom in call
            zoomAndDraw.ZoomIn();
            zoomAndDraw.ZoomIn();
            zoomAndDraw.ZoomIn();
            frame.add(zoomAndDraw);
            frame.setPreferredSize(new Dimension(640, 480));
            frame.setSize(new Dimension(640, 480));
            frame.setVisible(true);
    }Thanks and Regards
    Raja.

    Hi,
    I'm having one more doubt. Just assume, after calling the ZoomIn(), I am drawing a line.
    Subsequent ZoomIn() calls (let's say 5 times), changed the actual line position. How do I synchronize the zoom in call with the line coordinates?
    public void FireZoomIn()
            new Thread(new Runnable()
                public void run()
                    try
                        Thread.sleep(3000);
                    catch (InterruptedException iex)
                    int count = 0;
                    while (count++ < 5)
                        ZoomIn();
            }).start();
    public void mouseReleased(MouseEvent e)
                if (dragging)
                    component.addLine(start, e.getPoint());
                    component.repaint();
                    component.FireZoomIn();
                dragging = false;
            }Thanks and Regards
    Raja.

  • Need help with this error

    Hi,
    I keep getting this error when running my application. Classes compile correctly.
    I have two classes, one is the main GUI, the other the main functionality. I get the error below when I try and create an Object of the GUI within the other class. The same happens vice versa.
    Exception in thread "main" java.lang.StackOverflowError
            at sun.awt.AppContext.get(AppContext.java:547)
            at javax.swing.SwingUtilities.appContextGet(SwingUtilities.java:1770)
            at javax.swing.RepaintManager.currentManager(RepaintManager.java:81)
            at javax.swing.RepaintManager.currentManager(RepaintManager.java:100)
            at javax.swing.JComponent.repaint(JComponent.java:4518)
            at java.awt.Component.repaint(Component.java:2731)
            at javax.swing.JComponent.setFont(JComponent.java:2639)
            at javax.swing.LookAndFeel.installColorsAndFont(LookAndFeel.java:89)
            at
    javax.swing.plaf.basic.BasicPanelUI.installDefaults(BasicPanelUI.java:49)
            at
    javax.swing.plaf.basic.BasicPanelUI.installUI(BasicPanelUI.java:39)
            at javax.swing.JComponent.setUI(JComponent.java:652)
            at javax.swing.JPanel.setUI(JPanel.java:131)
            at javax.swing.JPanel.updateUI(JPanel.java:104)
            at javax.swing.JPanel.<init>(JPanel.java:64)
            at javax.swing.JPanel.<init>(JPanel.java:87)
            at javax.swing.JPanel.<init>(JPanel.java:95)
            at PokerGUI.<init>(PokerGUI.java:172)
            at PokerMain.<init>(PokerMain.java:38)Can anybody offer some insight into this, it's driving me nuts!
    Thanks
    Jimmy.

    Your design is screwed and you go to infinite recursion? I'm betting that.
    Show some relevant pieces of code properly formatted (use the code tags).

  • Centering a form

    I'm new to java programming. My program is up and running, however when I load it, the form loads in the top left corner. I'm using a form with the contents in a FlowLayout. Any advice on how to get the form to load in the center of the screen.
    Thanks,

    I have done a helper class you can use if you want to.
    import java.awt.Dimension;
    import java.awt.Component;
    * This class is a Util for awt Component and could be
    * used to place them in center of an other.
    * @author  <a href="mailto:[email protected]">Bo Regnlin</a>
    * @version 1.0
    public class ComponentUtil
               * Use this static method if you want to center
         * and set its propsion compared to the size of
         * the current users screen size.
         * Valid percent is between +-(0-100) minus is treated
         * as plus, bigger than 100 is always set to 100.
               *@param  component The component you want to center and set size on.
               *@param  percentOfScreen The percent of the current screensize you want
         *        the component to be.
      public static void centerComponentInWindow(Component component, int percentOfScreen)
        if(percentOfScreen < 0)
          centerComponentInWindow(component, - percentOfScreen);
          return;
        if(percentOfScreen > 100)
          centerComponentInWindow(component, 100);
          return;
        double percent = percentOfScreen / 100.d;
        Dimension dimension = component.getToolkit().getScreenSize();
        component.setSize((int)(dimension.getWidth()*percent),
                          (int)(dimension.getHeight()*percent));
        centerComponentInWindow(component);
               * Use this static method if you want to center a component in Window.
               *@param  component The component you want to center in window.
      public static void centerComponentInWindow(Component component)
        Dimension dimension = component.getToolkit().getScreenSize();
        component.setLocation((int)((dimension.getWidth()-component.getWidth())/2),
                              (int)((dimension.getHeight()-component.getHeight())/2));
        component.validate();
        component.repaint();
               * Use this static method if you want to center
         * a component over an other component.
               *@param  parent The component you want to use to place it on.
               *@param  toBeCentered The component you want to center.
      public static void centerComponentInComponent(Component parent, Component toBeCentered)
        toBeCentered.setLocation((int)parent.getX() + (int)((parent.getWidth()-toBeCentered.getWidth())/2),
                                (int)parent.getY() + (int)((parent.getHeight()-toBeCentered.getHeight())/2));
        toBeCentered.validate();
        toBeCentered.repaint();
    }

Maybe you are looking for