Java 2d - Painting problem

hi, I have problem with painting. Every time, when I minimize and then maximize application, the whole screen starts to "repaint" it's content (everything what was drawed). Normally it's not so big problem you don't register it, but I'm using some delay when drawing (Thread.sleep (x) ), and
then it's BIG problem, because always when minimized/maximized it starts to paint again and it's clearly visible...Also when I cover window of my application with another window, and then hide it, it do same thing. It's possible to avoid this? It's very unpleasant. thanx a lot
PS: Do not tell me not to use delay :) It's absolutely necessary in my application, because I must use some animations...

It does make logical sense if you were for instance calling the sleep method within a different thread, such as the EventQueue thread.
Rather than use the sleep method to create your delays, use a javax.swing.Timer thread set to a specific delay.
This way the animation is painted to the panel on a seperate thread.

Similar Messages

  • Java Window Painting Problems

    I am just getting into Java so forgive me if this a newbie question because well, I'm a newbie.
    I downloaded JBuilder 6.0 and got to work learning the language. The problem is that anything I use written in the Java lanuage when I move the Window it scambles(We are talking aplications). So if IE was written in Java and you moved this window all the text and buttons will suddenly appear under the old ones when your mouse clicks or moves over them. So it apears that all the controls have shifted. Another problem is using the scroll bar makes the text apear scambled and like lines are going through them. The only way I know to fix this is force it to completly re-draw by Maximizing the window and then Minimizing it.
    I would really like to solve this problem so using Java opposed to C++ is practicle. I mean I do like to move the Windows around. My brother is having the same problem when he uses LimeWire; a Napster like program written in Java.
    I am running:
    Athlon XP 1.4ghz
    Asus A7V266 w/ 256 DDR(2100@CL2)
    Voodoo 3 3000
    Windows ME
    Everything Java is up to date.
    Thanks,
    ~`DarkEyes`~

    Hi,
    I am facing excatly the same problem as you've mentioned. I am not using Windows blind or anyother program to alter the look and feel of my OS.
    I am running WIN 2K Professional Edition. Any further information on this would really help as I have already spent days trying to solve the painting issue.
    Thanks,
    Y
    If anyone would like to know what was going on
    on I'll tell you. Basicly I use Litestep and
    WindowBlinds as a way that I can create my own OS
    design. Litestep Replaces the Explorer shell and you
    get to design now it looks, feels and enteracts. And
    WindowBlinds lets you skin and change the way Windows
    act.
    I should have though of this before, but what
    at happens is WindowBlinds has to intercept the Calls
    to draw the windows and then it draws then itself. The
    problem being I don't think as of right now it works
    when it intercepts Java calls.
    I'll just have to unload WindowBlinds when I program
    Java or use it. Not the best solution but its a
    start.
    Thanks for the help,
    ~`DarkEyes`~

  • JMenuItem painting Problem

    Hi,
    I have painting problem with adding the JMenuItems dynamically. In the screen1 figure shown below, Menu 2 has has total 10 items, but initially we will show only three items. When the user clicks on the menu item ">>" all the Ten Items in Menu 2 are shown. But, All the 10 items are inserted in a compressed manner as shown in screen 2. When i click on the Menu 2 again, is shows properly as shown in screen 3.
    screen 1:
    <img src="http://img.photobucket.com/albums/v652/petz/Technical/screen1.jpg" border="0" alt="Screen 1"/>
    screen 2:
    <img src="http://img.photobucket.com/albums/v652/petz/Technical/screen2.jpg" border="0" alt="Screen 2"/>
    screen 3:
    <img src="http://img.photobucket.com/albums/v652/petz/Technical/screen3.jpg" border="0" alt="Screen 3"/>
    Here is the code:
    import java.awt.GridLayout;
    import java.awt.event.KeyEvent;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    public class MenuUI implements MouseListener
        JFrame frame;
        JMenuBar menubar;
        JMenu menu1,menu2;
        JMenuItem menuItem;
        JMenuItem lastMenuItem;
        String MENU1_ITEMS[] = {"ONE","TWO","THREE","FOUR","FIVE"};
        String MENU2_ITEMS[] = {"ONE","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE","TEN"};
        int MIN_MENU = 3;
        public MenuUI()
            menubar = new JMenuBar();
            /*menu1 = new JMenu("Menu 1");
            menu1.setMnemonic(KeyEvent.VK_1);
            menu1.getPopupMenu().setLayout(new GridLayout(5,1));
            menu2 = new JMenu("Menu 2");
            menu2.setMnemonic(KeyEvent.VK_2);
            menu2.getPopupMenu().setLayout(new GridLayout(5,2));*/
            menu1 = new JMenu("Menu 1");
            menu1.setMnemonic(KeyEvent.VK_1);
            menu2 = new JMenu("Menu 2");
            menu2.setMnemonic(KeyEvent.VK_2);
            menubar.add(menu1);
            menubar.add(menu2);
            createMinMenuItems();
            frame = new JFrame("MenuDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setJMenuBar(menubar);
            frame.setSize(500, 300);
            frame.setVisible(true);
        public void createMinMenuItems()
            for (int i = 0; i < MIN_MENU; i++)
                menuItem = new JMenuItem(MENU1_ITEMS);
    menu1.add(menuItem);
    lastMenuItem = new JMenuItem(">>");
    lastMenuItem.addMouseListener(this);
    menu1.add(lastMenuItem);
    for (int i = 0; i < MIN_MENU; i++)
    menuItem = new JMenuItem(MENU2_ITEMS[i]);
    menu2.add(menuItem);
    lastMenuItem = new JMenuItem(">>");
    lastMenuItem.addMouseListener(this);
    menu2.add(lastMenuItem);
    private void showAllMenuItems(int menuNo)
    if(menuNo == 1)
    menu1.remove(MIN_MENU);
    for (int i = MIN_MENU; i < MENU1_ITEMS.length; i++)
    menuItem = new JMenuItem(MENU1_ITEMS[i]);
    menu1.add(menuItem);
    menu1.updateUI();
    else if(menuNo == 2)
    menu2.removeAll();
    menu2.getPopupMenu().setLayout(new GridLayout((MENU2_ITEMS.length),1));
    for (int i = 0; i < MENU2_ITEMS.length; i++)
    menuItem = new JMenuItem(MENU2_ITEMS[i]);
    //menuItem.setMinimumSize(new Dimension(35,20));
    menu2.add(menuItem);
    menu2.updateUI();
    //menu2.getPopupMenu().invalidate();
    //menu2.getPopupMenu().repaint();
    //menubar.repaint();
    //menubar.invalidate();
    //menubar.getParent().repaint();
    /* (non-Javadoc)
    * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
    public void mousePressed(MouseEvent arg0)
    System.out.println("mousePressed: Menu 1 selected: "+menu1.isSelected());
    System.out.println("mousePressed: Menu 2 selected: "+menu2.isSelected());
    if(menu1.isSelected())
    System.out.println("mousePressed: Menu 1: Show All Items");
    showAllMenuItems(1);
    else if(menu2.isSelected())
    System.out.println("mousePressed: Menu 2: Show All Items");
    showAllMenuItems(2);
    /* (non-Javadoc)
    * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
    public void mouseClicked(MouseEvent evt)
    /* (non-Javadoc)
    * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
    public void mouseEntered(MouseEvent arg0)
    /* (non-Javadoc)
    * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
    public void mouseExited(MouseEvent arg0)
    /* (non-Javadoc)
    * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
    public void mouseReleased(MouseEvent arg0)
    public static void main(String[] args)
    MenuUI ui = new MenuUI();

    // menu2.updateUI();
    menu2.getPopupMenu().setVisible(false);
    menu2.getPopupMenu().setVisible(true);

  • Help Please, with Annoying painting problem.

    Hi:
    I keep running in to this annoying problem:
    Swing Components not being re-drawn properly after:
    Windows turns on the screensaver
    or to a lesser degree if the Java program is Iconified / deiconified.
    Components with Images on them get corrupted and the image is not drawn properly, maybe just the top cm or so, but it is annoying..
    And I can't figure out what or if anything I am doing wrong.
    It happens in a few of my applications.........
    mostly those wher I have overidden paintComponent()
    If someone would like to see if they have the same thing happen, below is an example that demonstrates the problem.
    You will probably need to fiddle with you power settings so that you monitor blanks after 1 min. to avoid having to wait too long.
    Run the program, wait for screen to blank out, bring screen back,...
    If the java picture is not corrupt try re-sizing the JFrame and see what happens.
    I am using Win98SE
    I have Java:
    java version "1.4.2-beta"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2-beta-b19)
    Java HotSpot(TM) Client VM (build 1.4.2-beta-b19, mixed mode)
    I would appreciate someone trying this out. Even if it doesn't happen for them.
    Or maybe there is a glaring Error in my code.... And if so I could fix it..
    Here is an exmple program to demonstrate this.
    Two classes, The JPanel was obviously meant to do other things but I cut it down..
    The main:
    import java.awt.BorderLayout;
    import java.awt.Container;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.ImageIcon;
    import java.net.*;
    public class Test extends JFrame
         public Test()
              super("Test");
              Container content = this.getContentPane();
              content.setLayout( new BorderLayout() );
              URL url = null;
              Class ThisClass = this.getClass();
              url=ThisClass.getResource("Background.jpg");
              StarPanel panel = new StarPanel( url );
              content.add( panel , BorderLayout.CENTER );
              this.setDefaultCloseOperation(EXIT_ON_CLOSE);
              this.setSize(400,400);
              this.setVisible( true );
         public static void main( String[] args )
              Test Example = new Test();
    }The JComponent - with overrriden paintComponent()
    import java.awt.Image;
    import javax.swing.JComponent;
    import javax.swing.JPanel;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.MediaTracker;
    import java.awt.Toolkit;
    import java.net.*;
         cut down version
    public class StarPanel extends JPanel
    private Image image = null;
    private boolean imageLoaded = false;
         public StarPanel( URL imageLocation )
              super();
              this.setOpaque( true );
              loadImage( imageLocation );
         public boolean isOpaque()
              return true;
         public Image getImage()
              return this.image;
         public boolean hasImage()
              return imageLoaded;
         public void loadImage( URL imageLocation )
              boolean goodLoad = true;
              boolean Test = false;
              Toolkit T = this.getToolkit();
              image = T.getImage( imageLocation );
              prepareImage(image, this);
              MediaTracker Tracker = new MediaTracker( this );
              Tracker.addImage( image , 0 );
              try
                   Tracker.waitForID( 0 );
              catch( InterruptedException IE )
                   System.out.println( "Interrupted loading Image for StarPanel: " + IE.getMessage() );
                   goodLoad = false;
              Test = Tracker.isErrorID( 0 );
              if( Test )
                   goodLoad = false;
              if( !goodLoad )
                   imageLoaded = false;
              else
                   imageLoaded = true;
              Tracker = null;
         sans any error checking
         protected void paintComponent(Graphics g)
              super.paintComponent( g );
              Graphics2D g2D = (Graphics2D) g;
              boolean T = g2D.drawImage(this.getImage(), 0, 0, this.getWidth(), this.getHeight(), this );
    }I have tried quite a few different approaches to remove or minimize this problem, and have read everything I can here on paintComponent() and etc
    Help would be appreciated.
    No dukes cos I somehow have less than 0.
    Arrg my code was all neat - before I pasted it in to the code tags.

    I tried your code and did not notice any painting problems. I'm using JDK1.4.1 on Windows 98.
    I don't see any problems with your code. Here is the thread I usually recommend when people want to add an image to a component, in case you want to run another test:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=316074

  • Sir i am using datasocket read ,i am communicating with java but my problem is that bcz im using while loop to see if value has changed my labview consumes all the processors time ,sir i want a event like thing so that while loop is not in continuous loop

    sir i have given lot of effort but i am not able to solve my problem either with notifiers or with occurence fn,probably i do not know how to use these synchronisation tools.

    sir i am using datasocket read ,i am communicating with java but my problem is that bcz im using while loop to see if value has changed my labview consumes all the processors time ,sir i want a event like thing so that while loop is not in continuous loopHi Sam,
    I want to pass along a couple of tips that will get you more and better response on this list.
    1) There is an un-written rule that says more "stars" is better than just one star. Giving a one star rating will probably eliminate that responder from individuals that are willing to anser your question.
    2) If someone gives you an answer that meets your needs, reply to that answer and say that it worked.
    3) If someone suggests that you look at an example, DO IT! LV comes with a wonderful set of examples that demonstate almost all of the core functionality of LV. Familiarity with all of the LV examples will get you through about 80% of the Certified LabVIEW Developer exam.
    4) If you have a question first search the examples for something tha
    t may help you. If you can not find an example that is exactly what you want, find one that is close and post a question along the lines of "I want to do something similar to example X, how can I modify it to do Y".
    5) Some of the greatest LabVIEW minds offer there services and advice for free on this exchange. If you treat them good, they can get you through almost every challenge that can be encountered in LV.
    6) If English is not your native language, post your question in the language you favor. There is probably someone around that can help. "We're big, we're bad, we're international!"
    Trying to help,
    Welcome to the forum!
    Ben
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction

  • Painters (java.awt.Paint interface)

    Hello,
    I would like to implement a collection of painters (like GradientPaint, TexturePaint ..). Unfortunatelly, I found little information regarding this topic on the web. I found out that I need to implement the java.awt.Paint interface (and everything that it implies: PaintContext etc..). Do you know of any web site that might have some form of collection of this painters, or more complex information like algorithms for simple textures...Mabe I am asking the question wrong, that's why any links to basic resources that I can start with are welcome. I have allready taken a look at :
    http://swing-fx.blogspot.com/2008/05/glossy-and-shiny-shapes-with-paint-and.html
    http://drj11.wordpress.com/2007/04/02/subclassing-javaawtpaint/
    These helped me to understand the logic..but I feel left somwhere in the air with only this information.
    Any help is appreciated!
    Regards,
    Radu Cosmin

    Hello,
    I would like to implement a collection of painters (like GradientPaint, TexturePaint ..). Unfortunatelly, I found little information regarding this topic on the web. I found out that I need to implement the java.awt.Paint interface (and everything that it implies: PaintContext etc..). Do you know of any web site that might have some form of collection of this painters, or more complex information like algorithms for simple textures...Mabe I am asking the question wrong, that's why any links to basic resources that I can start with are welcome. I have allready taken a look at :
    http://swing-fx.blogspot.com/2008/05/glossy-and-shiny-shapes-with-paint-and.html
    http://drj11.wordpress.com/2007/04/02/subclassing-javaawtpaint/
    These helped me to understand the logic..but I feel left somwhere in the air with only this information.
    Any help is appreciated!
    Regards,
    Radu Cosmin

  • Re   Java Stored Procedure Problem

    Ben
    There appear to be some problem with the forum. It doesn't want to show my response to your post with the subject "Java Stored Procedure Problem". See the answer to this thread for an example of how to do this...
    Is there a SAX parser with PL/SQL??

    Ben
    There appear to be some problem with the forum. It doesn't want to show my response to your post with the subject "Java Stored Procedure Problem". See the answer to this thread for an example of how to do this...
    Is there a SAX parser with PL/SQL??

  • "How to Resolve ORA-29532 Java 2 Permission Problems in RDBMS 8.1.6 and 8.1.7"

    I'm in the process of publishing the following note (134280.1), titled "How to Resolve ORA-29532 Java 2
    Permission Problems in RDBMS 8.1.6 and 8.1.7".
    It will be accessible from Oracle Support's "Metalink" site.
    "How to Resolve ORA-29532 Java 2 Permission Problems in RDBMS 8.1.6 and 8.1.7".
    Problem Description
    Periodically an application running in the Enterprise Java Engine
    (EJE) formerly known as the "Oracle 8i JVM", "the JSERVER component", or
    the "Aurora JVM" will fail with a "java 2" permissions error having the
    following format :
    Note : Message shown below have been reformatted for easier readability.
    java.sql.SQLException: ORA-29532: Java call terminated by uncaught Java exception:
    usually followed by a detailed error message similar to one of the following
    messages :
    Example # 1
    java.security.AccessControlException: the Permission
    (java.net.SocketPermission hostname resolve)
    has not been granted by dbms_java.grant_permission to
    SchemaProtectionDomain(SCOTT|PolicyTableProxy(SCOTT))
    Example # 2
    java.security.AccessControlException: the Permission
    (java.util.PropertyPermission * read,write)
    has not been granted by dbms_java.grant_permission to
    SchemaProtectionDomain(SCOTT|PolicyTableProxy(SCOTT))
    Example # 3
    java.security.AccessControlException: the Permission
    (java.io.FilePermission \matt1.gif read)
    has not been granted by dbms_java.grant_permission to
    SchemaProtectionDomain(SCOTT|PolicyTableProxy(SCOTT))
    Explanation
    The java 2 permission stated in line # 2 of each of the above "Examples"
    has not been granted to the user specified in line 4 of the above "Examples".
    Solution Description
    The methodology to solve this issue is identical for all java 2 permissions
    cases.
    1) Format a call "dbms_java.grant_permission" procedure as described below.
    2) Logon as SYS or SYSTEM
    3) Issue the TWO commands shown below
    4) Logoff as SYS or SYSTEM
    5) Retry your application
    For Example # 1
    1) Logon as SYS or SYSTEM
    2) Issue the following commands :
    a) call dbms_java.grant_permission('SCOTT',
    'java.net.SocketPermission',
    'hostname',
    'resolve');
    b) commit;
    Note: Commit is mandatory !!
    3) Logoff as SYS or SYSTEM
    4) Retry your application
    For Example # 2
    1) Logon as SYS or SYSTEM
    2) Issue the following commands :
    a) call dbms_java.grant_permission('SCOTT',
    'java.util.PropertyPermission',
    'read,write');
    b) commit;
    Note: Commit is mandatory !!
    3) Logoff as SYS or SYSTEM
    4) Retry your application
    For Example # 3
    1) Logon as SYS or SYSTEM
    2) Issue the following commands :
    a) call dbms_java.grant_permission('SCOTT',
    'java.io.FilePermission',
    '\matt1.gif',
    'read');
    b) commit;
    Note: Commit is mandatory !!
    3) Logoff as SYS or SYSTEM
    4) Retry your application
    References
    For more details on java 2 permissions and security within the EJE, review
    Chapter 5, in the Java Developer's Guide. entitled,
    "Security For Oracle8i Java Applications"
    The RDBMS 8.1.7 version can be found at :
    http://otn.oracle.com/docs/products/oracle8i/doc_library/817_doc/java.817/index.htm

    Hi, Don,
    I solved the problem of security exception I mentioned at java procedure topic as following:
    ORA-29532: Java call terminated by uncaught Java exception: java.lang.SecurityException
    I tried to use your solution as following:
    call dbms_java.grant_permission('SDE', 'java.net.SocketPermission', 'ORCL.COHPA.UCF.EDU','resolve');
    but SQL*plus gave me a error message:
    invalid collumn.
    What's the problem?
    However, I call a grant command as following:
    SQL> grant JAVASYSPRIV to sde;
    and then that exception is gone. What's the difference between dbms_java.grant_permission and grant command?
    Thanks
    Bing
    <BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by don -- oracle support:
    I'm in the process of publishing the following note (134280.1), titled "How to Resolve ORA-29532 Java 2
    Permission Problems in RDBMS 8.1.6 and 8.1.7".
    It will be accessible from Oracle Support's "Metalink" site.
    "How to Resolve ORA-29532 Java 2 Permission Problems in RDBMS 8.1.6 and 8.1.7".
    Problem Description
    <HR></BLOCKQUOTE>
    null

  • Paint problems in 1.4-RC1

    Is anyone else experiencing repaint problems with RC1? I've seen two intermittent things so far:
    1) When a modal JDialog is shown above its owner window, the contents of the owner window are being painted inside the JDialog
    2) Scroll bars (JScrollPane) are not being repainted properly when window is resized. Phantom scroll buttons remain at the old position.
    Any others out there?

    My JDK 1.4.0 Swing application does not paint very well on 2 out of 4 NT / SP5-6machines tested. Its OK on 2 machines and NOT OK on 2 others... The machines have mixture of different graphics cards.
    The base problem reminds me of 'running out of paint handles' in Win 3.1 days... i.e. the GUI fails to refresh and gets cluttered with 'random' strips, streched painting, general 'junk' that won't clear. Its quite serious because when the application window is moved the edit-box / buttons etc don't necessarily move at same time and get partially 'off the window' and stop working. Minimize/Maximize and drag overs by other apps don't clear it. The problem seems to get worse the longer the application is executed and seems to be even worse when there's more than 1 window up a time... i.e. it almost seems like 'lack of horsepower' in CPU but these machines are PIII 400MHZ with OK RAM so there should be enough CPU.
    Note that JDK 1.3 'corrects' the problem - i.e. running same code on JDK 1.3 (instead of JDK 1.4) works just fine and does NOT have the paint problems.
    ANY HELP APPRECIATED!!

  • Java Applet Panel problems with CardLayout

    Hi, I have a problem a I have been stucked for 2 days.
    I created 3 Panels to use with CardLayout. I would switch between those 3 panels depending on user interaction. I have some textfields and text areas on the 2nd and 3rd Panel. On the 1st panel, I would like to use g.drawstring to write some stuff on that panel, but the words would be blocked off if it goes to where the components are on the other panels.
    Thanks.

    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.font.*;
    public class CardTest extends Applet
        Panel panel;
        CardLayout cards;
        public void init()
        {   cards = new CardLayout();
            panel = new Panel(cards);
            panel.add("one", new GraphicPanel());
            panel.add("two", getPanel("panel two"));
            panel.add("three", getPanel("panel three"));
            setLayout(new BorderLayout());
            add(getNavPanel(), "North");
            add(panel);
        private Panel getNavPanel()
            final Button
                last = new Button("last"),
                next = new Button("next");
            ActionListener l = new ActionListener()
                public void actionPerformed(ActionEvent e)
                    Button button = (Button)e.getSource();
                    if(button == last)
                        cards.previous(panel);
                    if(button == next)
                        cards.next(panel);
            last.addActionListener(l);
            next.addActionListener(l);
            Panel panel = new Panel();
            panel.add(last);
            panel.add(next);
            return panel;
        private Panel getPanel(String s)
            Panel panel = new Panel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.weighty = 1.0;
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            panel.add(new Button("button"), gbc);
            panel.add(new TextArea(s, 8, 16), gbc);
            return panel;
        public static void main(String[] args)
            Applet applet = new CardTest();
            Frame f = new Frame();
            f.addWindowListener(new WindowAdapter()
                public void windowClosing(WindowEvent e)
                    System.exit(0);
            f.add(applet);
            f.setSize(400,400);
            f.setLocation(200,200);
            applet.init();
            f.setVisible(true);
    class GraphicPanel extends Panel
        Font font;
        String text;
        final int PAD = 25;
        public GraphicPanel()
            font = new Font("lucida bright regular", Font.PLAIN, 22);
            text = "Hello World";
        public void paint(Graphics g)
            super.paint(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            int w = getWidth();
            int h = getHeight();
            int dia = Math.min(w,h)/6;
            g2.setPaint(Color.blue);
            g2.drawLine(PAD, PAD, w - PAD, PAD);
            g2.drawLine(PAD, h - PAD, w - PAD, h - PAD);
            g2.setPaint(Color.green.darker());
            g2.drawOval(w/2 - dia/2, h*2/3, dia, dia);
            g2.setFont(font);
            FontRenderContext frc = g2.getFontRenderContext();
            float width = (float)font.getStringBounds(text, frc).getWidth();
            LineMetrics lm = font.getLineMetrics(text, frc);
            float x = (w - width)/2;
            float y = (h + lm.getHeight())/2 -lm.getDescent();
            g2.setPaint(Color.black);
            g2.drawString(text, x, y);
    }

  • Component paint problem:

    Hi everybody,
    I have just started playing with the Swing library
    recently, and I am experimenting with writing my
    own little customized component--a mini shape
    editor. There is one problem I am encountering.
    The circles that get re-drawn after a re-sizing
    of the window are crooked! However, when the
    circles were initially drawn to the compnent,
    they looked quite smooth. The only difference
    was that the circles were initially rendered
    via the graphics object that was obtained using
    the getGraphics() of the JComponent. I tried
    to force the paint method to use the graphics
    object returned from getGraphics(), but it
    does not rendered! Does anybody know what is
    the difference between these two graphics objects
    --the one returned from getGraphics() and the
    one passed into paint() by the system?
    Why am I getting the crooked line when the
    rendering is done via the paint graphics object?
    Thank you for your time in answering my question.
    --Chris

    Hi Richard,
    Thanks for your comments. As you suggested, I am
    posting some of my experimental code for discussion.
    Here is my derived class from JComponent:
    package SymbolEditorStuffs;
    import javax.swing.JComponent;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.Graphics;
    public class SymbolEditorWidget extends JComponent {
    * Constructor for SymbolEditorWidget.
    public SymbolEditorWidget() {
    super();
    canvas = new Canvas(this);     
    // Register mouse listeners to detect mouse
    // events.
    addMouseMotionListener(
    new SymbolEditorMouseMotionAdopter());
    addMouseListener(
    new SymbolEditorMouseAdopter());
    public void toolChanged(String toolName) {
    canvas.toolChanged(toolName);
    public Graphics getWidgetGraphics() {
    // Return this component's graphics object.
    return super.getGraphics();
    protected void paintComponent(Graphics graphics) {
    // Let the base class paints the component first.
    super.paintComponent(graphics);
    // Then the canvas handles the customized
    // component painting.
    canvas.paintCanvas(graphics);
    protected class SymbolEditorMouseMotionAdopter
    extends MouseMotionAdapter {
    public SymbolEditorMouseMotionAdopter() {
    super();
    public void mouseDragged(
    MouseEvent mouseEvent) {
    // Canvas handles mouse drag event.
    canvas.mouseDragged(mouseEvent);
    protected class SymbolEditorMouseAdopter
    extends MouseAdapter {
    public SymbolEditorMouseAdopter() {
    super();
    public void mousePressed(
    MousEvent mouseEvent) {
    // Canvas handles mouse presse events.
    canvas.mousePressed(mouseEvent);     
    public void mouseReleased(
    MouseEvent mouseEvent) {
    // Canvas handles mouse released events.
    canvas.mouseReleased(mouseEvent);     
    public void mouseClicked(
    MouseEvent mouseEvent) {
    // Canvas handles mouse clicked events.
    canvas.mouseClicked(mouseEvent);
    private Canvas canvas;
    As you correctly pointed out, the code for my repaint
    should be situated in the paintComponent(..., which
    I have overriden with my version. I suspect the base
    class' version of this function does something significant;
    therefore, I made a call to the base class version as
    well.
    The mouse events are what I use to manipulate the
    shapes with. Therefore, a shape that has been manipulated via the mouse must re-draw itself.
    Since the MouseEvent class comes with a function
    to access the component that received the mouse
    events, I am able to get hold of the graphics object
    of that component via the getGraphics(... It is
    with this graphics object that I use to redraw the
    manipulated shape.
    However, it is not true that I have two sets of code
    that redraw a shape. All shapes inherit from an
    interface that has a draw(...:
    interface Shape {
    public void draw(Graphics graphics);
    public void undraw(Graphics graphics);
    etc.
    class CircleShape implements Shape {
    public void draw(Graphics graphics) {
    // Draws the circle at the right location.
    etc.
    etc.
    Utimately, all draws for a shape are funnelled into
    this function. The only difference is where the
    graphics object came from. In the paint case,
    the graphics object was handed to me via the
    system. In all other cases, I have gotten hold of
    the graphics object via the getGraphics(,,,
    What struck me as odd was that when I manipalated
    a circle with the mouse, which caused a redraw of
    the circle via the graphics that I obtained through the getGraphcs(..., and then I resided the window, the
    same circle was NOT rendered as around as before
    the resize of the window. Since I called the
    drawOval(... at precisely the same location in both
    times, I expect the circle to be rendered with exactly
    the same roundness. This should be true because
    the drawOval(... is applying the same algorithm to
    render the circle in both cases. The fact that they are
    not the same roundness is the mystery that I cannot
    explain! What I expected was that both rendering
    should have produced the exact same circle! But
    they did not--one is of lower roundness quality than
    the other!!
    --Chris                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Java.lang.StackOverflowError problem, drawing images in applet :(

         * Paints the applet
        @Override
        public void paint(Graphics g)
            if(running && levelOne)
            g.setColor(Color.MAGENTA);
            g.drawString("HP Left: " + player.getHP(), 100, 10);
    //      g.drawString("Time Left: " + timer.getTime(), 170, 10);
            g.drawString("Score: " + player.getScore(), 30, 10);
            g.drawString("Required Score To Next Level: " + player.getScore() + "/3000", 100, 190);
            g.drawString("Level: 1", 30, 190);
            g.fillOval(x_pos - radius, y_pos - radius, 2 * radius, 2 * radius);
            if(start && storyStarted)
                try
                    update(g);
                    paintStory();
                catch(java.lang.StackOverflowError sofe)
                    System.exit(0);
            else if(start)
                g.drawImage(image, 0, 0, this);
                g.drawImage(gun, 200, 400, this);
         * Updates the paint() method and the applet
        @Override
        public void update(Graphics g)
            if(dbImage == null)
                dbImage = createImage(this.getWidth(), this.getHeight());
                dbG = dbImage.getGraphics();
            dbG.setColor(getBackground());
            dbG.fillRect(0, 0, this.getWidth(), this.getHeight());
            dbG.setColor(getForeground());
            paint(dbG);
            g.drawImage(dbImage, 0, 0, this);
        public void paintStory()
            getGraphics().drawImage(story1, 0, 0, this);
        }I know that my problem appears somewhere in the above written code, so if you would take a look, and try to help me fixing my problem! :D

    Vimsie wrote:
    I get a StackOverflowError, but the image isn't flickering!Err, the image is not flickering because there are no repaints happening anymore due to the StackOverflowError. This is hardly an argument for your approach.
    However, I have to admit I don't know how to solve your flickering problem. I've never used AWT but always SWING (but then I don't do applets).
    Maybe google can help?

  • Groupable + multiline table header paint problem

    hi, i try to make a groupable + multiline table header
    based on Nobuo Tamesama's code...
    there are some problems which i considered tolerable except one...
    the header didn't paint correctly when i set the autoResizeMode into autoresizemode_off
    and resize the columns pass the scrollpane width...
    thx in advance
    here's the complete code :
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.util.*;
    import javax.swing.border.*;
    import javax.swing.plaf.basic.*;
    public class GroupableHeaderExample extends JFrame {
        GroupableHeaderExample() {
            super("Groupable Header Example");
            JScrollPane sp = new JScrollPane();
            Object[][] data = {{"b1k1", "b1k2", "b1k3", "b1k4", "b1k5"}, {"b2k1", "b2k2", "b2k3", "b2k4", "b2k5"}};
            JTable table = new JTable(new DefaultTableModel(data, new Object[]{"Kol1", "Kol2\nmmm", "Kol3", "kol4\nmmm\nnnn", " \n \nKol5\nmmm"})) {
                protected JTableHeader createDefaultTableHeader() {
                    return new GroupableTableHeader(columnModel);
            table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            ColumnGroup cg = new ColumnGroup("CG", 0, 3);
            ColumnGroup cg2 = new ColumnGroup("CG2\nmmm", 1, 3);
            ColumnGroup cg3 = new ColumnGroup("CG3", 1, 2);
            GroupableTableHeader header = (GroupableTableHeader)table.getTableHeader();
            header.addColumnGroup(cg3);
            header.addColumnGroup(cg);
            header.addColumnGroup(cg2);
            header.fitHeight();
            sp.setViewportView(table);
            getContentPane().add(sp);
            setSize(400, 300);  
        public static void main(String[] args) {
            GroupableHeaderExample frame = new GroupableHeaderExample();
            frame.addWindowListener( new WindowAdapter() {
                public void windowClosing( WindowEvent e ) {
                    System.exit(0);
            frame.setVisible(true);
    class GroupableTableHeader extends JTableHeader {
        private Vector<ColumnGroup> columnGroups = new Vector<ColumnGroup>(1, 1);
        public GroupableTableHeader(TableColumnModel model) {
            super(model);
            setUI(new GroupableTableHeaderUI());
            setReorderingAllowed(false);
        public void addColumnGroup(ColumnGroup cg) {
            if(columnGroups.size() == 0) {
                columnGroups.addElement(cg);
                return;
            int size = columnGroups.size();
            for(int i = 0; i < size; i++) {
                if(cg.getLength() > ((ColumnGroup)columnGroups.elementAt(i)).getLength())
                    columnGroups.insertElementAt(cg, i);
                else {
                    if(i == size - 1)
                        columnGroups.addElement(cg);           
        public void fitHeight() {
            int[] counter = new int[getTable().getColumnCount()];
            for(int i = 0; i < getTable().getColumnCount(); i++) {
                int level = 0;
                for(int j = 0; j < columnGroups.size(); j++) {
                    if(i >= ((ColumnGroup)columnGroups.elementAt(j)).getStartIndex() && i <= ((ColumnGroup)columnGroups.elementAt(j)).getEndIndex())
                        level = level + getNewLineCount(((ColumnGroup)columnGroups.elementAt(j)).getText());
                counter[i] = level + getNewLineCount(table.getColumnModel().getColumn(i).getHeaderValue().toString());
            int maxCounter = counter[0];
            for(int i = 0; i < counter.length; i++) {
                if(counter[i] > maxCounter)
                    maxCounter = counter;
    setPreferredSize(new Dimension(100, (maxCounter) * 20));
    public Vector getColumnGroups() {
    return columnGroups;
    public int getNewLineCount(String str) {
    BufferedReader br = new BufferedReader(new StringReader(str));
    String line;
    Vector<String> v = new Vector<String>(1, 1);
    try {           
    while((line = br.readLine()) != null) {
    v.addElement(line);
    catch(IOException ex) {
    JOptionPane.showMessageDialog(null, ex.getMessage(), "Informasi", JOptionPane.INFORMATION_MESSAGE);
    System.exit(0);
    int i = 0;
    boolean b = false;
    for(i = 0; i < v.size(); i++) {
    for(int j = 0; j < v.elementAt(i).length(); j++) {
    if(v.elementAt(i).charAt(j) != ' ') {
    b = true;
    break;
    if(b)
    break;
    if(i == v.size())
    i = 0;
    return v.size() - i;
    public void updateUI(){
    setUI(new GroupableTableHeaderUI());
    class GroupableTableHeaderUI extends BasicTableHeaderUI {     
    public void paint(Graphics g, JComponent c) {
    TableCellRenderer renderer = new MultiLineHeaderRendererEx();
    Component[] cmp = new Component[header.getColumnModel().getColumnCount()];
    Vector cg = ((GroupableTableHeader)header).getColumnGroups();
    Component[] cmpGroup = new Component[cg.size()];
    TableColumnModel tcm = header.getTable().getColumnModel();
    for(int i = 0; i < cmpGroup.length; i++) {
    cmpGroup[i] = renderer.getTableCellRendererComponent(header.getTable(), ((ColumnGroup)cg.elementAt(i)).getText(), false, false, -1, i);
    rendererPane.add(cmpGroup[i]);
    int x = 0;
    int y = 0;
    int height = 20 * ((GroupableTableHeader)header).getNewLineCount(((ColumnGroup)cg.elementAt(i)).getText());
    for(int j = 0; j < ((ColumnGroup)cg.elementAt(i)).getStartIndex(); j++)
    x += tcm.getColumn(j).getWidth();
    for(int j = 0; j < cmpGroup.length; j++) {
    if(i == j)
    continue;
    if(((ColumnGroup)cg.elementAt(i)).getStartIndex() >= ((ColumnGroup)cg.elementAt(j)).getStartIndex() && ((ColumnGroup)cg.elementAt(i)).getEndIndex() <= ((ColumnGroup)cg.elementAt(j)).getEndIndex())
    y = ((ColumnGroup)cg.elementAt(j)).getY() + ((ColumnGroup)cg.elementAt(j)).getHeight();
    ((ColumnGroup)cg.elementAt(i)).setY(y);
    ((ColumnGroup)cg.elementAt(i)).setHeight(height);
    int width = 0;
    for(int j = ((ColumnGroup)cg.elementAt(i)).getStartIndex(); j <= ((ColumnGroup)cg.elementAt(i)).getEndIndex(); j++)
    width += tcm.getColumn(j).getWidth();
    rendererPane.add(cmpGroup[i]);
    rendererPane.paintComponent(g, cmpGroup[i], header, x, y, width, height, true);
    for(int i = 0; i < cmp.length; i++) {
    cmp[i] = renderer.getTableCellRendererComponent(header.getTable(), header.getColumnModel().getColumn(i).getHeaderValue(), false, false, -1, i);
    rendererPane.add(cmp[i]);
    int x = 0;
    int y = 0;
    for(int j = 0; j < i; j++)
    x += tcm.getColumn(j).getWidth();
    for(int j = 0; j < cmpGroup.length; j++) {
    if(i >= ((ColumnGroup)cg.elementAt(j)).getStartIndex() && i <= ((ColumnGroup)cg.elementAt(j)).getEndIndex())
    y = ((ColumnGroup)cg.elementAt(j)).getY() + ((ColumnGroup)cg.elementAt(j)).getHeight();
    rendererPane.add(cmp[i]);
    rendererPane.paintComponent(g, cmp[i], header, x, y, tcm.getColumn(i).getWidth(), (header.getPreferredSize().height - y), true);
    class MultiLineHeaderRendererEx extends JList implements TableCellRenderer {
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
    if(((GroupableTableHeader)table.getTableHeader()).getNewLineCount(value.toString()) == 1) {
    JLabel header = new JLabel();
    header.setForeground(table.getTableHeader().getForeground());
    header.setBackground(table.getTableHeader().getBackground());
    header.setFont(table.getTableHeader().getFont());
    header.setHorizontalAlignment(JLabel.CENTER);
    header.setText(value.toString());
    header.setBorder(UIManager.getBorder("TableHeader.cellBorder"));
    return header;
    else {
    setOpaque(true);
    setForeground(UIManager.getColor("TableHeader.foreground"));
    setBackground(UIManager.getColor("TableHeader.background"));
    setBorder(UIManager.getBorder("TableHeader.cellBorder"));
    setFont(UIManager.getFont("TableHeader.font"));
    ListCellRenderer renderer = getCellRenderer();
    ((JLabel)renderer).setHorizontalAlignment(SwingConstants.CENTER);
    setCellRenderer(renderer);
    String str = value.toString();
    BufferedReader br = new BufferedReader(new StringReader(str));
    String line;
    Vector<String> v = new Vector<String>(1, 1);
    try {           
    while((line = br.readLine()) != null) {
    v.addElement(line);
    catch(IOException ex) {
    JOptionPane.showMessageDialog(null, ex.getMessage(), "Informasi", JOptionPane.INFORMATION_MESSAGE);
    System.exit(0);
    setListData(v);
    return this;

    OMG ! the code i posted before is incomplete
    sorry...
    here's the complete one, pls help :
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.util.*;
    import javax.swing.border.*;
    import javax.swing.plaf.basic.*;
    public class GroupableHeaderExample extends JFrame {
        GroupableHeaderExample() {
            super("Groupable Header Example");
            JScrollPane sp = new JScrollPane();
            Object[][] data = {{"b1k1", "b1k2", "b1k3", "b1k4", "b1k5"}, {"b2k1", "b2k2", "b2k3", "b2k4", "b2k5"}};
            JTable table = new JTable(new DefaultTableModel(data, new Object[]{"Kol1", "Kol2\nmmm", "Kol3", "kol4\nmmm\nnnn", "Kol5\nmmm"})) {
                protected JTableHeader createDefaultTableHeader() {
                    return new GroupableTableHeader(columnModel);
            table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            ColumnGroup cg = new ColumnGroup("CG", 0, 4);
            ColumnGroup cg2 = new ColumnGroup("CG2\nmmm", 1, 4);
            ColumnGroup cg3 = new ColumnGroup("CG3", 1, 2);
            ColumnGroup cg4 = new ColumnGroup("CG4", 3, 4);
            GroupableTableHeader header = (GroupableTableHeader)table.getTableHeader();
            header.addColumnGroup(cg4);
            header.addColumnGroup(cg2);
            header.addColumnGroup(cg3);
            header.addColumnGroup(cg);
            header.fitHeight();
            sp.setViewportView(table);
            getContentPane().add(sp);
            setSize(400, 300);  
        public static void main(String[] args) {
            GroupableHeaderExample frame = new GroupableHeaderExample();
            frame.addWindowListener( new WindowAdapter() {
                public void windowClosing( WindowEvent e ) {
                    System.exit(0);
            frame.setVisible(true);
    class GroupableTableHeader extends JTableHeader {
        private Vector<ColumnGroup> columnGroups = new Vector<ColumnGroup>(1, 1);
        public GroupableTableHeader(TableColumnModel model) {
            super(model);
            setUI(new GroupableTableHeaderUI());
            setReorderingAllowed(false);
        public void addColumnGroup(ColumnGroup cg) {
            if(columnGroups.size() == 0) {
                columnGroups.addElement(cg);
                return;
            int size = columnGroups.size();
            for(int i = 0; i < size; i++) {
                if(cg.getLength() > ((ColumnGroup)columnGroups.elementAt(i)).getLength()) {
                    columnGroups.insertElementAt(cg, i);
                    break;
                else {
                    if(i == size - 1)
                        columnGroups.addElement(cg);           
        public void fitHeight() {
            int[] counter = new int[getTable().getColumnCount()];
            for(int i = 0; i < getTable().getColumnCount(); i++) {
                int level = 0;
                for(int j = 0; j < columnGroups.size(); j++) {
                    if(i >= ((ColumnGroup)columnGroups.elementAt(j)).getStartIndex() && i <= ((ColumnGroup)columnGroups.elementAt(j)).getEndIndex())
                        level = level + getNewLineCount(((ColumnGroup)columnGroups.elementAt(j)).getText());
                counter[i] = level + getNewLineCount(table.getColumnModel().getColumn(i).getHeaderValue().toString());
            int maxCounter = counter[0];
            for(int i = 0; i < counter.length; i++) {
                if(counter[i] > maxCounter)
                    maxCounter = counter;
    setPreferredSize(new Dimension(100, (maxCounter) * 20));
    public Vector getColumnGroups() {
    return columnGroups;
    public int getNewLineCount(String str) {
    BufferedReader br = new BufferedReader(new StringReader(str));
    String line;
    Vector<String> v = new Vector<String>(1, 1);
    try {           
    while((line = br.readLine()) != null) {
    v.addElement(line);
    catch(IOException ex) {
    JOptionPane.showMessageDialog(null, ex.getMessage(), "Informasi", JOptionPane.INFORMATION_MESSAGE);
    System.exit(0);
    int i = 0;
    boolean b = false;
    for(i = 0; i < v.size(); i++) {
    for(int j = 0; j < v.elementAt(i).length(); j++) {
    if(v.elementAt(i).charAt(j) != ' ') {
    b = true;
    break;
    if(b)
    break;
    if(i == v.size())
    i = 0;
    return v.size() - i;
    public void updateUI(){
    setUI(new GroupableTableHeaderUI());
    class GroupableTableHeaderUI extends BasicTableHeaderUI {     
    public void paint(Graphics g, JComponent c) {
    TableCellRenderer renderer = new MultiLineHeaderRendererEx();
    Component[] cmp = new Component[header.getColumnModel().getColumnCount()];
    Vector cg = ((GroupableTableHeader)header).getColumnGroups();
    Component[] cmpGroup = new Component[cg.size()];
    TableColumnModel tcm = header.getTable().getColumnModel();
    for(int i = 0; i < cmpGroup.length; i++) {
    cmpGroup[i] = renderer.getTableCellRendererComponent(header.getTable(), ((ColumnGroup)cg.elementAt(i)).getText(), false, false, -1, i);
    int x = 0;
    int y = 0;
    int height = 20 * ((GroupableTableHeader)header).getNewLineCount(((ColumnGroup)cg.elementAt(i)).getText());
    for(int j = 0; j < ((ColumnGroup)cg.elementAt(i)).getStartIndex(); j++)
    x += tcm.getColumn(j).getWidth();
    for(int j = 0; j < cmpGroup.length; j++) {
    if(i == j)
    continue;
    if(((ColumnGroup)cg.elementAt(i)).getStartIndex() >= ((ColumnGroup)cg.elementAt(j)).getStartIndex() && ((ColumnGroup)cg.elementAt(i)).getEndIndex() <= ((ColumnGroup)cg.elementAt(j)).getEndIndex())
    y = ((ColumnGroup)cg.elementAt(j)).getY() + ((ColumnGroup)cg.elementAt(j)).getHeight();
    ((ColumnGroup)cg.elementAt(i)).setY(y);
    ((ColumnGroup)cg.elementAt(i)).setHeight(height);
    int width = 0;
    for(int j = ((ColumnGroup)cg.elementAt(i)).getStartIndex(); j <= ((ColumnGroup)cg.elementAt(i)).getEndIndex(); j++)
    width += tcm.getColumn(j).getWidth();
    rendererPane.add(cmpGroup[i]);
    rendererPane.paintComponent(g, cmpGroup[i], header, x, y, width, height, true);
    for(int i = 0; i < cmp.length; i++) {
    cmp[i] = renderer.getTableCellRendererComponent(header.getTable(), header.getColumnModel().getColumn(i).getHeaderValue(), false, false, -1, i);
    int x = 0;
    int y = 0;
    for(int j = 0; j < i; j++)
    x += tcm.getColumn(j).getWidth();
    for(int j = 0; j < cmpGroup.length; j++) {
    if(i >= ((ColumnGroup)cg.elementAt(j)).getStartIndex() && i <= ((ColumnGroup)cg.elementAt(j)).getEndIndex())
    y = ((ColumnGroup)cg.elementAt(j)).getY() + ((ColumnGroup)cg.elementAt(j)).getHeight();
    rendererPane.add(cmp[i]);
    rendererPane.paintComponent(g, cmp[i], header, x, y, tcm.getColumn(i).getWidth(), (header.getPreferredSize().height - y), true);
    class MultiLineHeaderRendererEx extends JList implements TableCellRenderer {
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
    if(((GroupableTableHeader)table.getTableHeader()).getNewLineCount(value.toString()) == 1) {
    JLabel header = new JLabel();
    header.setForeground(table.getTableHeader().getForeground());
    header.setBackground(table.getTableHeader().getBackground());
    header.setFont(table.getTableHeader().getFont());
    header.setHorizontalAlignment(JLabel.CENTER);
    header.setText(value.toString());
    header.setBorder(UIManager.getBorder("TableHeader.cellBorder"));
    return header;
    else {
    setOpaque(true);
    setForeground(UIManager.getColor("TableHeader.foreground"));
    setBackground(UIManager.getColor("TableHeader.background"));
    setBorder(UIManager.getBorder("TableHeader.cellBorder"));
    setFont(UIManager.getFont("TableHeader.font"));
    ListCellRenderer renderer = getCellRenderer();
    ((JLabel)renderer).setHorizontalAlignment(SwingConstants.CENTER);
    setCellRenderer(renderer);
    String str = value.toString();
    BufferedReader br = new BufferedReader(new StringReader(str));
    String line;
    Vector<String> v = new Vector<String>(1, 1);
    try {           
    while((line = br.readLine()) != null) {
    v.addElement(line);
    catch(IOException ex) {
    JOptionPane.showMessageDialog(null, ex.getMessage(), "Informasi", JOptionPane.INFORMATION_MESSAGE);
    System.exit(0);
    setListData(v);
    return this;
    class ColumnGroup {
    private String text;
    private int startIndex, endIndex, y, height;
    public ColumnGroup(String text, int startIndex, int endIndex) {
    this.text = text;
    this.startIndex = startIndex;
    this.endIndex = endIndex;
    public int getEndIndex() {
    return endIndex;
    public int getHeight() {
    return height;
    public int getLength() {
    return endIndex - startIndex;
    public int getStartIndex() {
    return startIndex;
    public String getText() {
    return text;
    public int getY() {
    return y;
    public void setHeight(int height) {
    this.height = height;
    public void setY(int y) {
    this.y = y;

  • JMenu and Paint Problem

    Hello,
    I have been teaching my self Java and I have become quite proficient with it, however, I have a problem that I can not fix, or get around.
    I have a JMenuBar in a JFrame with some JMenu�s containing JMenuItems. I also have a JPanel that I draw inside (I Know that is probably not the wisest way to draw things, but it was the way I first learned to draw and now my program is too big and it is not worth while to change). Any ways, I draw some graphics inside of this JPanel.
    The menu items change the drawings; this is done by repainting the JPanel Graphic. However, when I click one of the menu items, the JPanel paints but there is a residual of the JMenu in the background that will not disappear.
    The menu is closed and if I open and then close the menu the residual goes away.
    => I would like to know how to prevent the residual from appearing?
    The problem also occurs when I use the popup menus outside of the JmenuBar.
    What I think is wrong.
    I think my problem is with the repaint. I don�t think the JFrame is repainting. I think I am simply repainting all the components in the JFrame but not the JFrame itself and thus the residual is not cleared from the JFrame. I don�t know how to fix this but I believe that is the problem because when I minimize the JFrame then Maximize it the JFrame will not paint, and I can see right through the JFrame, but the components paint fine.
    Sorry for the long question, but I don�t know what would be helpful.
    Any advice would be appreciated,
    Thank you
    Seraj

    // This is the code that listens for the menu item
    private void RBmmActionPerformed(java.awt.event.ActionEvent evt) {                                    
            calc.setIN(false);
            updateData();                    // updates some data
            paint2();                           // my special draw fuction shown below
        public void paint2()                          // this the special paint that draws on the JPanel
            Graphics page = jPanel1.getGraphics();
            if(start_end)
                myPic.draw(page);
            else
                page.setColor(Color.WHITE);
                page.fillRect((int)(OFFSET.getX()), (int)(OFFSET.getY()), (int)(R_BOUND-OFFSET.getX()), (int)(L_BOUND-OFFSET.getY()));
            repaint();             
    public void paint(Graphics g)               // this is the regular paint methode
            MessageHandler();
            ATD_age.repaint();
            StanderdCal.repaint();
            ChildSRF.repaint();
            MessageArea.repaint();
        }I hope that is helpful

  • Multiple transparent JPanels paint problem (smearing strings)

    I created full screen JWindow application.
    I created three panels:
    MainPanel - non transparent
    PPIPanel - transparent
    GlassPanel - transparent.
    All three panel and JWindow has the same bounds. Then I added PPIPanel and GlassPanel to MainPanel and then I added MainPanel to JWindow.
    MainPanel.add(PPIPanel);
    MainPanel.add(GlassPanel);
    JWindow.getContentPane().add(MainPanel);
    Whole application displays Air Traffic Situation comming from RADAR. MainPanel is a black background with airways, PPIPanel displays aircrafts and GlassPanel is MouseEvent listener for ZOOM, CENTER and other mouse operations.
    The painting code is always placed in paint(Graphics g) metod of each component. All aircraft are painted on the transparent PPIPanel with small dot fillOval() and two BOLD strings g.drawString("Aircraft")descibing aircraft.
    paint(Graphics g) {
    g.setColor(Color.GREEN);
    g.setFont(bold font);
    iterate Collection of aicrafts {
    g.fillOval(x,y,4,4);
    g.drawString(x+3,y+3,"Aircraft xxx");
    g.drawString(x+3,y+18,"Flight level");
    The situation is changing every 4 seconds and every 4 seconds special Thread calls repaint() method on PPIPanel to referesh the situation.
    The main problem is garbage remaining after refresh. Some aircrafts has smeared label after repaint ( probably because multiple transparent panels).
    What are your proposals to solve the problem. I'm just a java begginer so I need clear explenation (i.e. code example).

    just to make it clear
    paint(Graphics g) {
    super.paint(g)
    g.setColor(Color.GREEN);
    g.setFont(bold font);
    iterate Collection of aicrafts {
    g.fillOval(x,y,4,4);
    g.drawString(x+3,y+3,"Aircraft xxx");
    g.drawString(x+3,y+18,"Flight level");
    or
    paintComponent(Graphics g) {
    g.setColor(Color.GREEN);
    g.setFont(bold font);
    iterate Collection of aicrafts {
    g.fillOval(x,y,4,4);
    g.drawString(x+3,y+3,"Aircraft xxx");
    g.drawString(x+3,y+18,"Flight level");
    should work..
    Cheers
    Mike

Maybe you are looking for

  • Link to topic in CHM file

    Hello, all The problem: I need to link to a specific topic within a CHM file, via URL, rather than directly to the CHM file itself and I am having no luck finding a means to do so. I have tried the suggested methods from the support/web but not come

  • Is there any way to restrict adding himself as a approver in scenarios?

    Is there any way to restrict adding himself as a approver in scenarios?

  • Dynamic Link Error - Please HELP!!!!

    I am getting this message "Could not connect to Adobe After Effects. Please verify that Adobe After Effects and Adobe Dynamic Link components are installed." I've not had any trouble with After Effects and the Media Encoder until this morning. I've c

  • Time to move on from WD TV Live Hub.

    I love my WD TV Live Hub or at least what it could be.  But a few things continually block the experience.-Slow Network Access.  100 Mbit is sooo slow when copying HD media files to the unit.  Average of 8MBps.-Reboots and Re-indexing sometimes when

  • Why doesn't my avatar show?

    I don't seem to be able to ask a question of anyone at Adobe because I have only the free product Reader, so I'll put this here and hope for the best. I uploaded a cute little avatar from my hard drive to decorate my profile like a sociable being, an