JTabbedPane cause second paint

I have a problem with JTabbedPane that has me stumped. When a TabbedPane is displayed, it causes it's parent component to repaint itself. This appears to happen because the TabbedPane wants to paint the contents of it's visible tab. If I don't add any tabs to the TabbedPane, the problem goes away. I have given a simple example to demonstrate.import java.awt.*;
import javax.swing.*;
class TabTest
  public static void main(String[] args)
    JFrame frame = new JFrame("TabTest");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JTabbedPane tabbedPane = new JTabbedPane();
    tabbedPane.addTab("First Tab", new JPanel());
    tabbedPane.addTab("Second Tab", new JPanel());
    JPanel contentPane = new JPanel(new BorderLayout()){
      protected void paintComponent(Graphics g)
        try
          // sleep so we can watch the painting issue occur
          System.out.println("contentPane.paintComponent()");
          Thread.currentThread().sleep(1000);
        catch(Exception e){}
        super.paintComponent(g);
    contentPane.add(tabbedPane, BorderLayout.CENTER);
    frame.setContentPane(contentPane);
    frame.setBounds(300,300,300,300);
    frame.setVisible(true);
}My only solution so far is to use a CardLayout and simulate a TabbedPane like interface. When the tabs have some components on them, you can see a flicker, which is my main problem with this.

v1.4.2
Yes that is what I mean. Only a TabbedPane requires a second paint of the frame. When the tabbedPane has some components on it, requiring more painting, you will notice a flicker when displaying the window. The flicker is gone if your remove all tabs from the tabbedPane. If you get rid of the tabbedPane and put a regular JPanel there, only one paint is performed. Or if you put a JPanel with a cardlayout only one paint is performed.
In my application, it is actaully a modal JDialog with a borderlayout and the tabbedPane is put in the WEST region. If I do the little sleep(), I can see the borderlayouts CENTER, BOTTOM and NORTH regions painted and then the screen is wipped and finally get the WEST region...the tabbedPane. This requires a second paintComponent() call and several invalidates. This causes an annoying flicker which is only removed by removing all tabs from the tabbedPane or by using a CardLayout instead.

Similar Messages

  • Painting on JTabbedPanes

    I have code which reads rectangle tags from an svg file and displays them on a canvas in a tabbed pane, when I first click on the tabbed pane the image appears but when I click on another tab then go back to this tab the rectangle is not there. It does not appear to be repainting. How do I set my tabbed pane up so that when a user clicks on a tab the canvas is repainted?

    import java.awt.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class Painting
        JTabbedPane tabbedPane;
        public Painting()
            double[][] coords = {
                { 1.0/4, 1.0/4, 1.0/2, 2.0/3 }, { 1.0/3, 1.0/4, 1.0/3, 3.0/8 }
            Color[] colors = { Color.blue, Color.red };
            tabbedPane = new JTabbedPane();
            tabbedPane.addTab("blue", getPanel(coords[0], colors[0]));
            tabbedPane.addTab("red",  getPanel(coords[1], colors[1]));
        private JPanel getPanel(final double[] d, final Color color)
            JPanel panel = new JPanel()
                 * swing always calls this method when your component
                 * needs to be rendered so whatever you want to paint
                 * will always show up if you put the code in here
                protected void paintComponent(Graphics g)
                    super.paintComponent(g);
                    Graphics2D g2 = (Graphics2D)g;
                    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                        RenderingHints.VALUE_ANTIALIAS_ON);
                    int w = getWidth();
                    int h = getHeight();
                    double x      = d[0] * w;
                    double y      = d[1] * h;
                    double width  = d[2] * w;
                    double height = d[3] * h;
                    g2.setPaint(color);
                    g2.draw(new Rectangle2D.Double(x, y, width, height));
            return panel;
        public static void main(String[] args)
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new Painting().tabbedPane);
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    }

  • More than one paint method?

    Hi
    Im wondering if it is possible to have more than one paint method. It should look something like this.
    public class MyApplet extends JApplet {
    public void paint(Graphics g) { // the normal paint method
    public void SecondPaint(Graphics gr) { // should i name the Graphics
    // to the same as in the normal paint method ( Graphics g) ?
    }And if its possible how would i repaint the other method?
    This is for the normal
    repaint(); and how would i do for the second paint method?
    please write an example program with two paint methods and just write below how to repaint.
    Thanks you som much if you reply

    (sorry to hijack this thread...) Yes, it'swindows,
    but right now my problem isn't even that. It'sjust
    catching and correcting basic c-coding errors.
    Witness my embarrassment in the JNI forum:
    http://forum.java.sun.com/thread.jspa?threadID=5213196
    &tstart=15
    Now if only I lived in "middle-of-no-where"Virginia!
    Nice! ;-)I saw your note about "middle-of-nowhere" Virginia a little too late. And you don't need to live here; my Solaris machine is up and running 24/7 and is open for SSH and XClient. (Also open for telnet, which comes built into windows, I believe.) If you'd like to brush up on Solaris C, C++ and Java development, just let me know. You're more than welcome to use the machine. I have tons of space on the drive and a dedicated connection just to that machine. There is an application for windows called CygwinX which is an XClient for Solaris. You can use that to remotely log into the Solaris desktop. There are about fifteen other people that I let use the machine for various reasons. I host myriad open source projects for development that you're more than welcome to mess around with. Tools available to you would be NetBeans 5.5, Sun Studio (with the Sun C/C++/Fortran compiler - which is beautiful by the way); and the whole suite of GNU compilers. I have the CDE and the JavaDesktop built in. I also have tons of Motif tutorials and demonstrations if you're interested in those. Heads up, though ... XServer tends to run pretty slowly when I have more than about four users logged onto a desktop at once. But like I said, if you (or just about anyone else for that matter) are interested, let me know and I'd be more than glad to set you up.

  • Endless call of paint()

    Hi,
    I have a calendar component which consits of a JPanel. Inside the panel each day of month is drawn as a JPanel too. The day panels paint method I have overwritten to change the background color depending on the weekday and sometimes add an icon. The calendar panel works correctly, but when I step through the month anytime the paint method of the day panels are called endless. The CPU load grows to 99 %. That's the code of the overwritten paintComponent method of the day panel:
    protected void paintComponent(Graphics g)
            super.paintComponent(g);
            // filler panel to fit grid
            if (this.getName() != null && this.getName().equals(""))
                this.setBackground(Constants.FILL_PANEL_BACKGROUND_COLOR);
                return;
            Color colorBG = this.overviewParent.getStdBackgroundColor();
            if (this.weekDay == Calendar.SATURDAY)
                //this.setBackground(Constants.COLOR_SATURDAY);
                colorBG = Constants.COLOR_SATURDAY;
            else if (this.weekDay == Calendar.SUNDAY)
                colorBG = Constants.COLOR_SUNDAY;
            if (this.bDrawMouseOver)
                colorBG = Constants.MOUSE_OVER_BACKGROUND_COLOR;
            if (this.isSelected)
                colorBG = Constants.FOCUS_BACKGROUND_COLOR;
            this.setBackground(colorBG);
            if (this.labelAppl != null && this.labelInvit != null && this.domainObjects != null)
                Object curObj = null;
                Iterator it = this.domainObjects.iterator();
                while (it.hasNext())
                    curObj = it.next();
                    if (curObj instanceof ClassA)
                        if (this.labelAppl.getIcon() == null)
                            this.labelAppl.setIcon(this.overviewParent.getIconA());
                    else if (curObj instanceof ClassB)
                        if (this.labelInvit.getIcon() == null)
                            this.labelInvit.setIcon(this.overviewParent.getIconB());
        }When changing the month, I remove all day panels from the main panel and draw them new. When for instance the background color should change (on mouse over) I update the specific day panel with
    panel.invalidate();
    panel.repaint();
    Where is my fault ? Maybe setBackground() call. The endless loop occurs not immediately. After stepping through some month it appears. Any ideas ?

    Well, the basic code in your paintComponent(...) method is wrong. You should not be setting properties of a component in the paintComponent() method.
    The main problem would be:
    this.setBackground(colorBG);This is telling the component to change its background color. The RepaintManager is notified of the property change and reschedules another paint() on the component.
    You should also not be setting the icon based on the class. When you create the class you should set the icon. Or when you add the component to the parent container you should set the icon. Although I don't think this will cause a painting problem I don't believe the code belongs in this method.
    Generally, if you customize the paintComponent(...) method it should be to do custom paint by invoking methods on the Graphics object.

  • Paint interpolation

    hi
    posted a similar question before but still having probs.
    when painting with interpolation is there any way to make a stroke last a certain nummber of frames without unecessary animation?
    say I am painting out some disfiguration - a small area of troublesome greenscreen from a static shot for example.
    do i need to repaint the same stroke every frame for the duration - have tried but this seems to cause bubbling
    painting out the section on frames 1 and 10 then interpolating between also causes bubbling as the stroke is animated.
    if i use interpolate is there a way where i can copy the paint stroke from say frame 1 then paste it exactly to frame 10 so it appears to be a constant stroke to disguise the stroke animation.
    Any help much appreciated

    -Paint your stroke in Persist mode.
    -In Edit subtab, use Convert Stroke
    -Set to Frame mode, and enter 1,10 as your frames.
    -ed
    hi
    painting out the section on frames 1 and 10 then
    interpolating between also causes bubbling as the
    stroke is animated.
    if i use interpolate is there a way where i can copy
    the paint stroke from say frame 1 then paste it
    exactly to frame 10 so it appears to be a constant
    stroke to disguise the stroke animation.
    Any help much appreciated

  • Repaint() method 's not work but paint(getGraphics()) does, why?

    I've just read the following code ( in the Core Java 2 advance features vol 2 book):
      import java.awt.*;
      import java.awt.event.*;
       import java.awt.geom.*;
       import java.util.*;
       import javax.swing.*;
          Shows an animated bouncing ball.
      public class Bounce
         public static void main(String[] args)
            JFrame frame = new BounceFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.show();
         The frame with canvas and buttons.
      class BounceFrame extends JFrame
            Constructs the frame with the canvas for showing the
            bouncing ball and Start and Close buttons
         public BounceFrame()
            setSize(WIDTH, HEIGHT);
            setTitle("Bounce");
            Container contentPane = getContentPane();
            canvas = new BallCanvas();
            contentPane.add(canvas, BorderLayout.CENTER);
            JPanel buttonPanel = new JPanel();
            addButton(buttonPanel, "Start",
               new ActionListener()
                     public void actionPerformed(ActionEvent evt)
                        addBall();
            addButton(buttonPanel, "Close",
               new ActionListener()
                     public void actionPerformed(ActionEvent evt)
                       System.exit(0);
            contentPane.add(buttonPanel, BorderLayout.SOUTH);
            Adds a button to a container.
            @param c the container
            @param title the button title
            @param listener the action listener for the button
         public void addButton(Container c, String title,
            ActionListener listener)
            JButton button = new JButton(title);
            c.add(button);
            button.addActionListener(listener);
            Adds a bouncing ball to the canvas and makes
            it bounce 1,000 times.
         public void addBall()
            try
               Ball b = new Ball(canvas);
               canvas.add(b);
               for (int i = 1; i <= 1000; i++)
                  b.move();
                  Thread.sleep(5);
            catch (InterruptedException exception)
         private BallCanvas canvas;
         public static final int WIDTH = 450;
         public static final int HEIGHT = 350;
        The canvas that draws the balls.
    class BallCanvas extends JPanel
            Add a ball to the canvas.
            @param b the ball to add
       public void add(Ball b)
           balls.add(b);
        public void update(Graphics g) {
             super.update(g);
             System.out.println("Test");
        public void paintComponent(Graphics g)
          super.paintComponent(g);
          Graphics2D g2 = (Graphics2D)g;
          for (int i = 0; i < balls.size(); i++)
             Ball b = (Ball)balls.get(i);
             b.draw(g2);
            // System.out.println("Test");
        private ArrayList balls = new ArrayList();
        A ball that moves and bounces off the edges of a
       component
    class Ball
            Constructs a ball in the upper left corner
            @c the component in which the ball bounces
        public Ball(Component c) { canvas = c; }
           Draws the ball at its current position
           @param g2 the graphics context
        public void draw(Graphics2D g2)
           g2.fill(new Ellipse2D.Double(x, y, XSIZE, YSIZE));
          Moves the ball to the next position, reversing direction
          if it hits one of the edges
       public void move()
          x += dx;
          y += dy;
           if (x < 0)
              x = 0;
              dx = -dx;
         if (x + XSIZE >= canvas.getWidth())
             x = canvas.getWidth() - XSIZE;
              dx = -dx;
           if (y < 0)
             y = 0;
              dy = -dy;
           if (y + YSIZE >= canvas.getHeight())
              y = canvas.getHeight() - YSIZE;
              dy = -dy;
           //canvas.paint(canvas.getGraphics());//this would OK.
           canvas.repaint();//This not work, please tell me why?
        private Component canvas;
        private static final int XSIZE = 15;
       private static final int YSIZE = 15;
       private int x = 0;
       private int y = 0;
       private int dx = 2;
       private int dy = 2;
    }this program create a GUI containing a "add ball" button to creat a ball and make it bounce inside the window. ( this seems to be stupid example but it is just an example of why we should use Thread for the purpose ).
    Note: in the move() method, if i use canvas.repaint() then the ball is not redrawn after each movement. but if i use canvas.paint(canvas.getGraphics()) then everythings seem to be OK.
    Another question: Still the above programe, but If I create the ball and let it bounce in a separate thread, then canvas.repaint() in the move method work OK.
    Any one can tell me why? Thanks alot !!!

    I don't know why the one method works. Based on my Swing knowledge neither method should work. Did you notice that the JButton wasn't repainted until after the ball stopped bouncing. That is because of the following code:
    for (int i = 1; i <= 1000; i++)
        b.move();
        Thread.sleep(5);
    }This code is attempting to move the ball and then sleep for 5 milliseconds. The problem with this code is that you are telling the Event Thread to sleep. Normally painting events are added to the end of the Event Thread to allow for multiple painting requests to be combined into one for painting efficiency. When you tell the Thread to sleep then the GUI doesn't get a chance to repaint itself.
    More details about the EventThread can be found in the Swing tutorial:
    http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html
    This explains why the button isn't repainted, but it doesn't explain why the ball bounces. I don't know the answer to this for sure, but I do know that there is a method called paintImmediately(...) which causes the painting to be performed immediately without being added to the end of the Event Thread. This means the painting can be done before the Thread sleeps. Maybe the canvas.paint(....) is somehow invoking this method.
    When you click on the button this code is executed in the EvWell in Swing, all GUI painting is done on the Event Thread

  • Switching users causes screen display issues

    I've had a new MacBook Pro 2011 that came with Lion on it. It's been working well, I migrated my old user accounts from my previous MacBook with Snow Leopard on it.
    After having it a few weeks my son tried using the fast user switching and going into his account but the screen was exteremly glitchy. It basically show what looked like my users screen and would erase and paint with his correct screen as he dragged windows around. Eventually his screen would like correct then spontantously revert to showing my screen again.
    Fast user switching back to my account showed everything correctly. Logging us both out and logging him in alone works fine. Logging him in first and then switching to my user gives me the problem he experienced of seeing mostly his screen and having to drag screens around causing re-painting to show my proper screen.
    Screen refresh issue aside if we can work through messed up screens the computer appears to be working fine, apps launch properly and no sign of any memory or file corruption, everything "works" properly.
    I tried completely removing and re-creating his account but the problem remains.
    Couple of factors in case they are relevant.
    1) We upgraded the HDD to a SDD but it shows not signs of any issues
    2) We upgraded the memory beyond the normal limit of 8gb to 16gb using a Cruicial memory kit certified for the MacBook Pro.
    3) We have both the laptop screen 1680x1050 running and an attached thunderbolt display AND a usb DisplayLink adapter to a 3rd Dell 1600x1200 monitor.
    My intial thoughts were with the DisplayLink adapter. I made sure to get the latest drivers from the display link web site and did some searches but no one has described my problem.
    The screen issue seems to present itself mainly on the "main monitor" the 27" thunderbolt display but we have seen some screen corruption on the MacBook LCD. Oddly the DisplayLink always appears correct.
    Anyone have any ideas?
      System Version:          Mac OS X 10.7.3 (11D50b)
      Kernel Version:          Darwin 11.3.0
      Boot Volume:          Macintosh SSD
      Boot Mode:          Normal
      Secure Virtual Memory:          Enabled
      64-bit Kernel and Extensions:          Yes
      Time since boot:          21:31

    As a followup. Experimenting seems to suggest that removing the driver for DisplayLink cures the issue. Going to test more with reinstalling the driver and just unplugging the USB cable before switching.
    Was also seeing (before uninstall) issues with getting a Beach Ball freeze during logout of the 2nd user.
    I want to be certain of if it's the DisplayLink driver but once I am certain I'll take my gripe to their support forum.

  • HELP! Run-time Error with this code.

    I'm having problem with the code below. But if I were to remove the writer class and instances of it (writeman), then there are no problems. Can some1 pls tell me why the writer class is giving problems. Btw, no compilation errors, only errors at run-time..........
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.MouseListener;
    import java.awt.event.*;
    public class HelloWorld extends Applet
    public static String MyString = new String("Hello");
    Graphics f;
    public void init()
    Changer Changer1 = new Changer();
    writer writeman = new writer();
    setBackground(Color.red);
    setForeground(Color.green);
    addMouseListener(Changer1);
    writeman.paintit(f);
    public void paint(Graphics g)
    g.drawString(MyString,10 ,10);
    public class Changer implements MouseListener
    public void mouseEntered(MouseEvent e)
    setBackground(Color.blue);
    MyString = "HI";
    paint(f);
    repaint();
    public void mouseExited(MouseEvent e)
    setBackground(Color.red);
    repaint();
    public void mousePressed(MouseEvent e){};
    public void mouseReleased(MouseEvent e){};
    public void mouseClicked(MouseEvent e){};
    public class writer
    public void paintit(Graphics brush)
    brush.drawString("can u see me", 20, 20);

    I assume the exception you are getting is a NullPointerException...
    When you applet is loaded, it is initialised with a call to init... the following will then occur...
    HelloWorld.init()
    writeman.paintit(f)
    // f has not been initialised, so is null
    brush.drawString("can u see me", 20, 20)
    // brush == f == null, accessing a null object causes a NullPointerException!
    The simplest way to rectify this is to not maintain your own reference to the Graphics object. Move the writer.paintit(f) method to the HelloWorld.paint(g) method, and pass in the given Graphics object. Also, change the paint(f) call in Changer to repaint(), which will cause the paint method to be called with a valid Graphics object - which will then be passed correctly to writer.
    Hope this helps,
    -Troy

  • JOptionPane handling problem

    Hi all,
    I'm imlementing a GUI using JPanel and paintComponent(Graphics g).
    When i have to display some data on the screen i use JOptionPane.showMessageDialog(...) and the data are displayed.
    The problem is that, when i close the Message Dialog, it doesn't completely disappear from the screen and so my screen is being messed up. I think it has to do with the graphic environment but i can't figure out what exactly is the problem.
    Thanks,
    John.

    I'm imlementing a GUI using JPanel and
    paintComponent(Graphics g).
    When i have to display some data on the screen i use
    JOptionPane.showMessageDialog(...) and the data are
    displayed.hello John,
    are you invoking JPanel's paintComponent ?public void paintComponent(Graphics g)
          super.paintComponent(g);
          //your painting stuff...
    }Not calling JPanel's paintComponent can cause background-painting problems.
    regards,
    Tim

  • Mythfrontend (0.22): No LIRC and freezes on exit. [SOLVED - partially]

    Hello again, more problems with mythtv...
    First of all, mythfrontend doesn't respond to lirc input. It does however work in mythwelcome (and irw), but the stdout from mythfrontend includes:
    LIRC: Successfully initialized '/dev/lircd' using '/home/mythtv/.mythtv/lircrc' config
    The other problem is that mythfrontend always freezes when exiting. There is no printouts or anything, it just stops responding (when it should terminate). I believe this might be connected to some settings change, since I don't remember having this problem when first moving to 0.22. But I don't see what could be the cause (opengl painter? change of theme?). But it shouldn't happen, right?
    If anyone happens to have any idea of the reason for the problems, solutions, or similar problem, please post. Thanks
    Last edited by 1311219 (2009-12-23 13:04:45)

    After a much experimenting (including resetting the database), I've found the cause for the problem: "media monitoring" in mythfrontend
    I've never been able to get this to work, so I've disabled it... When enabled (and causing problems) it seems to complain about pmount not be able to lock directory and similar. Oh well, as long as recording/playing of recordings works, then I'm happy.
    I hope this helps other people in the same situation.

  • Scripting for PDF

    Hi,
    I am trying to create a basic JS script for an Acrobat X Pro created PDF, to have it on opening check the launching URL, and if not a specific, hard-coded URL in the script, to navigate to a URL redirect page (or alternatively, to close the PDF).
    So, far, haven't been able to get it to work. I think that I am following the guidelines, but I must be doing something wrong. 
    I used the JS editor to add a simple, document level script:
    if (doc.Url != "xyz.com")
    doc.closeDoc();
    //OR, the one I used in the test PDF (see link below)
    if (doc.Url != "xyz.com")
    this.getURL(www.xyz/redirect.html);
    Saved and re-opened the PDF, and nothing happens...
    My test PDF with scripting in the JavaScript editor is at:
    www.elearningprojects.com/abc.pdf
    Can't get this to work, so far.
    Any help appreciated.
    Regards,

    Hi,
    I'm new to scripting in Acrobat. Thank you for suggesting the debugger.
    It appears that getURL is not permitted by the security feature. I tried app.launchURL which works, but even if I follow it with closeDoc, the PDF stays open after the redirect.
    The only script that works is closeDoc. I'm using a condition if...to check if the URL != to a scripted URL. Even if the URL is correct (checks out), if I add an app.alert before closeDoc ("unauthorized to view the PDF"), the alert still displays (when it shouldn't).
    So far, a bit of a mess.
    It seems that a single script action in a conditional (for example, closeDoc), executes OK, but add a second action within the same conditional and it doesn't work as it should.
    I have been removing the function {} part, just adding the plain script: if... and  1 or 2 actions. I'm not sure how to set up an initial/opening event to trigger a function.
    I wonder if removing this function aspect causes second actions to fail to work properly?
    Any suggestions appreciated.
    Regards,

  • Strange Behavior between identical servers

    We have an interesting problem that is effecting the performance of an
    application on our production servers but is not happening on our test
    servers. All servers are the same, Win2k server sp3 running Weblogic
    5.1 sp9. Our clients were complaining of slow performance on the
    production servers, they were describing a situation where the page
    was "painting" across the screen rather than loading instantly as it
    does in test. We are using ssl and have an enterprise requirement
    that the "Do not save encrypted pages to disk" setting is checked
    (meaning we are not caching the pages) in IE (IE 6). Given that we
    immediately ruled out caching on the client as it is a non-issue.
    After running a tcptrace, we found a difference in the way the boxes
    were pushing the pages down to the client, in test, a single
    connection is established to the webserver and all of the components
    of the page (images, javascript files, etc...) are being pushed across
    that one connection. However in production, we found that when
    loading the same page a separate connection is being opened for every
    object pushed down, this is clearly what is causing the "painting"
    effect but the question is why???
    My first guess was HTTP1.0 vs HTTP1.1, but client is sending requests
    HTTP1.1 and in both test and production the server is responding with
    HTTP1.1, keep-alive settings are identical on both servers, in fact
    all configuration settings in configuration.properties are identical.
    Does anyone have any idea what might be causing this? We have
    verified that the primary configurable tcp/ip settings are identical
    on all boxes.
    Any suggestions would be greatly appreciated!

    I think you're reading way too much into my giggle.
    It was innocent smile at Dimitri's officiousness. Any reasonably well-read person knows that it doesn't matter what country you're in, if you just want to mention the name a product
    especially
    in a venue like these forumsthere are no regulations that say you need to mark it with an ® or a or a ©. It's universally understood that the applications we speak of here are owned by our esteemed hosts, and they sure don't give a rip about it.
    That's what I think.
    Oh, and I still think you need to take a remedial writing-for-comprehension class, as I have for a good 8 or 10 years now.

  • Draw a rectangle on an image in an applet

    Hello
    I have an applet that has 3 buttons. Each of them creates an image, which is displayed on the screen. Now, I want to draw a rectangle on these images. Since I already have a paint method for displaying the images correctly, I would need a second paint method for the rectangle. (I can't put everything in the same paint() method, because I have an horrible resukt)
    Does anyone have an idea of a method that would be able to replace a paint method?
    Any help would be appreciated
    Thanks
    Philippe

    Have you thought about using one of your button to get the action done? You could use the Graphics method to create your object rectangle.
    Don't know if it would work but seems like a good idea to try.

  • Beginner needs help with inserting images in applet.

    //  Name: Sachit Harish
    //  Name of Program: HorseRacing
    //  Date Started: May 15, 2003
    //  Date Finished: 2003
    //  Program Description:
    import java.awt.*;
    import java.applet.*;
    public class HorseRacing extends Applet
    //     Button startGameButton;
         InputField betAmountBox;
         Image redHorse; //<---------//
    //     Button[] drawings = new Button[4];      
    //    String[] labels =  {"Face", "Cheese", "Stick", "Mashed Potatoes"};
        //  Method Name: init()
        //  Parameters Passed: None
        //  Data Returned: None
        //  Method Purpose: Where we initialise the InputBoxes and colors.
        public void init()         
          //     startGameButton=new Button("Click to Start Game");
          //     add(startGameButton);
          /*  for(int i=0; i<drawings.length; i++)
                 drawings=new Button (labels[i]);     
         add(drawings[i]);
    inputBoxes();     
    setBackground(Color.gray); //background color
    setForeground(Color.black); //input field text color
    redHorse = getImage(getCodeBase(), "horse_red.GIF"); //<---------//
    // Method Name: paint()
    // Parameters Passed: Graphics variable screen
    // Data Returned: None
    // Method Purpose: Where the programs calls and collects all the methods.
    //                         If high and low are not integers, an error message
    //                         appears.
    public void paint(Graphics screen)
         //screen.drawString("HORSE RACES!!!!!", 40,60);
         //startGameButton.move(50,300);
         betAmountBox.setPosition(115,200);
         startGame();
         if(betAmountBox.isInt())
              int betAmount=getBetAmount();
         else
    screen.drawString("ERROR: You have not entered an Integer!", 10,110);
    screen.drawString(" Please correct your mistake.", 40,125);
         /*int xPos=10;
         int yPos=10;
         for(int i=0; i<drawings.length; i++)
              drawings[i].move(xPos,yPos);
              xPos+=60;
         screen.drawString("Click each button and get a surprise!", 10,50);*/
    // Method Name: inputBoxes()
    // Parameters Passed: None
    // Data Returned: None
    // Method Purpose: Where we initialise the inputboxes, set the size of
    // the InputField and adds it to the screen. Also
    // initialises the InputField to start with 1's
    void inputBoxes()
    betAmountBox = new InputField(5);
    add(betAmountBox);
    betAmountBox.initialise(50);
    // Method Name: getBetAmount()
    // Parameters Passed: Variable number
    // Data Returned: None
    // Method Purpose: Returns the variable number back to the paint()
    int getBetAmount()
    int betAmount=betAmountBox.toInt();
    return betAmount;
    // Method Name: action()
    // Parameters Passed: Event variable evt, Object varible obj
    // Data Returned: Variable true
    // Method Purpose: This block responds when the user takes an action
    // (such as hitting the return key). It causes the paint
    // block to be done again
    public boolean action(Event evt, Object arg)
    Graphics screen=getGraphics();
    if(evt.target instanceof Button)
         if(arg=="Click to Start Game")
              screen.clearRect(0,0,600,600);
              startGame();
    /*if(evt.target instanceOf Button)
                   if(arg=="Face")
                        screen.clearRect(5,55,400,400);
                        faceDrawing();
                   else if (arg=="Cheese")
                        screen.clearRect(5,55,400,400);
                        cheeseDrawing();
                   else if (arg=="Stick")
                        screen.clearRect(5,55,400,400);
                        stickDrawing();
                   else if (arg=="Mashed Potatoes")
                        screen.clearRect(5,55,400,400);
                        potatoeDrawing();
    return true;
    void startGame()
    Graphics screen=getGraphics();
              //Horse Racing Box
              screen.drawRect(10,10,505,120);
              screen.drawLine(60,10,60,130);
              screen.drawLine(10,40,515,40);
              screen.drawLine(10,70,515,70);
              screen.drawLine(10,100,515,100);               
              screen.setColor(Color.red);
              screen.fillRect(11,11,49,29);
              screen.setColor(Color.yellow);
              screen.fillRect(11,41,49,29);
              screen.setColor(Color.blue);
              screen.fillRect(11,71,49,29);
              screen.setColor(Color.orange);
              screen.fillRect(11,101,49,29);
              screen.setColor(Color.black);
              //Betting Box          
              screen.drawRect(10,150,280,100);     
              screen.drawLine(10,185,290,185);
              screen.drawLine(80,150,80,185);
              screen.drawLine(150,150,150,185);
              screen.drawLine(220,150,220,185);
              screen.setColor(Color.red);
              screen.fillRect(11,151,69,34);
              screen.setColor(Color.yellow);
              screen.fillRect(81,151,69,34);
              screen.setColor(Color.blue);
              screen.fillRect(151,151,69,34);
              screen.setColor(Color.orange);
              screen.fillRect(221,151,69,34);
              screen.setColor(Color.black);
              screen.drawString("BET = ", 40,230);
    screen.drawImage(redHorse, 200,200,300,300,this); //<---------//      
    The picture an't showing up... why? First time trying to insert images. (I made arrows where I did stuff with the image.)
    -sachit

    BTW, ignore the buttons and stuff. I just quickly grabbed this file from an earlier button program. :p
    -sachit

  • Opening new applet windows with button

    I'm having a bit of trouble. I have this button when you click it, would open up another window with text in it. That works perfectly. But when I try to add another button for another window, it doesn't go perfectly.
    I took out the useless code to show you the main stuff I'm working with.
    import java.awt.*;
    import java.applet.*;
    public class HorseRacing extends Applet
        CustomFrame gameWindow;
        CustomFrame creditWindow;
        Button openGame, openCredit;
        Image redHorse, yellowHorse, blueHorse, orangeHorse;
        public void init()         
              //Initializes the images
            redHorse = getImage(getCodeBase(), "../classes/horsered.GIF");
            yellowHorse = getImage(getCodeBase(), "../classes/horseyellow.GIF");
            blueHorse = getImage(getCodeBase(), "../classes/horseblue.GIF");
            orangeHorse = getImage(getCodeBase(), "../classes/horseorange.GIF");
              //Instructions window
            gameWindow= new CustomFrame("21 Century Horse Racing - Instructions", redHorse);
              openGame=new Button("View Instructions");
              add(openGame);
              //Credit window
              creditWindow=new CustomFrame2("21 Century Horse Racing - Credits");
              openCredit=new Button("View Credits");
              add(openCredit);
        //  Method Name: action()
        //  Parameters Passed: Event variable evt, Object varible obj
        //  Data Returned: Variable true
        //  Method Purpose: This block responds when the user takes an action
        //                  (such as hitting the return key). It causes the paint
        //                  block to be done again
        public boolean action(Event evt, Object arg)
            Graphics screen=getGraphics();
               boolean visible=gameWindow.isShowing();
            boolean visible2=creditWindow.isShowing();
               if(evt.target instanceof Button)
                 if(visible)
                         gameWindow.hide();
                         openGame.setLabel("View Instructions");
                    else
                         gameWindow.show();
                         openGame.setLabel("Close Instructions");
                    if(visible2)
                         creditWindow.hide();
                         openCredit.setLabel("View Credits");
                    else
                         creditWindow.show();
                         openCredit.setLabel("Close Credits");
            return true;
    //  Name: Sachit Harish
    //  Name of Program: CustomFrame
    //  Date Started: May 15, 2003
    //  Date Finished: 2003
    //  Program Description: This is a racing game where the program will
    //                               generate random odds for the 4 horses. The user
    //                               can then choose their horse and place a bet.
    //                               The user will then see the horses race, and the
    //                               money will be handed out depending on the odds.
    class CustomFrame extends Frame
         CustomFrame(String title,Image redHorse)
              super(title);
              Graphics screen=getGraphics();
              //getClass().getResource("../classes/horsered.GIF").getImage();
              //redHorse=getImage("../classes/horsered.GIF");
              //screen.drawImage(redHorse, 0,0,10,10,this);
         public void init()
              setBackground(Color.gray);
         public void paint(Graphics screen)
              resize(430,280);
              screen.setColor(Color.lightGray);
              screen.fillRect(0,0,500,500);
              screen.setColor(Color.black);
              screen.drawRect(15,40,402,185);
              screen.drawRect(14,39,404,187);
              screen.setColor(Color.gray);
              screen.fillRect(16,41,401,24);
              screen.setColor(Color.black);
              screen.drawString("- - Instructions - -", 160,58);
              screen.drawLine(15,65,417,65);
              screen.drawString("    Once you start clicking on the checkboxes to choose your horse, the", 20,80);
              screen.drawString("odds will be created beside the horses. You can then select the horse",20,95);
              screen.drawString("you want with the checkboxes and in the input box place your bet amount",20,110);
              screen.drawString("Press enter to confirm your bet and click 'Race'.",20,125);
              screen.drawString("    The horses will then race, and once they finish, the winner will be",20,145);
              screen.drawString("displayed. If you didn't choose that horse, you will lose the money you",20,160);
              screen.drawString("bet. If you won, you will be payed out depending on the odds of that",20,175);
              screen.drawString("horse. Your bank will change according to how much money you lost or",20,190);
              screen.drawString("made. Once that is over, new odds will be created and you can play",20,205);
              screen.drawString("again.",20,220);
                 //Image title = getImage(getCodeBase(), "../classes/titlepicture.jpg");
            //screen.drawImage(title, 0,0,430,220,this);         
    //  Name: Sachit Harish
    //  Name of Program: CustomFrame
    //  Date Started: May 15, 2003
    //  Date Finished: 2003
    //  Program Description: This is a racing game where the program will
    //                               generate random odds for the 4 horses. The user
    //                               can then choose their horse and place a bet.
    //                               The user will then see the horses race, and the
    //                               money will be handed out depending on the odds.
    class CustomFrame2 extends Frame
         CustomFrame2(String title)
              super(title);
              Graphics screen=getGraphics();
              //getClass().getResource("../classes/horsered.GIF").getImage();
              //redHorse=getImage("../classes/horsered.GIF");
              //screen.drawImage(redHorse, 0,0,10,10,this);
         public void init()
              setBackground(Color.gray);
         public void paint(Graphics screen)
              resize(430,280);
              screen.setColor(Color.lightGray);
              screen.fillRect(0,0,500,500);
              screen.setColor(Color.black);
              screen.drawRect(15,40,402,185);
              screen.drawRect(14,39,404,187);
              screen.setColor(Color.gray);
              screen.fillRect(16,41,401,24);
              screen.setColor(Color.black);
              screen.drawString("- - Credits - -", 160,58);
              screen.drawLine(15,65,417,65);
              screen.drawString("    CREDITS", 20,80);
                 //Image title = getImage(getCodeBase(), "../classes/titlepicture.jpg");
            //screen.drawImage(title, 0,0,430,220,this);         
    }If I take away everything associated with the creditWindow, it will work. But when I add that in, I get problems.
    Also, I let in those redHorse, yellowHorse, blueHorse, and orangeHorse images because thats another problem I'm having - to get an image to work in one of those new windows.
    -s64

    What happens if you change to a modern action listener?

Maybe you are looking for