Painting to a JPanel Class

I'm trying to create a paint application for my degree dissertation and i've hit a bit of a snag. I have a Canvas which is an extenstion of a JPanel, but i dont know how to enable other classes to paint on it. Can anyone help me please?
thanks,
Greg

make your other classes call methods on your Canvas class. your Canvas class can paint on itself based on the method calls...

Similar Messages

  • Referencing an inner swingworker class in a JPanel class...?

    Hi,
    I've got an inner swingworker class defined inside an extended JPanel (we'll call it middleJ) class. Basically the swingworker class runs off a filtered file chooser. I have a method in the JPanel class that instantiates the inner class and kicks off the swing worker (we'll call it kickOffSwing). Now if I instantiate middleJ in an outer class and call the kickOffSwing() method, that should run the filtered filechooser right? Is this the right way to go about running a lengthy background process inside a nested class structure, or is there a more organised way of doing things?
    Cheers!

    Never mind. Got it working fine! I often find the act of putting together a question helps focus on the task at hnad.

  • Problem about JPanel Class

    Hello!I am a chinese Java2 learner.I want to ask you a question :
    Why do the instance variables of Jpanel class can not be declared as a array,just like JButton class?
    For example :
    JPanel[] pane = new JPanel[4];
    pane[0].add( ...);
    pane[1].add( ...);
    My program has passed the compile,but it can not run at all.Please experts give me an answer.Thank you very much!
    My E-mail:[email protected]

    what is the error message you get when you run the app.?

  • Paint component inside JPanel

    Hi guys,
    I will start with the original problem and get to the only option that seems possible before hardcoding everything.
    I need to draw something like a binary tree. Jtree doesn't fall into binary because it does not have the root in the center. <1;2;6;8;9>, where 6 is the root, and 1,2 are its left child's children and 8,9 are right child's children. Since I couldn't find any possible solution of customizing JTree to draw it in binary format, I am left with the following option that is a step towards hardcoding.
    Create a subclass of JPanel and paint inside it. The full hardcode method would be to draw everything right here, ie the lines and the boxes.
    But since I need to listen to box selections using mouse, I was hoping to draw the boxes using JPanel/JLabel and override their paint() method.
    So is there a way to paint components(JLabel/JPanel and lines) into a painted component (JPanel)? Note, the container JPanel is not using any layout. everything is being drawn using paint method.

    You are probably going to want to create smaller objects that handle their own painting. For example... Create an extension of JComponent that handles painting a single node. Then create the JPanel to add those to. You can even go as far as writing your own LayoutManager to handle laying the Components out in your binary layout. This is really the most effective way to do it, especially if you want to be able to detect clicks and what not. You can just add MouseListener's to the individual components than.
    Hope this helps,
    Josh Castagno
    http://www.jdc-software.com

  • Using paint() for a JPanel in a ScrollBar

    i have a class that extends JPanel and paints some graphics in it using the function paint(). like g.drawString.. i had to add an instantition of that class in the container of my main class within a scrollbar. It initially painted well but when i scroll, it gets distorted. its something like this
    public class PaintedPane extends JPanel
    public PaintedPane()
    paint()
    other codes here..
    public class MainClass extends JFrame
    public PaintedPane pane;
    public JScrollbar scroll;
    public MainClass()
    pane = new PaintedPane();
    scroll = new JScrollBar(pane);
    it seems that the pane wont update the part of the pane not initially exposed because of the scrollBar. how can i fix it? thanks!

    sorry for the wrong section.
    here is the code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class MainClass extends JFrame
         public TextDraw td;
         public JScrollPane pane;
         public Container c;
         public MainClass()
              c = getContentPane();
              c.setLayout(new FlowLayout());
              td = new TextDraw();
              td.setPreferredSize(new Dimension(300, 300));
              pane = new JScrollPane(td);
              pane.setPreferredSize(new Dimension(300, 200));
              c.add(pane);
              setSize(400, 400);
              show();
         public static void main(String args[])
              MainClass m = new MainClass();
              m.addWindowListener(
                   new WindowAdapter()
                        public void windClosing(WindowEvent e)
                             System.exit(0);
    }and another java file for the TextDraw
    import javax.swing.*;
    import java.awt.*;
    public class TextDraw extends JPanel
       public TextDraw()
             setBackground(Color.WHITE);           
                setSize(500,  500);
                show();
       public void paint(Graphics g)
              for(int x = 0; x < 20; x++)
                   g.drawString("Hello world!", 20, (x)*20);
                   g.fillRect(5, (x)*20, 10, 10);
    }i dont realy know what to do to fix this. And if i chang the values of the "setSize(400, 400)" of the MainClass to "setSize(300, 300)" it works fine. why is it like that? sorry im not very familiar with all the paint, paintComponent and graphics things. thanks!

  • Painting graphics on JPanel

    hi all,
    below is my code,
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.Graphics2D;
    import java.awt.Graphics.*;
    public class Testing extends JFrame implements ActionListener
    String x[] = { " ", "Material A", "Material B", "Material C"};
    String y[] = { "                       ", "+5", "+4", "+3", "+2", "+1", " 0",
         "-1", "-2", "-3", "-2", "-5" };
    private JButton Plot, End;
    private Container c;
    private JPanel centerPanel, northPanel, southPanel;
    private JComboBox designMaterialx, materialRatingy;
    String desMaterial = "";
    public Testing()
    super( "Welcome" );
         Container c = getContentPane();
         centerPanel = new JPanel()
              protected void paintComponent(Graphics g)
              super.paintComponent(g);
              Graphics2D g2d = (Graphics2D)g;
              g.setColor(Color.blue);
    g.drawRect(120, 120, 20, 200);
    g.drawString ("Material", 30, 220);
    g.drawString ("Ratings", 30, 240);
    g.drawString ("+5", 102, 130);
    g.drawString ("0", 107, 220);
    g.drawString ("-5", 102, 315);
              g.setColor(Color.red);
              g.drawRect(120, 321, 20, 200);
              g.drawString ("Design", 30, 410);
              g.drawString ("Materials", 30, 430);
              g2d.rotate(-Math.PI/2.0,250.0,250.0);
              g.setColor(Color.black);
              g.drawString(desMaterial, -15, 135);
              centerPanel.setBackground(Color.white);
         c.add( centerPanel, BorderLayout.CENTER);
         setVisible(true);
              northPanel = new JPanel();
              northPanel.add(new Label( "Please choose accordingly:" ));
         northPanel.setLayout (new FlowLayout(FlowLayout.CENTER, 20, 0));
    designMaterialx = new JComboBox( x );
    designMaterialx.setMaximumRowCount( 2 );
    designMaterialx.setBorder(BorderFactory.createTitledBorder("Design Materials"));
    northPanel.add( designMaterialx );
    designMaterialx.setEditable(true);
    materialRatingy = new JComboBox( y );
    materialRatingy.setMaximumRowCount( 2 );
    materialRatingy.setBorder(BorderFactory.createTitledBorder("Material Ratings"));
    northPanel.add( materialRatingy );
    c.add( northPanel, BorderLayout.NORTH );
    setVisible( true );
    southPanel = new JPanel();
    Plot = new JButton( "Plot" );
    End = new JButton( "End" );
    southPanel.add( Plot );
    southPanel.add( End );
    c.add( southPanel, BorderLayout.SOUTH );
    setVisible( true );
    Plot.addActionListener(this);
    End.addActionListener(this);
    Plot.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    desMaterial = designMaterialx.getSelectedItem().toString();
    centerPanel.repaint();
    System.out.println(desMaterial);
    pack();
    public static void main( String args[] )
    Testing app = new Testing();
    app.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    public void actionPerformed(ActionEvent e)
         if(e.getSource()==Plot)
              System.out.println("Plot");
         else if(e.getSource()==End)
              System.exit(0);
    at the moment when the plot jButton is pressed, the selected values of the design materials jComboBox will be painted on the centerPanel inside the red rectangle. upon subsequent selection of the design materials & pressing of the plot jbutton, i wish to add them next to the existing ones but i'm not sure how to do this. could anyone out there help me on this? any kind of help would be appreciated.
    thanks in advance.
    rolf

    Here's a bunch of ideasimport java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.ArrayList;
    public class Test3 extends JFrame {
      MyGraph mg = new MyGraph();
      JTextField nameField = new JTextField("Sample2");
      JTextField valueField = new JTextField("100");
      public Test3() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = getContentPane();
        mg.addData(new MyData("Sample",50));
        content.add(mg, BorderLayout.CENTER);
        JPanel dataPanel = new JPanel();
        dataPanel.add(new JLabel("Name:"));
        dataPanel.add(nameField);
        dataPanel.add(new JLabel("Value:"));
        dataPanel.add(valueField);
        JButton jb = new JButton("Add");
        dataPanel.add(jb);
        jb.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent ae) {
            mg.addData(new MyData(nameField.getText(),Integer.parseInt(valueField.getText())));
            mg.repaint();
        content.add(dataPanel, BorderLayout.NORTH);
        setSize(300,300);
      public static void main(String[] args) { new Test3().setVisible(true); }
    class MyGraph extends JPanel {
      ArrayList al = new ArrayList();
      public void addData(MyData data) { al.add(data); }
      public void paintComponent(Graphics g) {
        Graphics2D g2d = (Graphics2D)g;
        super.paintComponent(g2d);
        g2d.setColor(Color.red);
        int height = getHeight(), width=getWidth();
        for (int i=0; i<al.size(); i++) {
          MyData md = (MyData)al.get(i);
          g2d.drawRect(i*20,height-md.getNum(),17,md.getNum());
        g2d.rotate(-Math.PI/2.0,width/2,height/2);
        g2d.setColor(Color.blue);
        for (int i=0; i<al.size(); i++) {
          MyData md = (MyData)al.get(i);
          g2d.drawString(md.getName(),30,i*20-15);
    class MyData {
      String name;
      int num;
      public MyData(String name, int num) {
        this.name=name;
        this.num=num;
      public String getName() { return name; }
      public int getNum() { return num; }
    }

  • Painting Shapes onto JPanels

    hi, I'm currently trying to draw shapes in java for the first time. I've been looking at the tutorials and examples for java.sun but I'm having a few problems.
    At the moment I have code as follows:
    public class drawShape{
    public void paintComponent(Graphics g) {
    g.drawRect(2,2,2,2);
    I want to draw the rectangle onto a form called mainCanvas which is just a normal JPanel. I've been trying but am unsure how to get this working. I've tried mainCanvas.drawRect but that won't work. and in all the examples given on java.sun I can't see what Graphics g is supposed to be?
    Hope u can help

    The Graphics object gets passed to you. e.g.:
    public class MyPanel extends JPanel {
        // overriding paintComponent
        public void paintComponent(Graphics g) {
            g.drawRect(2,2,2,2);
    }Then when you add a MyPanel to a frame and make it visible, Swing's rendering system will make sure your paintComponent method gets called.

  • Painting from outside main class

    Im writing some generic code and im having trouble trying to get the called class to paint correctly. I have this code so far, and it works, but I dont like it. I pass in graphics as a parameter and it doesnt use the natural repaint method, so I was hoping someone could show me how to do this the "right way". I also want to avoid using threads, im pretty sure theyre not absolutely necessary.
    Theres 2 classes, essentially its
    class 1: paint a green splashscreen, user presses button> call class 2
    class 2: paint a white screen and moving ball
    (the while loop has been commented out so i can check the state of repaint. My normal programs automatically repaint if i minimise them, this one wont repaint properly).
    import java.awt.*;
    import java.applet.*;
    import java.awt.event.*;
    import java.net.*;
    import java.io.*;
    public class Multi extends Applet implements ActionListener{
    Mgame game=new Mgame();
    private Button host;
        public void init() {
        setLayout(null) ;
        setButtons();
        public void paint(Graphics g) {
        g.setColor(Color.green);   
        g.fillRect(0,0,700,500); 
         public void setButtons() {
        host= new Button ("Host Game");
        host.setBounds(470,395,100,30);
        add(host);
        host.addActionListener(this);
         public void actionPerformed(ActionEvent event)
                  Graphics g = getGraphics();
                  game.gamerun(g);
    import java.awt.*;
    import java.applet.*;
    import java.awt.event.*;
    import java.net.*;
    import java.io.*;
    class Mgame{
    int ballx = 0;
    Graphics g;
    public void xpaint(){
        g.setColor(Color.white);   
        g.fillRect(0,0,700,500);         
        g.setColor(Color.red);   
        g.fillOval(ballx, 40, 90, 90);
    public void gamerun(Graphics graphics){
        g=graphics;
        //while(true){
        ballx=ballx+1;
        if (ballx==500) {ballx=10;}
        try { Thread.sleep(100); } catch (Exception e) {}
        xpaint();
    }Thanks for any help.

    How would I fix that then?
    I tried using
    class Mgame extends Multi{
    <etc>
    }Which means that the program now compiles, but now the program seems to skip the Mgame.gamerun repaint() line, so the program looks like its freezed up.
    New code listing is:
    import java.awt.*;
    import java.applet.*;
    import java.awt.event.*;
    import java.net.*;
    import java.io.*;
    public class Multi extends Applet implements ActionListener{
    Mgame game;
    private Button host;
        public void init() {
        game=new Mgame();
        setLayout(null) ;
        setButtons();
        public void paint(Graphics g) {
        g.setColor(Color.green);   
        g.fillRect(0,0,700,500); 
         public void setButtons() {
        host= new Button ("Host Game");
        host.setBounds(470,395,100,30);
        add(host);
        host.addActionListener(this);
         public void actionPerformed(ActionEvent event)
                  game.gamerun();
    import java.awt.*;
    import java.applet.*;
    import java.awt.event.*;
    import java.net.*;
    import java.io.*;
    class Mgame extends Multi{
    int ballx = 0;
    public void paint(Graphics g){
        g.setColor(Color.white);   
        g.fillRect(0,0,700,500);         
        g.setColor(Color.red);   
        g.fillOval(ballx, 40, 90, 90);
    public void gamerun(){
        while(true){
        ballx=ballx+1;
        if (ballx==500) {ballx=10;}
        try { Thread.sleep(100); } catch (Exception e) {}
        repaint();
    }

  • Painting in JPanel with PaintComponent.

    Hi I've got a problem, if i define my JPanel like this then I can't paint in it.
    public class kvadrat
    JPanel aPanel;
    public void Panel()
      aPanel = new JPanel();
      aPanel.setBackground(Color.white);
      aPanel.add(sendButton);
    public void Frame()
      Panel();
      JFrame frame = new JFrame("Considerate Music");
      Container iRutan = frame.getContentPane();
      iRutan.setLayout(new BorderLayout());
      iRutan.add(aPanel);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setBounds(300,300,700,400);
      frame.setVisible(true);
    public kvadrat()
      Frame();
    public static void main(String[] args)
      new kvadrat();
    public void paintComponent(Graphics g)
    }I can't use the line super.paintComponent(g); in paintComponent because I don't have any extend. I don't want to have any extends on my class so this is why I'm asking, is there a way to paint on my panel(aPanel) in any other way that using extends. You see if I'd like to add more panels I'll have to create a class for each panel and I don't like that.

    2 Ways.
    #1: An Inner Class
    public class kvadrat{
    public kvadrat(){
    new MyPanel();
    //inner class
    public class MyPanel extends JPanel{
    // methods
    }or
    #2: Anonymous Inner Classes (very sloppy)
    public class kvadrat
    JPanel aPanel;
    public void Panel()
    // right here:
      aPanel = new JPanel(){
           public void paintComponent(Graphics g){
      // code goes here
      aPanel.setBackground(Color.white);
      aPanel.add(sendButton);
    public void Frame()
      Panel();
      JFrame frame = new JFrame("Considerate Music");
      Container iRutan = frame.getContentPane();
      iRutan.setLayout(new BorderLayout());
      iRutan.add(aPanel);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setBounds(300,300,700,400);
      frame.setVisible(true);
    public kvadrat()
      Frame();
    public static void main(String[] args)
      new kvadrat();
    // removed: public void paintComponent(Graphics g)
    }

  • Painting in JPanel directly

    Hi.
    Can any one help me with how to paint directly in JPanel, I need to paint directly in a swing component, but i dont know in which and how
    How i use the paintComponent method of JPanel class..
    Thanks.

    There are two ways to do this. If you are extending the JPanel class call the paintComponent method and put all your painting in there.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class ThingMie extends JPanel
    // private variables
    public ThingMie()
    // other gui stuff
    setBackground(Color.white);
    setBorder(BorderFactory.createRaisedBevelBorder());
    protected void paintComponent(Graphics g)
    super.paintComponent(g);
    // write a string
    g.setFont(new Font("Comic Sans MS", Font.PLAIN, 11));
    g.setColor(Color.red);
    g.drawString("hello", 6, 10);
    // draw a rectangle
    g.setColor(Color.green);
    g.drawRect(15, 15, 30, 60);
    // draw an ellipse
    g.setColor(Color.blue);
    g.drawOval(150, 20, 50, 100);
    public static void main(String [] args)
    JFrame thing = new JFrame();
    thing.addWindowListener(new WindowAdapter()
    public void windowClosing(WindowEvent e)
    System.exit(0);
    thing.getContentPane().add(new ThingMie(), BorderLayout.CENTER);
    thing.setTitle("Painting to a panel");
    thing.setSize(400, 300);
    thing.setVisible(true);
    If you're creating a JPanel within another component, say a JFrame or a JDialog you can use code like this:
    import java.awt.*;
    import javax.swing.*;
    class ThingMie extends JFrame
    // private variables
    private JPanel panel;
         public ThingMie()
              setDefaultCloseOperation(DISPOSE_ON_CLOSE);
              // other gui stuff
              panel = new JPanel()
                   protected void paintComponent(Graphics g)
                        super.paintComponent(g);
                        // write a string
                        g.setFont(new Font("Comic Sans MS", Font.PLAIN, 11));
                        g.setColor(Color.red);
                        g.drawString("hello", 6, 10);
                        // draw a rectangle
                        g.setColor(Color.green);
                   g.drawRect(15, 15, 30, 60);
                        // draw an ellipse
                        g.setColor(Color.blue);
                        g.drawOval(150, 20, 50, 100);
              panel.setBackground(Color.white);
              panel.setBorder(BorderFactory.createRaisedBevelBorder());
              getContentPane().add(panel, BorderLayout.CENTER);
         public static void main(String [] args)
              ThingMie thing = new ThingMie();
              thing.setTitle("Painting to a panel");
              thing.setSize(400, 300);
              thing.setVisible(true);
    /***********/

  • Class extends JPanel ? help

    i have a class that extends JPanel and i have all my buttons , textfields created on it.
    so how do i call the class to display the panel on a frame?
    asuming class is the class that extends JPanel
    class newPanel = new class();
    f.contentPane.add(newPanel);
    is this the right way?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Yeah... that works fine, just call f.show(). Mind your LayoutManager....

  • Problem with JPanel and/or Thread

    Hello all,
    I have the following problem.
    I have a JFrame containing to JPanels. The JPanels are placed
    via BorderLayout.
    JPanel #1 is for moving a little rectangle (setDoubleBufferd), it is
    a self defined object extending JPanel.
    The paint methon in JPanel #1 has been overwritten to do the drawings.
    JPanel #2 contains 4 JButtons, but they have no effect at the
    moment. It is an "original" JPanel.
    The class extending JFrame implemented the interface Runnable and
    is started in its own thread.
    After starting the programm everthing looks fine.
    But if I press a Button in the second JPanel this button is painted in
    the top left corner of my frame. It changes if I press another button.
    Any help would be appreciated.
    Thanks.
    Ralf

    I have a JFrame containing to JPanels. The JPanels are
    placed
    via BorderLayout.The type of Layout does not seem to be relevant
    >
    JPanel #1 is for moving a little rectangle
    (setDoubleBufferd), it is
    a self defined object extending JPanel.
    The paint methon in JPanel #1 has been overwritten to
    do the drawings.
    JPanel #2 contains 4 JButtons, but they have no effect
    at the
    moment. It is an "original" JPanel.
    The class extending JFrame implemented the interface
    Runnable and
    is started in its own thread.
    After starting the programm everthing looks fine.
    But if I press a Button in the second JPanel this
    button is painted in
    the top left corner of my frame. It changes if I press
    another button.
    I noticed you solved this by painting the whole JFrame.
    Yeh Form time to time I get this problem too......
    Especially if the screen has gone blank - by going and having a cup of tea etc -
    Text from one Panel would be drawn in another.. annoying
    At first it was because I changed the state of some Swing Components
    not from the Event Thread.
    So make sure that your new Thread doesn't just blithely call repaint() or such like cos that leads to problems
    but rather something like
    SwingUtilities.invokeLater( new Runnable()
       public void run()
          MyComponent.repaint();
    });However I still get this problem using JScrollPanes, and was able to fix it by using the slower backing store method for the JScrollPane
    I could not see from my code how something on one JPanel can get drawn on another JPanel but it was happening.
    Anyone who could totally enlighten me on this?

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

  • JPanel child zoom

    I am trying to get a JPanel to paint its child JPanel according to a certain scale factor which the user selects from a JComboBox that is also in the JPanel, the parent one. The problem is that it's painting funny and not scaling the child JPanel. Please take a look at my code. Thanks.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.geom.AffineTransform;
    import java.awt.event.*;
    public class ZoomPanel extends JPanel
         private double zoom_factor = 1.0;
         private JComboBox zoom_combo;
         private JPanel widget_panel, child_panel;
         public ZoomPanel( JPanel child )
              super( new BorderLayout() );
              zoom_combo =
                   new JComboBox(
                        new Double[]
                             new Double( 0.10 ), new Double( 0.25 ), new Double( 0.33 ),
                             new Double( 0.50 ), new Double( 0.75 ), new Double( 1.00 ),
                             new Double( 1.25 ), new Double( 1.50 ), new Double( 2.00 ),
                             new Double( 3.00 ), new Double( 4.00 ), new Double( 5.00 ),
              zoom_combo.setEditable( true );
              zoom_combo.setSelectedIndex( 5 );
              zoom_combo.addActionListener(
                   new ActionListener()
                        public void actionPerformed( ActionEvent ae )
                             zoom_factor = ((Double) zoom_combo.getSelectedItem()).doubleValue();
              widget_panel = new JPanel();
              widget_panel.add( zoom_combo );
              add( widget_panel, BorderLayout.NORTH );
              child_panel = child;
              add( child_panel, BorderLayout.CENTER );
         public JPanel getChild()
              return child_panel;
         * Returns the zoom factor.
         public double getZoom()
              return zoom_factor;
         * Changes zoom factor.
         public void setZoom( final double d )
              zoom_factor = d;
              repaint();
         public void paintChildren( Graphics g )
              widget_panel.repaint();
              ((Graphics2D) child_panel.getGraphics()).setTransform(
                   AffineTransform.getScaleInstance(
                        zoom_factor,
                        zoom_factor ) );
              child_panel.repaint();
    } // ZoomPanel.java

    Ok, I did the following changes to your class : import javax.swing.*;
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.awt.geom.AffineTransform;
    import java.awt.event.*;
    public class ZoomPanel extends JPanel {
         private JComboBox zoom_combo;
         private JPanel widget_panel;
         private ZoomedPanel child_panel;
         public ZoomPanel(ZoomedPanel child) {
              super(new BorderLayout());
              zoom_combo = new JComboBox(new Double[]{new Double(0.10), new Double(0.25), new Double(0.33), new Double(0.50), new Double(0.75), new Double(1.00), new Double(1.25), new Double(1.50), new Double(2.00), new Double(3.00), new Double(4.00), new Double(5.00), });
              zoom_combo.setEditable(true);
              zoom_combo.setSelectedIndex(5);
              zoom_combo.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent ae) {
                        child_panel.setZoomFactor(((Double)zoom_combo.getSelectedItem()).doubleValue());
                        revalidate();
                        repaint();
              widget_panel = new JPanel();
              widget_panel.add(zoom_combo);
              add(widget_panel, BorderLayout.NORTH);
              child_panel = child;
              JPanel pan1 = new JPanel(new BorderLayout());
              JPanel pan2 = new JPanel(new BorderLayout());
              pan1.add(pan2, BorderLayout.NORTH);
              pan2.add(child_panel, BorderLayout.WEST);
              add(pan1, BorderLayout.CENTER);
         public JPanel getChild() {
              return child_panel;
         private static class ZoomedPanel extends JPanel {
              private double zoomFactor;
              public ZoomedPanel() {
                   this(true);
              public ZoomedPanel(boolean isDoubleBuffered) {
                   this(new FlowLayout(), isDoubleBuffered);
              public ZoomedPanel(LayoutManager layout) {
                   this(layout, true);
              public ZoomedPanel(LayoutManager layout, boolean isDoubleBuffered) {
                   super(layout, isDoubleBuffered);
                   zoomFactor = 1.0;
              public void setZoomFactor(double aZoomFactor) {
                   zoomFactor = aZoomFactor;
              public void paint(Graphics g) {
                   int w = getWidth();
                   int h = getHeight();
                   BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
                   Graphics2D g2D = (Graphics2D)bi.getGraphics();
                   super.paint(g2D);
                   Rectangle clipBounds = g.getClipBounds();
                   g.setClip(clipBounds.x, clipBounds.y,
                               (int)(clipBounds.width * zoomFactor),
                               (int)(clipBounds.height * zoomFactor));
                   ((Graphics2D)g).drawImage(bi, AffineTransform.getScaleInstance(zoomFactor, zoomFactor), null);
         public static void main(String[] args) {
              final JFrame frame = new JFrame("TestZoomPanel");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              ZoomedPanel insidePanel = new ZoomedPanel(new GridLayout(2, 2));
              insidePanel.add(new JButton("totot"));
              insidePanel.add(new JLabel("tutututu"));
              insidePanel.add(new JTextArea("qmsdfkqsdmlfkqsd\nqsdfqsdfqsdfkqsdf\nqsdfqsdfqsdf\nqsdfqsdfqsdfqsdf"));
              insidePanel.add(new JTextField("sdqsdfqsdf"));
              ZoomPanel zoomPanel = new ZoomPanel(insidePanel);
              frame.setContentPane(zoomPanel);
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        frame.pack();
                        frame.setVisible(true);
    } // ZoomPanel.javaThis is only to show you how it can be achieved following the approach you were using (that is, override a paint type method).
    However, you have to realize that in no way are the subcomponents scaled according to the zoom value. You should think of a more elaborate solution that would effectively change the size of the subcomponents. They could implement a Scalable interface with a scale(double zoomFactor) method used to modify the size of their font, their preferredSize...

  • Rendering Image in JPanel

    Hi,
    I am completely new to java imaging and I am planning to build a small image viewer application (something similar to the comic book reader).
    After some search and following the discussion here [http://forum.java.sun.com/thread.jspa?forumID=20&threadID=362429|http://forum.java.sun.com/thread.jspa?forumID=20&threadID=362429] , I have main app consists of JFrame with SplitPane which consists a ScrollPane. In separate class, I have JPanel class. I am trying to add the JPanel in ScrollPane when application starts. JPane is responsible for fetching and rendering image but something went wrong and it is giving me a NullPointer Exceptions. So far I was able to figure out that it is causing by the "paintComponent" method but no idea why. I am looking for a nice suggestions and guidance on this topic (especially something like why it didn't work and various ways to do things). "For Dummies" style suggestions are highly appreciated.
    Follwing are my two classes:
    ===============================
    =======================
    Separate JPanel Class
    =======================
    * JPanelCanvas.java
    * Created on July 17, 2008, 4:16 PM
    package org.zeenet.bookreader;
    * @author  Deepak K. Shrestha
    import java.awt.*;
    import java.awt.image.*;
    import javax.imageio.*;
    import java.io.*;
    public class JPanelCanvas extends javax.swing.JPanel {
        BufferedImage prevImg, currImg, nextImg = null;
        Graphics g;
        /** Creates new form JPanelCanvas */
        public JPanelCanvas() {
            initComponents();
            getImage();
            setSize();
            paintComponent(g); //<<<<-- so far this is causing the trouble <<<<
        //fetch image from file
        public void getImage() {
           try {
               currImg = ImageIO.read(new File("D:\\TEMPORARY\\logo.JPG"));
           } catch (IOException e) {
        public void setSize() {
            if (currImg == null) {
                 this.setPreferredSize(new Dimension (100,100));
            } else {
               this.setPreferredSize(new Dimension(currImg.getWidth(null), currImg.getHeight(null)));
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(currImg, 0, 0, null);
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
        private void initComponents() {
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
            this.setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 400, Short.MAX_VALUE)
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 300, Short.MAX_VALUE)
        }// </editor-fold>                       
        // Variables declaration - do not modify                    
        // End of variables declaration                  
    }==========================
    Main application
    ==========================
    * JFrameReader.java
    * Created on July 16, 2008, 3:16 PM
    package org.zeenet.bookreader;
    import javax.swing.*;
    * @author  Deepak K. Shrestha
    public class JFrameReader extends javax.swing.JFrame {
        /** Creates new form JFrameReader */
        public JFrameReader() {
            initComponents();
            setExtendedState(JFrameReader.MAXIMIZED_BOTH); //maximize application
            jScrollPaneCanvas.add(new JPanelCanvas()); //<<<<---attached the JPanel here <<<<<<<<<
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
        private void initComponents() {
            jLayeredPane1 = new javax.swing.JLayeredPane();
            jSplitPane1 = new javax.swing.JSplitPane();
            jScrollPaneCanvas = new javax.swing.JScrollPane();
            jScrollPaneList = new javax.swing.JScrollPane();
            jListItem = new javax.swing.JList();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("zeeBookReader");
            jSplitPane1.setRightComponent(jScrollPaneCanvas);
            jListItem.setModel(new javax.swing.AbstractListModel() {
                String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
                public int getSize() { return strings.length; }
                public Object getElementAt(int i) { return strings; }
    jScrollPaneList.setViewportView(jListItem);
    jSplitPane1.setLeftComponent(jScrollPaneList);
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(jLayeredPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
    .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
    .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 264, Short.MAX_VALUE)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jLayeredPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
    pack();
    }// </editor-fold>
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new JFrameReader().setVisible(true);
    // Variables declaration - do not modify
    private javax.swing.JLayeredPane jLayeredPane1;
    private javax.swing.JList jListItem;
    private javax.swing.JScrollPane jScrollPaneCanvas;
    private javax.swing.JScrollPane jScrollPaneList;
    private javax.swing.JSplitPane jSplitPane1;
    // End of variables declaration
    =======================
    By the way I am using Netbeans and all swing components are created using GUI editor.
    Trying to build this app gives me following error:
    ===========================================
    init:
    deps-jar:
    compile:
    run:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at javax.swing.JComponent.paintComponent(JComponent.java:766)
    at org.zeenet.bookreader.JPanelCanvas.paintComponent(JPanelCanvas.java:54)
    at org.zeenet.bookreader.JPanelCanvas.<init>(JPanelCanvas.java:30)
    at org.zeenet.bookreader.JFrameReader.<init>(JFrameReader.java:22)
    at org.zeenet.bookreader.JFrameReader$2.run(JFrameReader.java:80)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
    BUILD STOPPED (total time: 10 seconds)
    ===============================================
    Thanks

    You should not call paintComponent explicitly (especially with a null Graphics object).
    It is called internally when the component needs to repaint itself.
    Read this: [Performing Custom Painting|http://java.sun.com/docs/books/tutorial/uiswing/painting/]

Maybe you are looking for

  • Passing data from a Table in a Dialog to a Listbox in a Internal Frame

    Hi All, Currently I have 2 .java classes. In the first class, DisplayListBox.java, it would have listboxes in it and a textbox with a button, Find. Upon clicking on the "Find" button, it would create a dialog window and call the second class, TableSe

  • Slideshow in GoLive

    Daverj... Is there a way to add transitions to your actions? Also, for anyone... Is it possible to insert an .exe into GoLive for slideshows? I have a very good program called Pic to .exe and it creates very nice shows. Plus I have Lightroom which al

  • How do i send an efax

    How do I set up the efax for my HP Photosmart 5510 series?  I cannot find the directions anywhere.

  • Group Policy application frequency even if policy hasnt changed - Server 2012 R2

    Hi,   I'm aware of the group policy refresh intervals which apply only if the policy has changed. If I remember correctly, Server 2003 applied policies every 16 hours even if they hadnt changed. A sort of "to be sure, to be sure" setting. Does this e

  • About DOC INVOIC02 and FM IDOC_INPUT_INVOIC_MRM

    Hi; We need to park invoice by IDOC type INVOIC02 and FM IDOC_INPUT_INVOIC_MRM. Is there any way ( maybe user exit/BADI) to save the parked invoice information into a Z* table ? Thanks in advance. Vindy