How to draw a JPanel in an offscreen image

I am still working on painting a JPanel on an offline image
I found the following rules :
- JPanel.setBounds shall be called
- the JPanel does not redraw an offline image, on should explicitly override paint()
to paint the children components
- the Children components do not pain, except if setBounds is called for each of them
Still with these rules I do not master component placement on the screen. Something important is missing. Does somebody know what is the reason for using setBounds ?
sample code :
private static final int width=512;
private static final int height=512;
offScreenJPanel p;
FlowLayout l=new FlowLayout();
JButton b=new JButton("Click");
JLabel t=new JLabel("Hello");
p=new offScreenJPanel();
p.setLayout(l);
p.setPreferredSize(new Dimension(width,height));
p.setMinimumSize(new Dimension(width,height));
p.setMaximumSize(new Dimension(width,height));
p.setBounds(0,0,width,height);
b.setPreferredSize(new Dimension(40,20));
t.setPreferredSize(new Dimension(60,20));
p.add(t);
p.add(b);
image = new java.awt.image.BufferedImage(width, height,
java.awt.image.BufferedImage.
TYPE_INT_RGB);
Graphics2D g= image.createGraphics();
// later on
p.paint(g);
paint method of offScreenPanel :
public class offScreenJPanel extends JPanel {
public void paint(Graphics g) {
super.paint(g);
Component[] components = getComponents();
for (int i = 0; i < components.length; i++) {
JComponent comp=(JComponent) components;
comp.setBounds(0,0,512,512);
components[i].paint(g);

Unfortunately using pack doesn't work, or I didn't use it the right way.
I made a test case, eliminated anything not related to the problem (Java3D, applet ...). In the
test case if you go to the line marked "// CHANGE HERE" and uncomment the jf.show(), you have
an image generated in c:\tmp under the name image1.png with the window contents okay.
If you replace show by pack you get a black image. It seems there still something.
simplified sample code :[b]
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import com.sun.j3d.utils.applet.*;
import com.sun.j3d.utils.image.*;
import com.sun.j3d.utils.universe.*;
import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
public class test {
private static final int width=512;
private static final int height=512;
public test() {
JPanel p;
BorderLayout lay=new BorderLayout();
java.awt.image.BufferedImage image;
// add a JPanel with a label and a button
p=new JPanel(lay);
p.setPreferredSize(new Dimension(width,height));
JLabel t=new JLabel("Hello");
t.setPreferredSize(new Dimension(60,20));
p.add(t,BorderLayout.NORTH);
p.setDebugGraphicsOptions(DebugGraphics.LOG_OPTION );
// show the panel for debug
JFrame jf=new JFrame();
jf.setSize(new Dimension(width,height));
jf.getContentPane().add(p);
[b]
// CHANGE HERE->
jf.pack();
//jf.show();
// create an off screen image
image = new java.awt.image.BufferedImage(width, height,
java.awt.image.BufferedImage.TYPE_INT_RGB);
// paint JPanel on off screen image
Graphics2D g= image.createGraphics();
g.setClip(jf.getBounds());
System.err.println("BEFORE PAINT");
jf.paint(g);
System.err.println("AFTER PAINT");
// write the offscreen image on disk for debug purposes
File outputFile = new File("c:\\tmp\\image1.png");
try {
ImageIO.write(image, "PNG", outputFile);
} catch (Exception e) {
System.err.println(e.getMessage());
g.dispose();
jf.dispose();
public static void main(String[] args) {
test t=new test();
}

Similar Messages

  • How to tint a JPanel that paints an Image

    Hello all,
    I have a basic understanding of Java Swing architecture and the Drawing capabilities of the Graphics and Graphics2D classes. However, i am utterly confused how to implement a basic tint over an image.
    Overview:
    I have a GCard (Graphical Card) class that extends JPanel. This class contains a BufferedImage so that when the GCard is added to a higher-level Container, it paints the BufferedImage. What I want to do is tint that card image to a user specified color (let's say RED) via the GCard.setTint(Color.RED) method and then allow them to control if the tint is on/off via the GCard.setTinted(true) method.
    What I have:
    Currently, I have the following in my GCard.paintComponent(Graphics g) method:
         @Override
         protected void paintComponent(Graphics g) {
              int xPosition = 0;
              int yPosition = 0;
              if(image != null) {
                   g.drawImage(image, xPosition, yPosition, null);
                   if(isTinted() && tint != null) {
                        g.setColor(tint);
                        for(int x = xPosition; x < (xPosition + image.getWidth()); x += 2)
                             for(int y = yPosition; y < (yPosition + image.getHeight()); y += 2)
                                  g.drawLine(x, y, x, y);
         }All this does is implement a rudimentary tinting scheme by setting every other pixel in the panel to the tint color.
    What I want:
    What I'd like to see instead is a red haze over the entirety of the image. Much like the multiple item selection process that occurs when you select multiple things in a modern-day OS.
    How can i do this?
    From what I've read/thought out, I can either edit the actual image data to increase the level of the appropriate tint color, but I would prefer to be non-destructive to the image I'm holding in memory. I would prefer to imitate the 'layer' functionality of Adobe Photoshop where my image is the 'background' and I have a transparent panel that is tinted which can be switched on and off. Can I accomplish all of this in the paintComponent() method or will i need to add a JPanel (let's call it a tintPanel)to the GCard object and then add/remove that component from the GCard as necessary?
    Thanks for the help!
    -Pheez

    Something likeprotected void paintComponent(Graphics g) {
       super.paintComponent(g);
       g.drawImage(....);
       g.setColor(new Color(r, g, b, a)); // where a <1.0
       g.fillRect(aRectThatOverlapsTheImage);
    }db

  • Drawing a font on an offscreen image

    I'm trying to draw a font on my own offscreen image but I had to implement a few tweaks to get it to work and I would like to know how to do it properly. Here's my code:
      private int[] getPrintMetrics(Font fnt, String txt) {
        BufferedImage bi = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
        Graphics2D bg = (Graphics2D)bi.getGraphics();
        FontRenderContext frc = bg.getFontRenderContext();
        TextLayout tl = new TextLayout(txt, fnt, frc);
        int ret[] = new int[2];
        ret[0] = (int)tl.getBounds().getWidth();
        ret[1] = (int)(tl.getBounds().getHeight() * 1.5);
    //    ret[0] = (int)tl.getPixelBounds(frc, 0, 0).getWidth();
    //    ret[1] = (int)(tl.getPixelBounds(frc, 0, 0).getHeight() * 1.5);
        //BUG! WHY IS HEIGHT TOO SMALL? I HAVE TO ADD 50%
        return ret;
      public void print(Font fnt, int x, int y, String txt, int clr) {
        int size[] = getPrintMetrics(fnt, txt);
        BufferedImage bi = new BufferedImage(size[0], size[1], BufferedImage.TYPE_INT_RGB);
        Graphics2D bg = (Graphics2D)bi.getGraphics();
        FontRenderContext frc = bg.getFontRenderContext();
        TextLayout tl = new TextLayout(txt, fnt, frc);
        //this method draws the outline only
        Shape shape = tl.getOutline(AffineTransform.getTranslateInstance(0, tl.getBounds().getHeight()));
        bg.setColor(new Color(clr));
        bg.draw(shape);
        bg.setColor(new Color(clr));
        bg.setFont(fnt);
        bg.drawString(txt, 0, -1 * tl.getBaselineOffsets()[tl.getBaseline()+2]);   //BUG! HOW DO I KNOW WHICH BASELINE TO USE?
        putPixels(bi.getRGB(0,0,size[0],size[1],null,0,size[0]), x, y, size[0], size[1], 0);
      }putPixels() is my own member that will draw to my own image buffer.
    1) Why must I multiply the height by 1.5 in the getPrintMetrics() ?
    2) How do I know which baseline to use (I just hacked it).
    Thanks.

    Why is the height so small?
    new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);The graphics context for this BufferedImage is very small.
    For more size increase the width and height dimensions.
    Try this.
    import java.awt.*;
    import java.awt.font.*;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    public class GraphicsExercise {
        private JLabel getContent() {
            BufferedImage image = createImage();
            Graphics2D g2 = image.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                                RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            g2.setPaint(Color.blue);
            Font font = new Font("dialog", Font.PLAIN, 36);
            g2.setFont(font);
            FontRenderContext frc = g2.getFontRenderContext();
            String s = "Hello World";
            LineMetrics metrics = font.getLineMetrics(s, frc);
            float height = metrics.getAscent() + metrics.getDescent();
            float width = (float)font.getStringBounds(s, frc).getWidth();
            float x = (image.getWidth() - width)/2f;
            float y = (image.getHeight() + height)/2 - metrics.getDescent();
            g2.drawString(s, x, y);
            g2.dispose();
            return new JLabel(new ImageIcon(image), JLabel.CENTER);
        private BufferedImage createImage() {
            int w = 240;
            int h = 165;
            int type = BufferedImage.TYPE_INT_RGB;
            BufferedImage image = new BufferedImage(w, h, type);
            Graphics2D g2 = image.createGraphics();
            g2.setBackground(UIManager.getColor("Panel.background"));
            g2.clearRect(0,0,w,h);
            g2.dispose();
            return image;
        public static void main(String[] args) {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new GraphicsExercise().getContent());
            f.pack();
            f.setLocation(200,200);
            f.setVisible(true);
    }

  • Setting a jpanel as a background image

    i have managed to load the image into a jpanel but now need to know how to set the jpanel as a background image, to allow my jbuttons and textfields to be seen over the top

    that statement is unbeleivably true.
    right, heres my two classes, the first class is where i created the image
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.* ;
    import java.io.*;
    import javax.imageio.*;
    public class EmailBackgroundImage extends JComponent
    public void paint (Graphics g)
    File bkgdimage = new File ("background.jpg");
    Image imagebg = createImage ( 250,300 );
    try {
    imagebg = ImageIO.read(bkgdimage);
    catch (IOException e)
    g.drawImage(imagebg, 0, 0,null,null);
    this next class is where i'm trying to make the background
    youll notice remnants of my current attempt to create the background image.
    in its current state it does compile
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.* ;
    import java.sql.*;
    import java.util.*;
    import java.awt.color.*;
    public class emailFrontpage extends JFrame implements ActionListener
    JLabel FirstNameLabel = new JLabel("First Name");
    JLabel LastNameLabel = new JLabel("Last Name");
    JLabel EmailLabel = new JLabel("Email Address");
    JTextField FirstNameText = new JTextField( 10 );
    JTextField LastNameText = new JTextField( 10 );
    JTextField EmailAddressText = new JTextField( 20 );
    JPanel panel1 = new JPanel();
    JPanel panel2 = new JPanel();
    JPanel panel3 = new JPanel();
    JPanel panel4 = new JPanel();
    JPanel panel5 = new JPanel();
    JPanel image = new JPanel();
    JButton Enterbutton = new JButton("Enter Details");
    JButton Logon = new JButton("Log on");
    EmailBackgroundImage myimage;
    EmailEdit editEmp;
    emailFrontpage()
    getContentPane().setLayout( new BoxLayout( getContentPane(), BoxLayout.Y_AXIS ));
    myimage = new EmailBackgroundImage();
    image.add(myimage);
    myimage.setSize(250,300);
    image.setOpaque( false );
    FirstNameLabel.setForeground(Color.WHITE);
    LastNameLabel.setForeground(Color.WHITE);
    EmailLabel.setForeground(Color.WHITE);
    panel1.add(Logon);
    panel2.add(FirstNameLabel); panel2.add(FirstNameText);
    panel3.add(LastNameLabel); panel3.add(LastNameText);
    panel4.add(EmailLabel); panel4.add(EmailAddressText);
    panel5.add(Enterbutton);
    getContentPane().add(image);
    getContentPane().add(panel1);
    getContentPane().add(panel2);
    getContentPane().add(panel3);
    getContentPane().add(panel4);
    getContentPane().add(panel5);
    // .setBackground( Color.black )
    Enterbutton.addActionListener( this );
    Logon.addActionListener( this );
    Enterbutton.setActionCommand( "ENTERBUTTONPRESSED" );
    Logon.setActionCommand( "LOGONBUTTONPRESSED" );
    setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE );
    editEmp = new EmailEdit();
    public void actionPerformed( ActionEvent evt)
    if ( evt.getActionCommand().equals("LOGONBUTTONPRESSED") )
    emailLogonpage emaillogon = new emailLogonpage();
    emaillogon.setSize( 250, 300 );
    emaillogon.setVisible( true );
    emaillogon.setResizable(false);
    setVisible(false);
    else
    String newFN = FirstNameText.getText();
    String newLN = LastNameText.getText();
    String newEA = EmailAddressText.getText();
    editEmp.addNewEmail(newFN, newLN, newEA);
    setVisible(false);
    emailFrontpage emailfront = new emailFrontpage();
    emailfront.setSize( 250, 300 );
    emailfront.setVisible( true );
    emailfront.setResizable(false);
    public static void main ( String[] args )
    emailFrontpage emailfront = new emailFrontpage();
    emailfront.setSize( 250, 300 );
    emailfront.setVisible( true );
    emailfront.setResizable(false);
    }

  • How do i draw on JPanel?

    Hi all,
    Is it possible to draw inside swing JPanel? If so, how to draw, say, a rectangle inside a JPanel? Thanks a bunch!
    mp

    JPanel, is a generic light weight component. By Default, they dont paint any thing except for the background, you can easily add borders and customise their painting.

  • How to draw in a JPanel and refresh it?

    Hey guys,
    i want to draw a map, consisting of a lot of colored rectangles, in a JPanel.
    it is part of project i am working on. a robot is discovering a track and i want to draw this track step by step, the informations are sent via bluetooth.
    i am not sure how to draw it step by step and how to refresh it?
    i am able to draw a static graphic with the abstract class Graphics and the method paintComponent of the class JPanel.
    How do I add one or more rectangles to the existing graphic?
    thanks for your help!

    i would like to realize the standard approach.
    but i am not quite sure how.
    i tried to realize it like this, but there is an error, if the i uncomment the two lines and i do not understand why!
    import java.awt.image.*;
    import java.awt.*;
    import javax.swing.*;
    public class TrackWindow extends JFrame {   
         public TrackWindow() {
              super("Mapping");
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              this.setAlwaysOnTop(true);
              this.setLocationByPlatform(true);
              this.setSize(500, 500);
              this.add(new TrackPanel());
              this.setVisible(true);
         public static void main(String[] args) {
              new TrackWindow();
         public class TrackPanel extends JPanel {
              public BufferedImage track = null;
              public TrackPanel() {
                   track = (BufferedImage)this.createImage(200, 200);
                   //Graphics2D g2 = track.createGraphics();
                   //g2.fillRect(0, 0, 15, 15);
              public void paintComponent(Graphics g) {
    }could you please help me a little.
    Thank you!

  • How to draw text vertically, or in an angle

    please help me how to draw text vertically, or in an angle

    I robbed the framework from Dr Las or 74phillip (don't remember which) ...
    import java.awt.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class AngleText extends JPanel {
      private int      degrees = 16;
      private JSpinner degreesSpinner;
      public AngleText () {
        setBackground ( Color.WHITE );
      }  // AngleText constructor
      protected void paintComponent ( Graphics _g ) {
        super.paintComponent ( _g );
        Graphics2D g = (Graphics2D)_g;
        g.setRenderingHint ( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
        AffineTransform at = AffineTransform.getRotateInstance ( Math.toRadians ( degrees ) );
        Font f =  g.getFont();
        g.setFont ( f.deriveFont ( at ) );
        g.drawString ( "Rotating Text!", getWidth()/2, getHeight()/2 );
        g.setRenderingHint ( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
      }  // paintComponent
      public JPanel getUIPanel () {
        SpinnerModel degreesModel = new SpinnerNumberModel (
                                      degrees  // initial
                                     ,0        // min
                                     ,360      // max
                                     ,2        // step
        degreesSpinner = new JSpinner ( degreesModel );
        degreesSpinner.addChangeListener ( new DegreesTracker() );
        JPanel panel = new JPanel();
        panel.add ( degreesSpinner );
        return panel;
      }  // getUIPanel
      //  DegreesTracker
      private class DegreesTracker implements ChangeListener {
        public void stateChanged ( ChangeEvent e ) {
          Integer i = (Integer)((JSpinner)e.getSource()).getValue();
          degrees   = i.intValue ();
          repaint();
      }  // DegreesTracker
      //  main
      public static void main ( String[] args ) {
        JFrame f = new JFrame ( "AngleText" );
        f.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
        AngleText app = new AngleText();
        f.getContentPane().add ( app );
        f.getContentPane().add ( app.getUIPanel(), BorderLayout.SOUTH );
        f.setSize ( 200, 200 );
        f.setVisible ( true );
      }  // main
    }  // AngleText

  • How to draw 2D shapes on the image generated by JMF MediaPlayer?

    Hello all:
    IS there any way that we can draw 2D shapes on the image generated by JMF
    MediaPlayer?
    I am currently working on a project which should draw 2D shapes(rectangle, circle etc) to
    mark the interesting part of image generated by JMF MediaPlayer.
    The software is supposed to work as follows:
    1> first use will open a mpg file and use JMF MediaPlayer to play this video
    2> if the user finds some interesting image on the video, he will pause the video
    and draw a circle to mark the interesting part on that image.
    I know how to draw a 2D shapes on JPanel, however, I have no idea how I can
    draw them on the Mediaplayer Screen.
    What technique I should learn to implement this software?
    any comments are welcome.
    thank you
    -Daniel

    If anyone can help?!
    thank you
    -Daniel

  • How to draw a line(shortest distance)  between two ellipse using SWING

    how to draw a line(should be shortest distance) between two ellipse using SWING
    any help will be appreciated
    regards

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import javax.swing.event.MouseInputAdapter;
    public class ELine extends JPanel {
        Ellipse2D.Double red = new Ellipse2D.Double(150,110,75,165);
        Ellipse2D.Double blue = new Ellipse2D.Double(150,50,100,50);
        Line2D.Double line = new Line2D.Double();
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setPaint(Color.green.darker());
            g2.draw(line);
            g2.setPaint(Color.blue);
            g2.draw(blue);
            g2.setPaint(Color.red);
            g2.draw(red);
        private void connect() {
            double flatness = 0.01;
            PathIterator pit = blue.getPathIterator(null, flatness);
            double[] coords = new double[2];
            double x1 = 0, y1 = 0, x2 = 0, y2 = 0;
            double min = Double.MAX_VALUE;
            while(!pit.isDone()) {
                int type = pit.currentSegment(coords);
                switch(type) {
                    case PathIterator.SEG_MOVETO:
                    case PathIterator.SEG_LINETO:
                        Point2D.Double p = getClosestPoint(coords[0], coords[1]);
                        double dist = p.distance(coords[0], coords[1]);
                        if(dist < min) {
                            min = dist;
                            x1 = coords[0];
                            y1 = coords[1];
                            x2 = p.x;
                            y2 = p.y;
                        break;
                    case PathIterator.SEG_CLOSE:
                        break;
                    default:
                        System.out.println("blue type: " + type);
                pit.next();
            line.setLine(x1, y1, x2, y2);
        private Point2D.Double getClosestPoint(double x, double y) {
            double flatness = 0.01;
            PathIterator pit = red.getPathIterator(null, flatness);
            double[] coords = new double[2];
            Point2D.Double p = new Point2D.Double();
            double min = Double.MAX_VALUE;
            while(!pit.isDone()) {
                int type = pit.currentSegment(coords);
                switch(type) {
                    case PathIterator.SEG_MOVETO:
                    case PathIterator.SEG_LINETO:
                        double dist = Point2D.distance(x, y, coords[0], coords[1]);
                        if(dist < min) {
                            min = dist;
                            p.setLocation(coords[0], coords[1]);
                        break;
                    case PathIterator.SEG_CLOSE:
                        break;
                    default:
                        System.out.println("red type: " + type);
                pit.next();
            return p;
        public static void main(String[] args) {
            final ELine test = new ELine();
            test.addMouseListener(test.mia);
            test.addMouseMotionListener(test.mia);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(test);
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    Graphics g = test.getGraphics();
                    g.drawString("drag me", 175, 80);
                    g.dispose();
        private MouseInputAdapter mia = new MouseInputAdapter() {
            Point2D.Double offset = new Point2D.Double();
            boolean dragging = false;
            public void mousePressed(MouseEvent e) {
                Point p = e.getPoint();
                if(blue.contains(p)) {
                    offset.x = p.x - blue.x;
                    offset.y = p.y - blue.y;
                    dragging = true;
            public void mouseReleased(MouseEvent e) {
                dragging = false;
            public void mouseDragged(MouseEvent e) {
                if(dragging) {
                    double x = e.getX() - offset.x;
                    double y = e.getY() - offset.y;
                    blue.setFrame(x, y, blue.width, blue.height);
                    connect();
                    repaint();
    }

  • How to draw rectanlge in the panel, clear, repaint?

    when i was taking my coding, i found a problem which i could not solve.So, i hope someone can help. Thank you.
    the question :
    1. how to draw Rectangle in the Panel?
    2. how to clear?
    3. how to repaint?
    The following is my coding.
    import javax.swing.*;
    import java.awt.*;
    public class DrawScreen extends JFrame {
    Color rectColor=Color.white;
    int hight=100;
    Panel Button_panel = new Panel();
    Button button1 = new Button();
    Button button2 = new Button();
    Button button3 = new Button();
    Panel Draw_Panel = new Panel();
    public DrawScreen(String title) {
         super(title);
         try {
         Init();
         catch(Exception e) {
         e.printStackTrace();
    private void Init() throws Exception {
    setResizable(false);
    setFont(new Font("Serif",Font.ITALIC,12));
         this.getContentPane().setLayout(null);
         Button_panel.setBackground(SystemColor.control);
         Button_panel.setLocale(java.util.Locale.getDefault());
         Button_panel.setBounds(new Rectangle(14, 17, 118, 259));
         Button_panel.setLayout(null);
         button1.setLabel("Draw Square");
         button1.setBounds(new Rectangle(0, 69, 115, 22));
         button2.setLabel("Colour Red");
         button2.setBounds(new Rectangle(0, 111, 115, 22));
         button3.setLabel("Clear Screen");
         button3.setBounds(new Rectangle(2, 152, 115, 22));
         Draw_Panel.setBackground(Color.white);
         Draw_Panel.setBounds(new Rectangle(138, 15, 254, 266));
    //     System.out.println(Draw_Panel.getBounds());
         this.getContentPane().setBackground(Color.white);
         this.getContentPane().add(Button_panel, "East");
         Button_panel.add(button3, null);
         Button_panel.add(button2, null);
         Button_panel.add(button1, null);
         this.getContentPane().add(Draw_Panel, "West");
         addWindowListener(new java.awt.event.WindowAdapter(){
              public void windowClosing(java.awt.event.WindowEvent e){
                   System.exit(0);
    button1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    button1ActionPerformed(evt);
    button2.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    button2ActionPerformed(evt);
    button3.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    button3ActionPerformed(evt);
    pack();
    private void button1ActionPerformed(java.awt.event.ActionEvent evt) {
         hight=(int)(Math.random()*100);
         rectColor=Color.black;
    repaint();
    private void button2ActionPerformed(java.awt.event.ActionEvent evt) {
         rectColor=Color.red;
    repaint();
    private void button3ActionPerformed(java.awt.event.ActionEvent evt) {
    rectColor=Color.white;
    repaint();
    public void paint(Graphics g){
         g.setColor(rectColor);
         g.drawRect(50, 50,hight,hight);
    public static void main(String[] args) {
    DrawScreen ds=new DrawScreen("Square Plotter");
         ds.setSize(600,350);
         ds.setVisible(true);

    Few changes and it works:
    import javax.swing.*;
    import java.awt.*;
    public class DrawScreen extends JFrame
         Color  rectColor    = Color.white;
         int    hight        = 100;
         Panel  Button_panel = new Panel();
         Button button1      = new Button();
         Button button2      = new Button();
         Button button3      = new Button();
         DPanel Draw_Panel   = new DPanel();
    public DrawScreen(String title)
         super(title);
         setResizable(false);
    //     setFont(new Font("Serif",Font.ITALIC,12));
    //     this.getContentPane().setLayout(null);
         Button_panel.setBackground(SystemColor.control);
         Button_panel.setLocale(java.util.Locale.getDefault());
         Button_panel.setBounds(new Rectangle(14, 17, 118, 259));
         Button_panel.setLayout(null);
         button1.setLabel("Draw Square");
         button1.setBounds(new Rectangle(0, 69, 115, 22));
         button2.setLabel("Colour Red");
         button2.setBounds(new Rectangle(0, 111, 115, 22));
         button3.setLabel("Clear Screen");
         button3.setBounds(new Rectangle(2, 152, 115, 22));
         Draw_Panel.setBackground(Color.white);
         Draw_Panel.setBounds(new Rectangle(138, 15, 254, 266));
    //  System.out.println(Draw_Panel.getBounds());
    //     this.getContentPane().setBackground(Color.white);
         this.getContentPane().add(Button_panel, "East");
         Button_panel.add(button3);
         Button_panel.add(button2);
         Button_panel.add(button1);
         this.getContentPane().add(Draw_Panel, "Center");
         addWindowListener(new java.awt.event.WindowAdapter()
              public void windowClosing(java.awt.event.WindowEvent e)
                   System.exit(0);
         button1.addActionListener(new java.awt.event.ActionListener()
              public void actionPerformed(java.awt.event.ActionEvent evt)
                   button1ActionPerformed(evt);
         button2.addActionListener(new java.awt.event.ActionListener()
              public void actionPerformed(java.awt.event.ActionEvent evt)
              button2ActionPerformed(evt);
         button3.addActionListener(new java.awt.event.ActionListener()
              public void actionPerformed(java.awt.event.ActionEvent evt)
                   button3ActionPerformed(evt);
    //     pack();
    private void button1ActionPerformed(java.awt.event.ActionEvent evt)
         hight=(int)(Math.random()*100);
         rectColor=Color.black;
         repaint();
    private void button2ActionPerformed(java.awt.event.ActionEvent evt)
         rectColor=Color.red;
         repaint();
    private void button3ActionPerformed(java.awt.event.ActionEvent evt)
         rectColor=Color.white;
         repaint();
    public class DPanel extends JPanel
    public DPanel()
    public void paintComponent(Graphics g)
         super.paintComponent(g);
         g.setColor(rectColor);
         g.drawRect(50, 50,hight,hight);
    public static void main(String[] args)
         DrawScreen ds=new DrawScreen("Square Plotter");
         ds.setSize(600,350);
         ds.setVisible(true);
    }Noah

  • How to draw image in different dpi?

    I wonder is there any approach can be used to draw a image in different dpi, such as 144dpi, in a JPanel?
    'cause my image processed from other tools is not good, if I can draw image in a high dpi, then the image will looks much better, though the image becomes smaller.
    Note: no SCALE!

    I have a image which is 152dpi, then, how does the Widows draws this image? It looks much better than scale the 72dpi image to the same size.
    Really puzzled-_-                                                                                                                                                                                                                                                                                                                               

  • Resize of Drawing in JPanel

    Hi,
    I am looking for some ideas on how to resize a drawing in JPanel.
    I wanted to increase its width and height at run time by dragging its end points (any direction).
    One more thing is how do I add text to the drawing at run time? Is this possible?
    My idea is to develop an application similar to MS-Word where we can add few drawings and add text to them.
    Any help would be great.
    Mathew

    The drawing code has to be written in ratios. Don't draw from x1, y1, to x2, y2 -- draw from (left + .3*width, top + .3 * height) to . . . Then the drag gesture should give you new width and height values, and you can just repaint().

  • How to make a JPanel selectable

    When extending a JPanel and overriding the paintComponent() method the custom JPanel can not be selected so that it gets for example KeyEvents.
    But if I make the new Class extend a JButton it gets of course selected and able to receive for example KeyEvents.
    My question is therefore; what does the JButton implement that a JPanel doesn&#8217;t so that a JButton gets selectable? Or in other words; how to make a JPanel selectable?
    Aleksander.

    Try this extended code. Only the first panel added can get the Focus.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class Test extends JFrame
      public Test()
        setLocation(400,300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        JPanel panel1 = new JPanel(new BorderLayout());
        JPanel panel2 = new JPanel(new BorderLayout());
        ImagePanel imgPanel = new ImagePanel();
        panel1.setFocusable(true);
        panel2.setFocusable(true);
        panel1.setPreferredSize(new Dimension(0, 50));
        panel2.setPreferredSize(new Dimension(0, 50));
        panel1.setBorder(BorderFactory.createLineBorder(Color.RED,     4));
        panel2.setBorder(BorderFactory.createLineBorder(Color.CYAN,    4));
        imgPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 4));
        panel1.add(new JLabel("Panel 1"), BorderLayout.CENTER);
        panel2.add(new JLabel("Panel 2"), BorderLayout.CENTER);
        getContentPane().add(panel1, BorderLayout.NORTH);
        getContentPane().add(panel2, BorderLayout.SOUTH);
        getContentPane().add(imgPanel, BorderLayout.CENTER);   
        pack();
        panel1.addKeyListener(new KeyAdapter(){
            public void keyPressed(KeyEvent ke){
                System.out.println("Panel1");}});
        panel2.addKeyListener(new KeyAdapter(){
            public void keyPressed(KeyEvent ke){
                System.out.println("Panel2");}});
      public static void main(String[] args){new Test().setVisible(true);}
    class ImagePanel extends JPanel
      Image img;
      public ImagePanel()
        setFocusable(true);
        setPreferredSize(new Dimension(400,300));
        try{img = javax.imageio.ImageIO.read(new java.net.URL(getClass().getResource("Test.gif"), "Test.gif"));}
        catch(Exception e){/*handled in paintComponent()*/}
        addKeyListener(new KeyAdapter(){
          public void keyPressed(KeyEvent ke){
            System.out.println("ImagePanel");}});
      public void paintComponent(Graphics g)
        if(img != null)
          g.drawImage(img, 0,0,this.getWidth(),this.getHeight(),this);
        else
          g.drawString("This space for rent",50,50);
    }

  • How to draw horizontal line in smartform after end of the all line items

    Hi Friends,
    I am working on the smartform. I have created TABLE node in Main window.
    i want to draw a horizontal line after end of the main window table node. i mean after printing all the line items of the table, I need to print one horizontal line.
    Could you please help me how to resolve this issue.
    FYI: I tried with the below two options. But no use.
    1. desinged footer area in the table node of the main window.
    2. tried with uline and system symbols.
    please correct me if i am wrong. please explain in detail how to draw horizontal line after end of the main window table.
    this is very urgent.
    Thanks in advance
    Regards
    Raghu

    Hello Valter Oliveira,
    Thanks for your answer. But I need some more detail about blank line text. i.e thrid point.
    Could you please tell me how to insert blank line text.
    1 - in your table, create a line type with only one column, with the same width of the table
    2 - in table painter, create a line under the line type
    3 - insert a blank line text in the footer section with the line type you have created.

  • How to draw vertical lines in SMART FORMS

    Hi Guys,
    Can anyone please let me know how to draw vertical and horizontal lines in smart forms, i have to do this in the secondary window.
    thanks,
    Ramesh

    Hi Ramesh,
    In the window output options you have option of check box to get lines.
    Then you need to give the spacing for vertical and horizontal.
    Another option is putting a template on window and getting the boxes, but it is quite little bit complex.
    Put the cursor on the WINDOW in which the lines you want.
    Right click on it>create>complex section.
    In that select the TEMPLATE radio button.
    Goto TAB TEMPLATE.
    Name: give some name of line.
    From: From coloumn.
    To: To coloumn
    Height: specify the height of the line.
    Next give the coloumn widths.
    Like this you can draw the vertical and horzontal lines.
    If the above option doesnot workout then u can try the below option also
    any how you can draw vertical and horizontal lines using Template and Table.
    for Template First define the Line and divide that into coloumns and goto select patterns and select the required pattern to get the vertical and horizontal lines.
    For table, you have to divide the total width of the table into required no.of columns and assign the select pattern to get the vertical and horizontal lines.
    if this helps, reward with points.
    Regards,
    Naveen

Maybe you are looking for

  • DBCA hangs in solaris

    when I start dbca in solaris 10, the command just hangs there, nothing happens. what is wrong with this? I have set up the DISPLAY VARIABLE $DISPLAY=myipaddress:0.0 $export DISPLAY $echo $DISPLAY myipaddress:0.0 Thank you.

  • Important question about my code

    Okay so here's the deal, I have been working on creating the 6/49 lottery game and so far everything works fine, however I have one problem with how the program runs. The instructions are as follows: The program generates 6 random numbers from 1 to 4

  • Chinese Word List Update 1.7: Please help me update it manually

    Apple has released Chinese Word list update on June 7, 2013. This is a small 118 KB update that normally will update itself automatically without any ability for user to control the update.Normally, it will be updated in the backgroud in 7-8 days aft

  • ERROR :SCRIPT7002: XMLHttpRequest: Network Error 0x2efd, Could not complete the operation due to error 00002efd. File: default.html

    Hi ,all I am beginner for windows 8 app development. I created simple project on domain name called www.aaa.com and also hosted web services on same domain. at that time i was able to access web services on my application code using AJAX. Then i crea

  • Existing menu underneath spry tabbed panel

    I have an existing css based nav menu.  Now I have added a tabbed panel on the page.  All looks good, until I browse the nav menu in IE7.  The dropdowns hide behing the tabbed panel tabs (but not the tabbed panel content).  Is this a known issue, I t