BoxView and paint method

Hello, i would like to know how the paint(Graphics g, Shape allocation) method is working, especially how it gets the Shape object. I would like to reuse this Shape object in other method. My class subclass javax.swing.text.BoxView.
thansk for help

http://java-sl.com/JEditorPaneStructureTool.html
Here you can see how the view bounds is highlighted when you click on appropriate view in the tree. Check the source code how the bounds are calculated.
Hope this helps.
Regards,
Stas

Similar Messages

  • Problem in paint() method

    i have defined a new class which extends JPanel. In that I have defined a paintComponent() method. i dont know how to use the repaint() method.
    can anyone help?

    i have defined a new class which extends JPanel. In
    that I have defined a paintComponent() method. i dont
    know how to use the repaint() method.I do not fully understand your problem, sorry. Could you please clarify a bit?
    The repaint()-method is there to draw an image to the screen once again, to make changes visible. As far as I know, it calls the update()- and paint()-methods whenever you call it.

  • Printing with Book and paint()

    I'm posting this because I'm hoping someone can unconfuse me!
    I'm trying to use a Book class, so the correct number of pages appears in the printer dialogue. However, I don't seem to be able to get this to work. My confusion is over the following. In http://java.sun.com/j2se/1.3/docs/guide/2d/spec/j2d-print.fm4.html (section 7.4.2) it has an example with the following three lines:
    Book bk = new Book();
    bk.append(new PaintCover(), pfl);
    bk.append(new PaintContent(), job.defaultPage(), 2);
    and it states this is used to print two pages. Yet the API states the third parameter 'Appends numPages pages to the end of this Book.' This would imply three pages are printed, one of PaintCover and two of PaintContent.
    Furthermore, there is the pgnum parameter in the print() method. Now I would have thought that is tied in with this third Book parameter. But that seems to have a life of its own. It is supposed to be a zero-based index. But does that mean that PaintContent.print() will initially receive the value 1 (ie page 2), and be called twice (because of the argument 2) in the code extract above?
    If so, do you need to have the Printable.NO_SUCH_PAGE return value in the method?
    Perhaps my question should be: how do the third parameters of the Book class and paint() methods work, and how do they relate to each other.
    As I say I am very badly confused, and any advice, help or otherwise prodding in the correct direction will be welcomed! :-)
    Joe.

    Printable.NO_SUCH_PAGE is usefull when u r not using Book ..
    ex, if you use
    book = new Book();
    book.append(this,pageFormat,10);
    printJob.setPageable(book); it will print 10 pages
    and
    printJob.setPrintable(this,pageFormat); will print until you call Printable.NO_SUCH_PAGE - which is usefull when you dont know number of pages

  • Stuck with the paint and repaint methods

    I am supposed to create a JApplet with a button and a background color. When the button is clicked the first time a word is supposed to appear (I got that part), when the button is clicked the second time the word is supposed to appear again in a different color and in a different location on the Applet (I got that part).
    The problem is that the first name is supposed to disappear when the second word appears. So I know I have to repaint the screen when the button is clicked the second time and draw the first string in the same color as the background color to make it invisible.
    My problem is I am not sure how I can code to apply different settings each time the button is clicked. Can anyone help? Please let me know if my explanation sucks. I will try to explain better. However here is the code I have so far. I added a counter for the button just for testing purposes.
    I just need some hints on what to do and if there is a easier way than using that if statement please let me know. I probably make it harder than it is.
    Thanks in advance and Merry Christmas.
    import javax.swing.*;
       import java.awt.*;
       import java.awt.event.*;
        public class DisplayMyName extends JApplet
        implements ActionListener
          String myName = "DOG";
          String myName1 = "DOG";
          JButton moveButton = new JButton("Move It");
          Font smallFont = new Font("Arial", Font.BOLD, 12);
          Font largeFont = new Font("Lucida Sans", Font.ITALIC, 20);
          int numClicks = 0;
          JLabel label = new JLabel("Number of button clicks:" + numClicks);
           public void init()
             Container con = getContentPane();
             con.setBackground(Color.RED);
             con.setLayout( new FlowLayout() );
             con.add(moveButton);
             con.add(label);
             moveButton.addActionListener(this);
           public void paint(Graphics g)
             numClicks++;
             label.setText("Number of button clicks: " + numClicks);
             if (numClicks == 2)
             { g.setFont(smallFont);
                g.setColor(Color.BLUE);
                g.drawString(myName, 50, 100);
                   else
             if (numClicks == 3)
             { g.setFont(largeFont);
                g.setColor(Color.YELLOW);
                g.drawString(myName, 100, 200);
           public void actionPerformed(ActionEvent move)
             repaint();
       }

    You're putting your program logic in the paint method, something you should not do. For instance, try resizing your applet and see what effect that has on number of button clicks displayed. This is all a side effect of the logic being in the paint method.
    1) Don't override paint, override paintComponent.
    2) Don't draw/paint directly in the JApplet. Do this in a JPanel or JComponent, and then add this to the JApplet. In fact I'd add the button, the and the label to the JPanel and add the label to the JApplet's contentPane (which usually uses BorderLayout, so it should fill the applet).
    3) Logic needs to be outside of paint/paintComponent. the only code in the paintComponent should be the drawing/painting itself. The if statements can remain within the paintComponent method though.
    4) When calling repaint() make sure you do so on the JPanel rather than the applet itself.
    For instance where should numClicks++ go? Where should the code to change the label go? in the paint/paintComponent method? or in the button's actionlistener? which makes more sense?
    Edited by: Encephalopathic on Dec 24, 2008 9:37 AM

  • Mixing a paint method and labels???

    Hi,
    I've got a panel which has a paint method which draws various shapes, it also has someJLabels. The problem is when i add this paint method to the class then all the JLabels disappear! If i remove it then they display as normal.
    Please can someone help
    Cath

    I think you should be overriding the paintComponent() method of the JPanel.
    Here is a link to a section in the Swing tutorial titled "Painting".
    http://java.sun.com/docs/books/tutorial/uiswing/overview/draw.html
    Don't forget to continue with the "Working with Graphics" link at the bottom. (This will explain why you should use paintComponent() method).

  • Adding a JButton when there's a paint method

    I'm creating a game application, sort of like a maze, and I want to add buttons to the levelOne panel to be able to move around the maze. When I add the buttons to the panel they don't appear, I assume the paint method is the reason for this. here's my code, I have 3 files, ill post the user_interface, and the levels class, where the level is created and where i tried to add the button. I tried putting the buttons in a JOptionPane, but then my JMenu wouldn't work at the same time the OptionPane was opened. If anyone knows a way around this instead, please let me know. I also tried using a separate class with a paintComponent method in it, and then adding the button (saw on a forum, not sure if it was this one), but that didn't work either. Also, if there is a way just to simply have the user press the directional keys on the keyboard and have the program perform a certain function when certain keys are pressed, I'd like to know, as that would solve my whole problem. Thanks.
    //Libraries
    import java.awt.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.text.*;
    public class User_Interface extends JFrame
    static Levels l = new Levels ();
    static Delay d = new Delay ();
    private Container contentPane = getContentPane ();
    private JPanel main, levelOne;
    private String level;
    private CardLayout cc = new CardLayout ();
    private GridBagConstraints gbc = new GridBagConstraints ();
    private JPanel c = new JPanel ();
    private String label = "MainMenu";
    public User_Interface ()
    //Generates the User-Interface
    super ("Trapped");
    main = new JPanel ();
    GridBagLayout gbl = new GridBagLayout ();
    main.setLayout (gbl);
    c.setLayout (cc);
    // set_gbc (gbc, 2, 2, 5, 5, GridBagConstraints.NONE);
    c.add (main, "Main Page");
    contentPane.add (c, BorderLayout.CENTER);
    cc.show (c, "Main Page");
    levelOne = new JPanel ();
    levelOne.setLayout (new GridBagLayout ());
    levelOne.setBackground (Color.black);
    c.add (levelOne, "LevelOne");
    JMenuBar menu = new JMenuBar ();
    JMenu file = new JMenu ("File");
    JMenu help = new JMenu ("Help");
    JMenuItem about = new JMenuItem ("About");
    JMenuItem mainmenu = new JMenuItem ("Main Menu");
    mainmenu.addActionListener (
    new ActionListener ()
    public void actionPerformed (ActionEvent event)
    cc.show (c, "Main Page");
    label = "MainMenu";
    JMenuItem newGame = new JMenuItem ("New Game");
    newGame.addActionListener (
    new ActionListener ()
    public void actionPerformed (ActionEvent event)
    l.xCord = 2;
    l.yCord = 2;
    l.xLoc = 140;
    l.yLoc = 140;
    JPanel entrance = new JPanel ();
    entrance.setLayout (new FlowLayout ());
    c.add (entrance, "Entrance");
    label = "Entrance";
    level = "ONE";
    cc.show (c, "Entrance");
    JMenuItem loadgame = new JMenuItem ("Load Game");
    JMenuItem savegame = new JMenuItem ("Save Game");
    JMenuItem exit = new JMenuItem ("Exit");
    exit.addActionListener (
    new ActionListener ()
    public void actionPerformed (ActionEvent event)
    JFrame frame = new JFrame ();
    frame.setLocation (10, 10);
    JOptionPane.showMessageDialog (frame, "Come Back Soon!", "TRAPPED", JOptionPane.INFORMATION_MESSAGE);
    System.exit (0);
    file.add (about);
    file.add (mainmenu);
    file.add (newGame);
    file.add (loadgame);
    file.add (savegame);
    file.add (exit);
    menu.add (file);
    menu.add (help);
    setJMenuBar (menu);
    //Sets the size of the container (columns by rows)
    setSize (750, 550);
    //Sets the location of the container
    setLocation (10, 10);
    //Sets the background colour to a dark blue colour
    main.setBackground (Color.black);
    //Makes the container visible
    setVisible (true);
    public void paint (Graphics g)
    super.paint (g);
    g.setColor (Color.white);
    if (label == "MainMenu")
    for (int x = 0 ; x <= 50 ; ++x)
    g.setColor (Color.white);
    g.setFont (new Font ("Arial", Font.BOLD, x));
    g.drawString ("T R A P P E D", 100, 125);
    d.delay (10);
    if (x != 50)
    g.setColor (Color.black);
    g.drawString ("T R A P P E D", 100, 125);
    if (label == "Entrance")
    l.Entrance ("ONE", g);
    label = "LevelOne";
    if (label == "LevelOne")
    l.LevelOne (g, levelOne, gbc);
    label = "";
    public static void main (String[] args)
    // calls the program
    User_Interface application = new User_Interface ();
    application.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
    } //End of Main Method
    //Libraries
    import java.awt.*;
    import java.io.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class Levels extends Objects
    private JFrame frame = new JFrame ();
    //Sets location, size, and visiblity to the frame where the JOptionPane
    //will be placed
    frame.setLocation (600, 600);
    frame.setSize (1, 1);
    frame.setVisible (false);
    public int xCord = 2;
    public int yCord = 2;
    public void LevelOne (Graphics g, JPanel one, GridBagConstraints gbc)
    ***Trying to add the button, doesn't appear. Tried adding to the container, and any JPanel i had created***
    JButton button1 = new JButton ("TEST");
    one.add (button1);
    g.setColor (Color.white);
    g.fillRect (500, 100, 200, 300);
    g.setColor (Color.black);
    g.drawRect (500, 100, 200, 300);
    g.setFont (new Font ("Verdana", Font.BOLD, 25));
    g.setColor (Color.black);
    g.drawString ("LEVEL ONE", 525, 80);
    //ROW ONE
    counter = -80;
    counter2 = 200;
    for (int a = 1 ; a <= 7 ; ++a)
    if (xCord < a && yCord == 0)
    g.setColor (darkGray);
    g.fillRect (xLoc + counter, yLoc - 80, 40, 40);
    g.setColor (Color.black);
    g.drawRect (xLoc + counter, yLoc - 80, 40, 40);
    if (xCord > a - 1 && yCord == 0)
    g.setColor (darkGray);
    g.fillRect (xLoc + counter2, yLoc - 80, 40, 40);
    g.setColor (Color.black);
    g.drawRect (xLoc + counter2, yLoc - 80, 40, 40);
    counter += 40;
    counter2 += 40;
    *****Theres 9 more rows, just edited out to save space****
    int y = 100;
    int x = 100;
    for (int a = 0 ; a < 20 ; ++a)
    g.setColor (Color.white);
    g.fillRoundRect (x, y, 40, 40, 5, 5);
    g.setColor (Color.black);
    g.drawRoundRect (x, y, 40, 40, 5, 5);
    y += 40;
    if (a == 9)
    x += 320;
    y = 100;
    x = 140;
    y = 100;
    for (int a = 0 ; a < 14 ; ++a)
    g.setColor (Color.white);
    g.fillRoundRect (x, y, 40, 40, 5, 5);
    g.setColor (Color.black);
    g.drawRoundRect (x, y, 40, 40, 5, 5);
    x += 40;
    if (a == 6)
    x = 140;
    y += 360;
    g.setColor (Color.black);
    g.drawRect (100, 100, 360, 400);
    ImageIcon[] images = new ImageIcon [4];
    images [0] = new ImageIcon ("arrow_left.gif");
    images [1] = new ImageIcon ("arrow_up.gif");
    images [2] = new ImageIcon ("arrow_down.gif");
    images [3] = new ImageIcon ("arrow_right.gif");
    int direction = -1;
    *****This is where I tried to have the OptionPane show the directional buttons******
    //frame.setVisible (true);
    // direction = JOptionPane.showOptionDialog (frame, "Choose Your Path:", "Trapped", JOptionPane.YES_NO_CANCEL_OPTION,
    // JOptionPane.QUESTION_MESSAGE,
    // null,
    // images,
    // images [3]);
    // if (direction == 0)
    // if (xCord - 1 > 0)
    // xCord -= 1;
    // xLoc += 40;
    // if (direction == 1)
    // if (yCord - 1 > 0)
    // yCord -= 1;
    // yLoc += 40;
    // if (direction == 2)
    // if (yCord + 1 < 9)
    // yCord += 1;
    // yLoc -= 40;
    // if (direction == 3)
    // if (xCord + 1 < 13)
    // xCord += 1;
    // xLoc -= 40;
    //LevelOne (g, one, gbc);
    }

    i tried adding a keylistener, that didn't work too well, i had tried to add it to a button and a textarea which i added to the 'one' frame, it didn't show up, and it didn't work. How would i go about changing the paint method so that it doesn't contain any logic? That's the only way I could think of getting the program to move forward in the game. Thanks.
    //Libraries
    import java.awt.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.text.*;
    public class User_Interface extends JFrame
        static Levels l = new Levels ();
        static Delay d = new Delay ();
        private Container contentPane = getContentPane ();
        private JPanel main, levelOne;
        private String level;
        private CardLayout cc = new CardLayout ();
        private GridBagConstraints gbc = new GridBagConstraints ();
        private JPanel c = new JPanel ();
        private String label = "MainMenu";
        public User_Interface ()
            //Generates the User-Interface
            super ("Trapped");
            main = new JPanel ();
            GridBagLayout gbl = new GridBagLayout ();
            main.setLayout (gbl);
            c.setLayout (cc);
            // set_gbc (gbc, 2, 2, 5, 5, GridBagConstraints.NONE);
            c.add (main, "Main Page");
            contentPane.add (c, BorderLayout.CENTER);
            cc.show (c, "Main Page");
            levelOne = new JPanel ();
            levelOne.setLayout (new GridBagLayout ());
            levelOne.setBackground (Color.black);
            c.add (levelOne, "LevelOne");
            JMenuBar menu = new JMenuBar ();
            JMenu file = new JMenu ("File");
            JMenu help = new JMenu ("Help");
            JMenuItem about = new JMenuItem ("About");
            JMenuItem mainmenu = new JMenuItem ("Main Menu");
            mainmenu.addActionListener (
                    new ActionListener ()
                public void actionPerformed (ActionEvent event)
                    cc.show (c, "Main Page");
                    label = "MainMenu";
            JMenuItem newGame = new JMenuItem ("New Game");
            newGame.addActionListener (
                    new ActionListener ()
                public void actionPerformed (ActionEvent event)
                    l.xCord = 2;
                    l.yCord = 2;
                    l.xLoc = 140;
                    l.yLoc = 140;
                    JPanel entrance = new JPanel ();
                    entrance.setLayout (new FlowLayout ());
                    c.add (entrance, "Entrance");
                    label = "Entrance";
                    level = "ONE";
                    cc.show (c, "Entrance");
            JMenuItem loadgame = new JMenuItem ("Load Game");
            JMenuItem savegame = new JMenuItem ("Save Game");
            JMenuItem exit = new JMenuItem ("Exit");
            exit.addActionListener (
                    new ActionListener ()
                public void actionPerformed (ActionEvent event)
                    JFrame frame = new JFrame ();
                    frame.setLocation (10, 10);
                    JOptionPane.showMessageDialog (frame, "Come Back Soon!", "TRAPPED", JOptionPane.INFORMATION_MESSAGE);
                    System.exit (0);
            file.add (about);
            file.add (mainmenu);
            file.add (newGame);
            file.add (loadgame);
            file.add (savegame);
            file.add (exit);
            menu.add (file);
            menu.add (help);
            setJMenuBar (menu);
            //Sets the size of the container (columns by rows)
            setSize (750, 550);
            //Sets the location of the container
            setLocation (10, 10);
            //Sets the background colour to a dark blue colour
            main.setBackground (Color.black);
            //Makes the container visible
            setVisible (true);
        public void paint (Graphics g)
            super.paint (g);
            g.setColor (Color.white);
            if (label == "MainMenu")
                for (int x = 0 ; x <= 50 ; ++x)
                    g.setColor (Color.white);
                    g.setFont (new Font ("Arial", Font.BOLD, x));
                    g.drawString ("T    R    A    P    P    E    D", 100, 125);
                    d.delay (10);
                    if (x != 50)
                        g.setColor (Color.black);
                        g.drawString ("T    R    A    P    P    E    D", 100, 125);
            if (label == "Entrance")
                l.Entrance ("ONE", g);
                label = "LevelOne";
            if (label == "LevelOne")
                l.LevelOne (g, levelOne, gbc);
                label = "";
            //g.setColor (new Color
        public static void main (String[] args)
            // calls the program
            User_Interface application = new User_Interface ();
            application.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        } //End of Main Method
    //Libraries
    import java.awt.*;
    import java.io.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.ActionMap;
    import javax.swing.plaf.*;
    public class Levels extends Objects
        implements KeyListener
        //static final String newline = System.getProperty ("line.separator");
        JButton button;
        private JFrame frame = new JFrame ();
            //Sets location, size, and visiblity to the frame where the JOptionPane
            //will be placed
            frame.setLocation (600, 600);
            frame.setSize (1, 1);
            frame.setVisible (false);
        JButton button1;
        public int xCord = 2;
        public int yCord = 2;
        public void LevelOne (Graphics g, JPanel one, GridBagConstraints gbc)
        //    button = new JButton ("TEST");
        //    ButtonHandler handler = new ButtonHandler ();
         //   button.addActionListener (handler);
          //  one.add (button);
            g.setColor (Color.white);
            g.fillRect (500, 100, 200, 300);
            g.setColor (Color.black);
            g.drawRect (500, 100, 200, 300);
            g.setFont (new Font ("Verdana", Font.BOLD, 25));
            g.setColor (Color.black);
            g.drawString ("LEVEL ONE", 525, 80);
            //ROW ONE
            counter = -80;
            counter2 = 200;
            for (int a = 1 ; a <= 7 ; ++a)
                if (xCord < a && yCord == 0)
                    g.setColor (darkGray);
                    g.fillRect (xLoc + counter, yLoc - 80, 40, 40);
                    g.setColor (Color.black);
                    g.drawRect (xLoc + counter, yLoc - 80, 40, 40);
                if (xCord > a - 1 && yCord == 0)
                    g.setColor (darkGray);
                    g.fillRect (xLoc + counter2, yLoc - 80, 40, 40);
                    g.setColor (Color.black);
                    g.drawRect (xLoc + counter2, yLoc - 80, 40, 40);
                counter += 40;
                counter2 += 40;
            int y = 100;
            int x = 100;
            for (int a = 0 ; a < 20 ; ++a)
                g.setColor (Color.white);
                g.fillRoundRect (x, y, 40, 40, 5, 5);
                g.setColor (Color.black);
                g.drawRoundRect (x, y, 40, 40, 5, 5);
                y += 40;
                if (a == 9)
                    x += 320;
                    y = 100;
            x = 140;
            y = 100;
            for (int a = 0 ; a < 14 ; ++a)
                g.setColor (Color.white);
                g.fillRoundRect (x, y, 40, 40, 5, 5);
                g.setColor (Color.black);
                g.drawRoundRect (x, y, 40, 40, 5, 5);
                x += 40;
                if (a == 6)
                    x = 140;
                    y += 360;
            g.setColor (Color.black);
            g.drawRect (100, 100, 360, 400);
            ImageIcon[] images = new ImageIcon [4];
            images [0] = new ImageIcon ("arrow_left.gif");
            images [1] = new ImageIcon ("arrow_up.gif");
            images [2] = new ImageIcon ("arrow_down.gif");
            images [3] = new ImageIcon ("arrow_right.gif");
            int direction = -1;
            //frame.setVisible (true);
            // direction = JOptionPane.showOptionDialog (frame, "Choose Your //\Path:", "Trapped", JOptionPane.YES_NO_CANCEL_OPTION,
            //         JOptionPane.QUESTION_MESSAGE,
            //         null,
            //         images,
            //         images [3]);
            // if (direction == 0)
            //     if (xCord - 1 > 0)
            //         xCord -= 1;
            //         xLoc += 40;
            // if (direction == 1)
            //     if (yCord - 1 > 0)
            //         yCord -= 1;
            //         yLoc += 40;
            // if (direction == 2)
            //     if (yCord + 1 < 9)
            //         yCord += 1;
            //         yLoc -= 40;
            // if (direction == 3)
            //     if (xCord + 1 < 13)
            //         xCord += 1;
            //         xLoc -= 40;
            one.addKeyListener (this);
            // one.add (button1);
            if (xCord == 1)
                LevelOne (g, one, gbc);
        /** Handle the key typed event from the text field. */
        public void keyTyped (KeyEvent e)
        /** Handle the key pressed event from the text field. */
        public void keyPressed (KeyEvent e)
            if (e.getSource () == "Up")
                JOptionPane.showMessageDialog (null, "Hi", "Hi", 0, null);
        /** Handle the key released event from the text field. */
        public void keyReleased (KeyEvent e)
            // displayInfo (e, "KEY RELEASED: ");
    }

  • Paint() method in an entity class

    Hi,
    I am trying to draw 2 shapes in a Canvas, one rectangle and a circle.
    However, I have an entity class for both the rectangle and the circle, something like:
    public class MyRectangle
    private int width, height;
    public MyRectangle() { ... }
    pulbic getWidth() { return width; }
    pulbic getHeight() { return Height; }
    I do not want to draw these 2 shape in the paint() method of the Canvas, I want my Rectangle class and my Circle to have their own paint method to draw themselves into the canvas, is it possible?
    If it is possible, can you tell me roughly how to do it?
    Do I have to extend the Component class?
    Thanks in advance.
    SK

    Hi,
    I tried to do what you mentioned as the following, but I cant get the circle display on the screen, do you know why? Thanks
    public class Ball extends Component
    private static final int diameter = 15;
    private int xPosition = 10, yPosition = 10;
    public Ball()
    public int getX() { return xPosition; }
    public int getY() { return yPosition; }
    public int getDiameter() { return diameter; }
    public void paint(Graphics g)
         super.paint(g);
    Graphics2D graphics2D = (Graphics2D)g;
    graphics2D.fillOval(xPosition, yPosition, diameter, diameter);
    public class MyFrame extends JFrame
    public MyFrame()
    // Set up the main frame
    super("Test");
    setPreferredSize(new Dimension(400, 300));
    Container contentPane = getContentPane();
         Ball aBall = new Ball();
         JPanel myPanel = new JPanel();
         myPanel.setBackground(Color.white);
         myPanel.setBorder(BorderFactory.createLineBorder(Color.black));
         myPanel.setOpaque(true);
    myPanel.add(aBall);
         contentPane.add(myPanel, BorderLayout.CENTER);     
    pack();
    /** The main method */
    public static void main(String[] args)
         MyFrame myFrame = new MyFrame();
    myFrame.setVisible(true);
    }

  • Paint() method is in infinite loop when focus is set to JTextPane

    Hi All,
    I am creating one JScrollPane, JPanel and JTextPane. JPanel is added to JScrollPane and JTextPane is added to JPanel. If I override paint() method in JPanel, its in infinite loop. I don't know why it is behaving like this. Can anyone solve my problem. Since, I am doing so much drawings in paint() method, its getting to slow.
    Here is the code what I wrote.
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TestTextPane1 extends JFrame {
         JPanel panel;
         JScrollPane pane;
         public TestTextPane1() {
              panel = new JPanel(new BorderLayout()) {
                   public void paint(Graphics g) {
                        super.paint(g);
                        System.out.println("inside paint");
              JTextPane textPane = new JTextPane();
              panel.add(textPane);
              pane = new JScrollPane(panel);
              getContentPane().add(pane);
              setSize(300, 200);
              setVisible(true);
         public static void main(String [] args) {
              new TestTextPane1();
    Any help will be useful for me.
    Regards
    Kishore.

    What are you trying to do? You are adding the textPane to the panel and then overriding the paint() method. The textPane will never be painted if you do this.
    In Swing, you should override the paintComponent() method, not the paint() method. See the Swing tutorial on Painting:
    http://java.sun.com/docs/books/tutorial/uiswing/overview/draw.html
    Don't forget to read the "Working With Graphics" link at the bottom.

  • How to use an object's paint method

    I have created a class imagePanel which extends a jPanel to display an image. When I create a new imagePanel object I pass it an image argument which is used to paint my image on the jPanel, so far so good. I don't wish to have to continuously create new ImamePanels to display new images so I thought I could make a set_Image method that would set a new image in an exising imagePanel object. This is where I run into problems how to use the existing object paint method to replace the image. I tried this without success:
    public Image setMyImage (Image myImage)
    imageX = myImage; // imageX is the image that is painted by the imagePanel object's paint method
    paint(g);
    Something must be wrong on how I access the paint method. Thanks for any help.
    Jack

    Yahoooo, got it. This was the code I needed and thanks for your help:
    public void setImage (Image myImage)
    imageX = myImage;
    repaint(300);
    }

  • Problem about calling paint method

    I have created a class to ask user input 3 floating-point numbers, using JApplet. the code list below
    import java.awt.Graphics;
    import javax.swing.*;
    public class Numbers
    double average,sum,product;
    String result;
    public void init()
    String firstNumber,secondNumber,thirdNumber;
    double num1,num2,num3;
    firstNumber=JOptionPane.showInputDialog("enter first number");
    secondNumber=JOptionPane.showInputDialog("Enter second number");
    thirdNumber=JOptionPane.showInputDialog("Enter thrid number");
    num1=Double.parseDouble(firstNumber);
    num2=Double.parseDouble(secondNumber);
    num3=Double.parseDouble(thirdNumber);
    sum=num1+num2+num3;
    product=num1*num2*num3;
    average=(num1+num2+num3)/3;
    result="";
    if(num1<num2 && num2<num3)
    result=result+num3+" is the largest number";
    if(num2>num1 && num2>num3)
    result=result+num2 +" is the largest number";
    if(num1>num2 && num2>num3)
    result=result+ num1+" is the largest number";
    public void paint(Graphics g)
    super.paint(g);
    g.drawString("sum is"+sum,25,25);
    g.drawString("product is"+ product,25,40);
    g.drawString("average is"+ average,25,60);
    g.drawString(" the largest number is"+result,25,80);
    however, after I compiled, it gave me the error message as:
    java:40: cannot resolve symbol
    symbol : method paint (java.awt.Graphics)
    location: class java.lang.Object
    super.paint(g);
    ^(pointer should point to the dot)
    don't know why,
    Message was edited by:
    ritchie_lin

    your class doesn't extend japplet or any other object for that matter. It does extend Object as all classes do, and Object has no paint method.
    Consider changing:
      public class Numbersto
      public class Numbers extends JAppletAlso, please use code tags next time you're posting code.
    Addendum: If this is not the JApplet portion of your code, it still has to subclass a Swing component that can accept painting such as JPanel. Also, with Swing you use paintComponent rather than paint.
    Message was edited by:
    petes1234

  • Hovering mouse over a button and painting

    The following code is what I have to try to paint a rectangle when ever I hover over a button. This rectangle will show a brief description of what the button will do. I'm doing something similar when pressing the help button and hovering over something a description in a rectangle shows up. But I cannot get the paint method to work. Can anyone tell me what I need to do to fix this.
    public void mouseMoved(MouseEvent e) {
                        //System.out.println("asdf");
                        showMessage("Test");
                   private void showMessage(String string)
                        public void paint(Graphics g)
                             g.fillRect(25, 20, 20, 20);
                             g.drawString("Hello", 25, 20);
                        //System.out.println(string);
                   }

    jadescor wrote:
    The following code is what I have to try to paint a rectangle when ever I hover over a button. This rectangle will show a brief description of what the button will do. I'm doing something similar when pressing the help button and hovering over something a description in a rectangle shows up. But I cannot get the paint method to work. Can anyone tell me what I need to do to fix this. You really need to read the Sun Java Graphics tutorial as your assumptions on how painting works is not correct. For instance, you shouldn't be calling the paint method directly.
    Also, do you want to be doing this Graphics? Would it be easier to just add a tool tip to your button (i.e., use setToolTipText(...))?
    Good luck.
    Edited by: Encephalopathic on Apr 19, 2008 8:20 PM

  • How to call paint() method during creating object

    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    class SomeShape extends JPanel {
         protected static float width;
         protected BasicStroke line = new BasicStroke(width, BasicStroke.CAP_ROUND, BasicStroke.CAP_ROUND);
    class Oval extends SomeShape {
         Oval(float width) {
              this.width = width;
              line = new BasicStroke(width, BasicStroke.CAP_ROUND, BasicStroke.CAP_ROUND);
              repaint();
         public void paint(Graphics g) {
              Graphics2D pen = (Graphics2D)g;
              int i = 10;
              super.paint(g);
                   g.setColor(Color.blue);
                   g.drawOval(90, 0+i, 90, 90);
                   System.out.println("paint()");
    public class FinalVersionFactory {
        JFrame f = new JFrame();
        Container cp = f.getContentPane();
        float width = 0;
        SomeShape getShape() {
             return new Oval(width++); //I want to paint this oval when I call getShape() method
         public FinalVersionFactory() {
              f.setSize(400, 400);
    //          cp.add(new Oval()); without adding
              cp.addMouseListener(new MouseAdapter() {
                   public void mouseReleased(MouseEvent e) {
                        getShape();
              f.setVisible(true);
         public static void main(String[] args) { new FinalVersionFactory(); }
    }I need help. When I cliked on the JFrame nothing happened. I want to call paint() method and paint Oval when I create new Oval() object in getShape(). Can you correct my mistakes? I tried everything...Thank you.

    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    class SomeShape extends JPanel {
         protected static float width;
         protected static BasicStroke line = new BasicStroke(width, BasicStroke.CAP_ROUND, BasicStroke.CAP_ROUND);
    class Oval extends SomeShape {
         static int x, y;
         Oval(float width, int x, int y) {
              this.width = width;
              this.x = x;
              this.y = y;
              line = new BasicStroke(width, BasicStroke.CAP_ROUND, BasicStroke.CAP_ROUND);
         public void paint(Graphics g) {
              Graphics2D pen = (Graphics2D)g;
                   g.setColor(Color.blue);
                   pen.setStroke(line);
                   g.drawOval(x, y, 90, 90);
                   System.out.println("Oval.paint()"+"x="+x+"y="+y);
    class Rect extends SomeShape {
         static int x, y;
         Rect(float width, int x, int y) {
              this.width = width;
              this.x = x;
              this.y = y;
              line = new BasicStroke(width, BasicStroke.CAP_ROUND, BasicStroke.CAP_ROUND);
         public void paint(Graphics g) {
              Graphics2D pen = (Graphics2D)g;
                   g.setColor(new Color(250, 20, 200, 255));      
                   pen.setStroke(line);
                   g.drawRect(x, y, 80, 80);
                   System.out.println("Rect.paint()"+"x="+x+"y="+y);
    public class FinalVersionFactory extends JFrame {
        Container cp = getContentPane();
        float width = 0;
        int x = 0;
        int y = 0;
            boolean rect = false;
        SomeShape getShape() {
             SomeShape s;
              if(rect) {
                   s = new Rect(width, x, y);
                   System.out.println("boolean="+rect);
              } else {
                   s = new Oval(width++, x, y);
                   System.out.println("boolean="+rect);
              System.out.println("!!!"+s); //print Oval or Rect OK
              return s; //return Oval or Rect OK
         public FinalVersionFactory() {
              setSize(400, 400);
              SomeShape shape = getShape();
              cp.add(shape); //First object which is add to Container(Oval or Rect), returned by getShape() method
              //will be paint all the time. Why? Whats wrong?
              cp.addMouseListener(new MouseAdapter() {
                   public void mouseReleased(MouseEvent e) {
                        x = e.getX();
                        y = e.getY();
                        rect = !rect;
                        getShape();
                        cp.repaint(); //getShape() return Oval or Rect object
                                      //but repaint() woks only for object which was added(line 67) as first
              setVisible(true);
         public static void main(String[] args) { new FinalVersionFactory(); }
    }I almost finish my program but I have last problem. I explained it in comment. Please look at it and correct my mistakes. I will be very greatful!!!
    PS: Do you thing that this program is good example of adoption Factory Pattern?

  • Determining if printing is going on in paint method

    By looking at the source of the existing visual components, I have found out that JComponent.paintChildren uses getFlag(IS_PRINTING) to determine wether or not the current call to paint will paint to screen or to a printer.
    The problem is that both getFlag and the constants it uses are declared as private in JComponent. This is why I am wondering why Sun chose to keep this information private to the JComponent class, while this information could be very useful in some situations.
    Also, would there be any alternatives to determine wether or not printing is occuring from a paint method besides managing flags the same way JComponent does?
    Thanks in advance.

    I gave a try to your approach but it doesn't seem that the graphics object passed to the paint method during the printing process implements PrintGraphics. I'll keep trying stuff with that idea until some new input is given, but thanks for the idea, it sure could have worked out ;)

  • Invoking paint method in Java3D

    I have some example programs in using Java3D but none of them paints 'directly' on the canvas3D.
    if i have a class that extends a Canvas3D how would i call the paint method, can i use this method to draw a 2D polygon on my canvas? (because i wanted to have 3D and 2D objects mixed).
    how would i do this? are the points in terms of x, y, z?
    can anyone help me with this?
    thanks in advance

    I've been trying to do this myself, snd it's a right pain in the arse.
    To actually paint on the Canvas3D, when you override postRender(), you do all your stuff but it doesn't work until you call flush(). However, when I tied it (just drawing a simple rectange), my app slowed from 20fps to 2, which is a bit too much of a performance hit for my liking.
    The J3D Repository overlay is fairly easy to set up, but for some reason the polygon it draws on is about 1 unit away from where you add it, so for a 1st person thing like I'm doing, it dissapears when you get too near a wall. In the end, i have just created my own by putting a texture on a cube just in front of the viewport.

  • How paint method in TiledLayer work ?

    It's my 1st time in forum. Does anyone has source code of Sprite, TiledLayer class or know how exactly the paint method work? I had used it in some game but not satisfied with it. I want to code my own class but i wonder it has some native or low-level code.
    Sorry for my poor E !!!

    perhaps you want to use a more hardware oriented approach. I can highly recommend you the Slick API. It is built on top of the LWJGL API set, which is a Java binding for OpenGL, OpenAL and provides device support such as joysticks/joypads. Slick turns the 3D part into an easy to use 2D rendering framework.
    [http://slick.cokeandcode.com/|http://slick.cokeandcode.com/]
    Basic example program:
    [http://slick.cokeandcode.com/wiki/doku.php?id=01_-_a_basic_slick_game|http://slick.cokeandcode.com/wiki/doku.php?id=01_-_a_basic_slick_game]

Maybe you are looking for