Paint()  problems

i was messing around and created a program that inside a JFrame there is a crosshair image that follows your mouse pointer and if you click the mouse, it leaves a red dot on that spot. The problem is that in order for the crosshair image not to create a trail of itself, i call repaint() from mouseMoved() to refill the entire background each time you move the mouse (fill rectangle of size of JFrame to background color in paint()). This works except it makes it so that when you click to leave a dot, those get erased as soon as you try to move the mouse. i thought about only refilling the small area where the crosshair last was before it moved instead of the entire JFrame but this could cause issues if you move the mouse over a spot that already has a red dot there (it will be erased). Cant think of a solution to this.

In wsing the code that drow the content on the screne should be placed in the paintComponent method and in your mouseMove just save the coordinates where you should drow the image in to a variable and call repaint.
The paintComponent should read the coordinates from the variables and do the drowing. To clean up of old drowing just call super.paintComponent from paint component before do any drowing

Similar Messages

  • 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);

  • 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!!

  • 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

  • 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 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.

  • 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`~

  • Report painter problem very urgent

    Hi to ALL,
    I have prepared two reports of cost centre through report painter. The format is proper is both the reports. The set is also correct and values in set(i.e cost centres) are also properly
    but when we execute the report one report is being executed properly while other shows zero values. only when i doubleclick on zero amt and go to plan line items then it shows me values for that particular row in report.
    Why is it so? what is solution to it? can it be possible that my tables are not correct. Ia m using CCSS table.
    Pls this is very urgent
    Thanks in advance
    Tanuja

    Hi
    Can you check one thing...after selecting the zero you are getting the line item...chekc the total of that items...if it is coming zero..then no problem.
    If not you can check in the no.format of that report. If you select the lacs format and your amount is below ten thousand...you will get the zero value only
    VVR

  • Report Painter problem with empty selection variant

    Hello,
    I use the cost center selection variant for the column definition in Report Painter as characteristic value. This selection variant get only the cost centers which are valid from 1.1.2003 to 31.12.2004. The column of the report created by Report Painter which uses this selection variant display value without taking into account limitations follow from this selection variant. I expect value zero for year fiscal year 2007 in this column, because the cost centers are invalid in 2007 year but the report displays different value. The problem appeared after upgrade from 4.6C to ECC 6.0.
    Best Regards
    ZD

    My problem with Report Painter occurred when I was creating my own report based on 1VK library.
    In my example I used in the column definition characteristic Cost
    Center, which is determined by selection variant, and Basic Key Figure
    equal SWKG-Costs. For system date (18.07.2007) there are no valid
    master data for the characteristic Cost Center but when I execute
    report for fiscal year 2007 the column display no-zero value without
    taking into account value of Characteristic Cost Center. I expected
    zero value in this column because there are no postings for Cost
    Centers (no valid cost centers were selected) in financial year 2007.
    Could you help me with this problem ?

  • Screen painter problem

    Hi everyone,
    In screen painter, I would call the current screen before output module. But it tells 'the statement is not accessible' when I active the programme. What's the problem? Thanks!!

    call under start of selection event.
    start-of-selection.
    call screen 100.

  • 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

  • Painting problems with cwgraph in multiple document interface (mdi).

    Has anyone else seen weird behavior when using a cwgraph on an MDI child form in .NET. Whenever I open a new child window (containing a cwgraph) it gets painted once in the correct location and again offest about 50 pixels away and the old original location doesn't get invalided properly.
    The only workaround I've found is to contain the cwgraph in a panel or groupbox and the problem seems to go away entirely.

    Do you only see this problem with the graph, or do you see it with other Measurement Studio controls as well? Do you have any other ActiveX control on an MDI child and if so, what is the behavior of those controls? Could you please post a small test project that reproduces the problem? Thanks.
    - Elton

  • Oil Painting problem

    Hello
    Thanks for the genius CS6, but I get this problem whenever I use Oil Painting feature, the whole pic gets darker

    Hm, I wonder if it could be a color-management issue...  Have you tried changing your Advanced GPU settings to Basic (then closing and restarting Photoshop)?
    It might be that you could benefit from updating your operating system if it's not already right up to date.
    -Noel

Maybe you are looking for

  • Getting Error 500--Internal Server Error when trying to access worklistapp

    java.lang.NoClassDefFoundError: org/apache/myfaces/trinidadinternal/convert/ColorConverter      at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)      at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAc

  • How to get information about BBP_PDATT (attached document)

    Hello I'm writing a function module, and i want to get the attached document of a purchase order. I know the function module BBP_PD_PO_GETDETAIL gets this information but it is too long for me and i just need attached document. I found the Function m

  • Ix4-300d can I run Rsync copy jobs accoss VPN

    I want to set up a point to point VPN to an offsite location with an ix4-300d at each location then run copy jobs between the devices.  By necessity these will be different subnets (172.16.16.x and 172.16.20.x)  The user guide seems to indicate that

  • Please help to load image in the database

    Hi to all. .... I need to save image file in the database thru forms ... I have some image file in the application server and I need to load it in the database in a Blob col.. Any help ... ?? Thank's in advance

  • Nokia N73 Camera Reset

    When I click a photo sometimes the camera resets.. and the camera reloads.. sometimes it happens after a photo have been clicked.. It bugs me a lot, I generally click photo's of black and white mode but when I clikc the photo camera resets.. and it c