Draw geotiff in a JFrame

Hi: However I found that some geotiff image can be displayed in a JFrame,however others can not.
The core codes:
  PlanarImage resultImage = null;
  InputStream is = null;
  try {
   is = new FileInputStream(new File("D:/wu.tif"));
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  SeekableStream seekableStream = SeekableStream.wrapInputStream(is, true);
  ParameterBlock pb = new ParameterBlock();
  pb.add(seekableStream);
  resultImage = JAI.create("TIFF", pb);
  JFrame jf=new JFrame("Geo");
  jf.setSize(800,600);
  jf.setVisible(true);
  Graphics g=jf.getGraphics();
  g.drawImage(resultImage.getAsBufferedImage(), 0, 0, null);-----------------------
The two geotiff, usa.tiff and wu.tif, the wu.tif can not drawed in the JFrame, it is a black blank.
I wonder why?
The files can be found there :
[usa.tiff|http://www.mofile.com/pickup/uziiaq7x4zr6fnm/]
[wu.tif|http://www.mofile.com/pickup/5uvoybjury2fxkn/]
I hope someone can check it for me ,thanks.

Maxideon wrote:
The image files that your links prompt me to download have an exe extension? I'm not about to download them to find out what the deal is.No,the extension of the first is .tiff, and the second is tif, how can they become to exe?
Well, is there a safe way to share the image?

Similar Messages

  • Drawing a picture within JFrame when I've already created a JFrame

    Hi everyone,
    I was wondering if you could help me out with this problem I'm getting. I'm creating a program to simulate an 'elevator.' When first creating the project I created a brand new 'Java GUI Form' : 'JFrame Form'. From here I went on to drag-and-drop various command buttons and labels to create the user interface (the 'inside' of an elevator). Here is where my question comes in. On the very left of my interface I want to have the program draw a simulation of a box (the elevator) moving up and down with the 'floor numbers' the user pushes. However i don't know how to access the coding of the jFrame object that I created through the design editor so i can input the coding.
    First Question: What do i have to 'write' that would force that box to print into the current JFrame?
    Second Question: What Code (and where do i put it) essentially 'locks' the JFrame from being resized?

    Here, maybe by putting this it might help you recognize what i'm trying to say. The code i'm trying to put in is:
    JFrame window = new JFrame ("Drawing");
            window.setBounds(200,200,700,500);
            window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            window.setVisible(true);
            Container contentPane = window.getContentPane();
            contentPane.setBackground(new Color(125, 125, 125));
            Graphics g = contentPane.getGraphics();* This is a portion of the code
    When run, this program creates a NEW JFRAME WINDOWS, i'm trying to make it run inside an already existing JFrame, whose variable Name i dont know how to find.

  • Draw a circle on a jFrame

    Hi! How can i draw a circle over a jFrame?

    In general trying to draw directly on a JFrame is not a good idea and can be problematic. You should think about doing your drawing in a JPanel and adding that to the frame
    Here are a number of things to look at in drawing a circle
    Graphics.drawOval(...)
    Ellipse2D, Ellipse2D.Double
    Area - you can create an area from any Shape, and it offers a lot of advantages to dealing with Shape
    Graphics2D.draw/fill(Shape)

  • What to draw on in fullscreen

    I am writing a fullscreen exclusive game (this is my first) which will also be able to switch to a windowed mode, and I want to make sure I have everything set up correctly. Here is the plan: I am going to to my drawing in some kind of draw() method in the class where my main game loop is located, then I will will do the rendering in a render() method located in the class where all my full screen stuff is set up. My first question is what component should I draw on? can I draw directly onto the JFrame and will that be supported in windowed mode? is there some component: Canvas, JPanel, etc. that is better suited for full screen apps?

    My first question is what component should I draw on?Using BufferStrategy, you can draw on either a Frame (or any of its subclasses) or a Canvas.
    can I draw directly onto the JFrame and will that be supported in windowed mode?yup.
    is there some component: Canvas, JPanel, etc. that is better suited for full screen apps?BufferStrategy can be used with Canvas - however some ppl find it to be buggy.
    Frame is also buggy, but less so.
    A word of warning, switching between windowed and fullscreen is very buggy in 1.4.x. (i.e. its impossible)
    It will hopefully be completely fixed in 1.5.

  • How to make lines I draw as an objects??

    Hi friends:
    I met a problem here, I find a similiar code below, but cannot solve it.
    How to make lines I draw as objects in this application??
    ie the lines I draw will be selectable as other JLabels, can be highlighted, can be deleted etc, just like any other components or object,
    How to do this??
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.Vector;
    import java.lang.reflect.Array;
    import javax.swing.*;
    import javax.swing.event.*;
    public class Drawines
         public static void main(String[] args)
            JFrame f = new JFrame("Draw Lines");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new ConnectionPanel());
            f.setSize(400,300);
            f.setLocation(200,200);
            f.setVisible(true);
    class Drawines extends JPanel
        JLabel                                       label1, label2, label3, label4;
        JLabel[]                       labels;
        JLabel                                       selectedLabel;
        protected              JButton btn            = new JButton("DrawLines");
        protected              JButton btn1           = new JButton("Clear");
        protected              JButton btn2           = new JButton("No Draw");
        protected                      boolean isActivated = false;
        protected           int      stoppoint     = 0;          
        int cx, cy;
        Vector order                     = new Vector();
        Vector order1                     = new Vector();
        Object[] arr                    = null;
        public ConnectionPanel()
            setLayout(null);
            addLabels();
            label1.setBounds( 25,  50, 125, 25);
            label2.setBounds(225,  50, 125, 25);
            label3.setBounds( 25, 175, 125, 25);
            label4.setBounds(225, 175, 125, 25);
            btn.setBounds(10, 5, 100, 25);
            btn1.setBounds(100, 5, 100, 25);
            btn2.setBounds(200, 5, 100, 25);
                add(btn);
             add(btn1);
             add(btn2);
            determineCenterOfComponents();
            ComponentMover mover = new ComponentMover();
             ActionListener lst = new ActionListener() {
                 public void actionPerformed(ActionEvent e) {
                     ComponentMover mover = new ComponentMover();
                           addMouseListener(mover);
                           addMouseMotionListener(mover);
                           isActivated = false;
            ActionListener lst1 = new ActionListener() {
                       public void actionPerformed(ActionEvent e) {
                           isActivated=true;
              btn.addActionListener(lst);
              btn1.addActionListener(lst1);
        public void paintComponent(final Graphics g)
             super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
             Point[] p;
                System.out.println("order.size()"+ order.size());
                System.out.println("order1.size()"+ order1.size());
                     if (!isActivated && order1.size()==0) {
                         for(int i = 0 ; i < order.size()-1; i++) {
                                JLabel l1 = (JLabel)order.elementAt(i);
                               JLabel l2 = (JLabel)order.elementAt(i+1);
                               order1.add(order.elementAt(i));
                               order1.add(order.elementAt(i+1));
                               System.out.println();
                               p = getCenterPoints(l1, l2);
                               g2.setColor(Color.black);
                                            g2.draw(new Line2D.Double(p[0], p[1]));            
                     }else if(!isActivated && order1.size()>0){
                             order=order1;
                         for(int i1 = 0 ; i1 < order.size()-1; i1++) {
                               JLabel l1 = (JLabel)order.elementAt(i1);
                               JLabel l2 = (JLabel)order.elementAt(i1+1);
                               System.out.println();
                               p = getCenterPoints(l1, l2);
                               g2.setColor(Color.red);
                                g2.draw(new Line2D.Double(p[0], p[1]));    
                                System.out.println(" order1.size() = " + order.size());
                     }else {
                          order1 = order;
                         for(int i1 = 0 ; i1 < order1.size()-1; i1++) {
                                    JLabel l1 = (JLabel)order1.elementAt(i1);
                                    JLabel l2 = (JLabel)order1.elementAt(i1+1);
                                    p = getCenterPoints(l1, l2);
                                    g2.setColor(Color.blue);
                                    if (order.elementAt(i1) !=null){
                                         g2.draw(new Line2D.Double(p[0], p[1]));    
        private Point[] getCenterPoints(Component c1, Component c2)
            Point
                p1 = new Point(),
                p2 = new Point();
            Rectangle
                r1 = c1.getBounds(),
                r2 = c2.getBounds();
                 p1.x = r1.x + r1.width/2;
                 p1.y = r1.y + r1.height/2;
                 p2.x = r2.x + r2.width/2;
                 p2.y = r2.y + r2.height/2;
            return new Point[] {p1, p2};
        private void determineCenterOfComponents()
            int
                xMin = Integer.MAX_VALUE,
                yMin = Integer.MAX_VALUE,
                xMax = 0,
                yMax = 0;
            for(int i = 0; i < labels.length; i++)
                Rectangle r = labels.getBounds();
    if(r.x < xMin)
    xMin = r.x;
    if(r.y < yMin)
    yMin = r.y;
    if(r.x + r.width > xMax)
    xMax = r.x + r.width;
    if(r.y + r.height > yMax)
    yMax = r.y + r.height;
    cx = xMin + (xMax - xMin)/2;
    cy = yMin + (yMax - yMin)/2;
    private class ComponentMover extends MouseInputAdapter
    Point offsetP = new Point();
    boolean dragging;
    public void mousePressed(MouseEvent e)
    Point p = e.getPoint();
    for(int i = 0; i < labels.length; i++)
    Rectangle r = labels[i].getBounds();
    if(r.contains(p) && !isActivated )
    selectedLabel = labels[i];
    order.addElement(labels[i]);
    offsetP.x = p.x - r.x;
    offsetP.y = p.y - r.y;
    dragging = true;
    repaint(); //added
    break;
    public void mouseReleased(MouseEvent e)
    dragging = false;
    public void mouseDragged(MouseEvent e)
    if(dragging)
    Rectangle r = selectedLabel.getBounds();
    r.x = e.getX() - offsetP.x;
    r.y = e.getY() - offsetP.y;
    selectedLabel.setBounds(r.x, r.y, r.width, r.height);
    //determineCenterOfComponents();
    repaint();
    private void addLabels()
    label1 = new JLabel("Label 1");
    label2 = new JLabel("Label 2");
    label3 = new JLabel("Label 3");
    label4 = new JLabel("Label 4");
    labels = new JLabel[] {
    label1, label2, label3, label4
    for(int i = 0; i < labels.length; i++)
    labels[i].setHorizontalAlignment(SwingConstants.CENTER);
    labels[i].setBorder(BorderFactory.createEtchedBorder());
    add(labels[i]);
    Thanks in advance.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    2 choice, bundle your app in a jar, or get a native compiler.
    executable jar
    http://java.sun.com/j2se/1.3/docs/guide/jar/jarGuide.html
    http://developer.java.sun.com/developer/qow/archive/21/index.html
    native
    http://gcc.gnu.org/java/
    http://www-106.ibm.com/developerworks/library/j-native.html
    http://icafe.sourceforge.net/
    http://www.towerj.com/
    http://www.xlsoft.com/en/products/development/jet/jetpro.html

  • Drawing Graphs

    Hi,
    Anybody tell me how to draw the Graphs in JFrame. I want to have months 1,...12 on X-axis and Values for each month on Y-axis.
    |
    v |
    a |
    l | .
    u | . .
    e |________.________________
    1 2 3 4 ... 12 month-->
    I do not have any idea how to make 2D graphics in java. Help me with an example so that i can understand very easily and do my work very fast.
    Thanks,

    import java.awt.*;
    import java.awt.font.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class LineGraph
        public static void main(String[] args)
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new GraphPanel());
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    class GraphPanel extends JPanel
        final int
            HPAD = 60,
            VPAD = 40;
        int[] data;
        Font font;
        public GraphPanel()
            data = new int[] {
                120, 190, 211, 75, 30, 290, 182, 65, 85, 120, 100, 101
            font = new Font("lucida sans regular", Font.PLAIN, 16);
            setBackground(Color.white);
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setFont(font);
            FontRenderContext frc = g2.getFontRenderContext();
            int w = getWidth();
            int h = getHeight();
            // scales
            float xInc = (w - HPAD - VPAD) / 11f;
            float yInc = (h - 2*VPAD) / 10f;
            int[] dataVals = getDataVals();
            float yScale = dataVals[2] / 10f;
            // ordinate
            g2.draw(new Line2D.Double(HPAD, VPAD, HPAD, h - VPAD));
            // tic marks
            float x1 = HPAD, y1 = VPAD, x2 = HPAD - 3, y2;
            for(int j = 0; j < 10; j++)
                g2.draw(new Line2D.Double(x1, y1, x2, y1));
                y1 += yInc;
            // labels
            String text; LineMetrics lm;
            float xs, ys, textWidth, height;
            for(int j = 0; j <= 10; j++)
                text = String.valueOf(dataVals[1] - (int)(j * yScale));
                textWidth = (float)font.getStringBounds(text, frc).getWidth();
                lm = font.getLineMetrics(text, frc);
                height = lm.getAscent();
                xs = HPAD - textWidth - 7;
                ys = VPAD + (j * yInc) + height/2;
                g2.drawString(text, xs, ys);
            // abcissa
            g2.draw(new Line2D.Double(HPAD, h - VPAD, w - VPAD, h - VPAD));
            // tic marks
            x1 = HPAD; y1 = h - VPAD; y2 = y1 + 3;
            for(int j = 0; j < 12; j++)
                g2.draw(new Line2D.Double(x1, y1, x1, y2));
                x1 += xInc;
            // labels
            ys = h - VPAD;
            for(int j = 0; j < 12; j++)
                text = String.valueOf(j + 1);
                textWidth = (float)font.getStringBounds(text, frc).getWidth();
                lm = font.getLineMetrics(text, frc);
                height = lm.getHeight();
                xs = HPAD + j * xInc - textWidth/2;
                g2.drawString(text, xs, ys + height);
            // plot data
            x1 = HPAD;
            yScale = (float)(h - 2*VPAD) / dataVals[2];
            for(int j = 0; j < data.length; j++)
                y1 = VPAD + (h - 2*VPAD) - (data[j] - dataVals[0]) * yScale;
                if(j > 0)
                    g2.draw(new Line2D.Double(x1, y1, x2, y2));
                x2 = x1;
                y2 = y1;
                x1 += xInc;
        private int[] getDataVals()
            int max = Integer.MIN_VALUE;
            int min = Integer.MAX_VALUE;
            for(int j = 0; j < data.length; j++)
                if(data[j] < min)
                    min = data[j];
                if(data[j] > max)
                    max = data[j];
            int span = max - min;
            return new int[] { min, max, span };
    }

  • Moving a shape randomly through a JFrame

    I'm trying to make a rectangle move to an arbitrary position when the mouse is clicked. I can't get the mouseClicked method to call the fillRect one. Does anyone know what I should do?
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Graphics;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.util.Random;
    import javax.swing.JApplet;
    import javax.swing.JFrame;
    public class ex4 extends JFrame implements MouseListener {
    Random numGen = new Random();
             Color getRandomColor() {
                return new Color(numGen.nextInt(256), numGen.nextInt(256), numGen.nextInt(256));
    Random generator = new Random();
    int randomIndex = generator.nextInt( 400 );
         private String message = new String ("");
         private Color myColor = Color.WHITE;
         public ex4() {
              setSize(400,400);
              setTitle("ex4");
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              addMouseListener(this);
              setVisible(true);
              this.setBackground(Color.WHITE);
         public void paint(Graphics g) {
              super.paint(g);
              int x = generator.nextInt();
              int y = generator.nextInt();
                 g.setColor(getRandomColor());
              g.fillRect( x, y, x/2, y/2);
         public void mouseClicked(MouseEvent arg0) {
         public void mouseEntered(MouseEvent arg0) {
         public void mouseExited(MouseEvent arg0) {
         public void mousePressed(MouseEvent arg0) {
              // TODO Auto-generated method stub
         public void mouseReleased(MouseEvent arg0) {
              // TODO Auto-generated method stub
          * @param args
         public static void main(String[] args) {
              new ex4();
         public void setMyColor(Color myColor) {
              this.myColor = myColor;
         public Color getMyColor() {
              return myColor;
         

    scheng12 wrote:
    this is an entirely different code than my other thread.and yet yet you're still committing the same error of trying to draw directly to the JFrame and adding a MouseListener directly to the JFrame.

  • Runtime error accessing ArrayList

    These 2 classes are basically the classes from the book developing games in java, without the fullscreen stuff. They are supposed to create an animation. They both compile fine but when I run I get an error message, an no animation, paint() is only called once. Here's the error message:
    Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 4, Size: 4
    at java.util.ArrayList.RangeCheck(ArrayList.java:546)
    at java.util.ArrayList.get(ArrayList.java:321)
    at Animation.getFrame(Animation.java:60)
    at Animation.update(Animation.java:43)
    at AnimationTest1.animationLoop(AnimationTest1.java:58)
    at AnimationTest1.run(AnimationTest1.java:44)
    at AnimationTest1.main(AnimationTest1.java:10)
    I think this means the program is trying to access frame 4 when there is none. Right? I just can't get my brain around this. Any help would be great!
    import java.awt.Image;
    import java.util.ArrayList;
    /*     this class manages a serie of images (frames) and the amount of time to
         display each frame */
    public class Animation {
         private ArrayList frames;
         private int currFrameIndex;
         private long animTime;
         private long totalDuration;
         //creates a new, empty animation, calls start().
         public Animation() {
              frames = new ArrayList();
              totalDuration = 0;
              start();
         //adds an image to the animation, + how long to display the image.
         public synchronized void addFrame(Image image, long duration) {
              totalDuration += duration;
              frames.add(new AnimFrame(image, totalDuration));
         //starts this animation over from the beginning .
         public synchronized void start() {
              animTime = 0;
              currFrameIndex = 0;
         //updates this animations current frame if necessary
         public synchronized void update(long elapsedTime) {
              if (frames.size() >1) {
                   animTime += elapsedTime;
                   if (animTime >= totalDuration) {
                        animTime = animTime % totalDuration;
                        currFrameIndex = 0;
                   while (animTime > getFrame(currFrameIndex).endTime) {
                        currFrameIndex ++;
         //gets the animations current frame. null if none availible.
         public synchronized Image getImage() {
              if (frames.size() == 0) {
                   return null;
              else {
                   return getFrame(currFrameIndex).image;
         private AnimFrame getFrame(int i) {
              return (AnimFrame)frames.get(i);
         private class AnimFrame {
              Image image;
              long endTime;
              public AnimFrame(Image image, long endtime) {
                   this.image = image;
                   this.endTime = endTime;
    import java.awt.*;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    public class AnimationTest1 {
         public static void main (String args[]) {          
              AnimationTest1 test = new AnimationTest1();
              test.run();
         private static final long DEMO_TIME = 5000;
         private JFrame frame;
         private Animation anim;
         public void loadImages() {
              //load images
              Image player1 = loadImage("gif1.png");
              Image player2 = loadImage("gif2.png");
              Image player3 = loadImage("gif3.png");
              //create animation
              anim = new Animation();
              anim.addFrame(player1, 200);
              anim.addFrame(player2, 200);
              anim.addFrame(player3, 200);
              anim.addFrame(player2, 200);
         //loads image with ImageIcon
         private Image loadImage(String filename) {
              return new ImageIcon(filename).getImage();
         public void run() {
              try {
                   frame = new JFrame();
                   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   frame.setSize(300, 300);
                   frame.setVisible(true);
                   loadImages();
                   animationLoop();
              finally {
         public void animationLoop() {
              long startTime = System.currentTimeMillis();
              long currTime = startTime;
              while (currTime - startTime < DEMO_TIME) {
                   long elapsedTime = System.currentTimeMillis() - currTime;
                   currTime += elapsedTime;
                   anim.update(elapsedTime);
                   //getContentpane.getgraphics??!!
                   Graphics g = frame.getGraphics();
                   draw(g);
                   g.dispose();
                   try {
                        Thread.sleep(20);
                   catch (InterruptedException ex) {}
         //draw the animation
         public void draw(Graphics g) {
              g.setColor(Color.white);
              g.fillRect(0, 0, 300, 300);          
              g.drawImage(anim.getImage(), 0, 0, null);
    }

    106498II wrote:
    i changed it to read:
    while (animTime > getFrame(currFrameIndex).endTime) {
                        currFrameIndex ++;
                        if (currFrameIndex >3) {
                             currFrameIndex = 0;
                        }this gets rid of the error but still no animation. Perhaps its something to do with that I draw directly on the JFrame?On the JFrame? Better to draw in a JPanel or JComponent. Also, perhaps you're trying to animate on the EDT in which case you get the beginning picture, and the end picture but usually you get nothing in between. Are you using a non-EDT thread or a Swing Timer?
    Addendum: yeah it looks like you're trying to put the EDT (event dispatch thread -- the main thread that runs Swing) to sleep here. Please don't do this. Also you're trying to draw outside of a paint or paintComponent method.
    Solution: Run don't walk to the Sun java2D and Swing graphics tutorials and read and study them.
    Edited by: petes1234 on Dec 11, 2007 7:21 PM

  • Synchronous painting

    Hello!
    I need help in writing a program which uses a synchronous painting. My program looks like this:
    import javax.swing.*;
    import java.awt.*;
    import java.util.*;
    public class Draw extends JPanel{
    private JFrame frame = new JFrame ();
    public Draw (){
    frame.getContentPane ().add (this,BorderLayout.CENTER);
    frame.pack ();
    frame.setSize (new Dimension (300,200));
    frame.setVisible (true);
    public static void main (String[] args)
    {Draw draw = new Draw ();}
    public void paintComponent (Graphics gr){
    super.paintComponent (gr);
    gr.setColor (Color.blue);
    Random r = new Random(System.currentTimeMillis ());
    for(int i=0 ; i<2000000 ; i++){
    int x1 = r.nextInt (this.getWidth ());
    int y1 = r.nextInt (this.getHeight ());
    int x2 = r.nextInt (this.getWidth ());
    int y2 = r.nextInt (this.getHeight ());
    gr.drawLine (x1,y1,x2,y2);
    How can I modify the code so that I see every line drawn after I call drawLine(...) ?
    Thanks!

    It inpossible to tell from your query whether you want to progress towards a solid blue panel or only have one line showing at a time.
    The following code shows both. It is rigged toward showing all lines without clearing. To change to one line showing follow the comment directionsimport javax.swing.JFrame;
    import javax.swing.JPanel;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.util.Random;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    public class Draw extends JPanel implements ActionListener
       private JFrame frame = new JFrame ();
       private int x1 = 0,x2 = 0,y1 = 0,y2 = 0;
       private Random r;
       private Graphics g;       //comment out for single line
       public Draw ()
          super(false); //not double buffered
          r = new Random(System.currentTimeMillis ());
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setContentPane(this);
          frame.pack ();
          frame.setSize (new Dimension (300,200));
          frame.setVisible (true);
          drawLines();
       private void drawLines()
          g = getGraphics();            //comment out for single line
          g.setColor (Color.blue);      //comment out for single line
          int delay = 30; //milliseconds - adjustable
          //forget 2 million, this will run forever if you let it
          new javax.swing.Timer(delay, this).start();
       public static void main (String[] args)
       {Draw draw = new Draw ();}
       public void actionPerformed(ActionEvent evt)
          x1 = r.nextInt (this.getWidth ());
          y1 = r.nextInt (this.getHeight ());
          x2 = r.nextInt (this.getWidth ());
          y2 = r.nextInt (this.getHeight ());
          g.drawLine (x1,y1,x2,y2);      //change to repaint(); for single line
       public void paintComponent (Graphics gr)
          super.paintComponent (gr);
          drawLines();            //comment out for single line
          gr.setColor (Color.blue);
          gr.drawLine (x1,y1,x2,y2);
    }

  • Displaying a Shape?

    I am creating an application that does screen capture of the desktop. I have it working for the most part. I am using the Robot class to capture a 640x480 Rectangle on the screen that is centered using the current position of the mouse.
    So that the user can see the area that is being captured I would like to add a visual Rectangle to the screen that just has the stroke outlined? I am at a loss for where or how to do this. It seams like all the examples I see for drawing shapes has you draw them to a JFrame or some other component. Could you guys suggest to me how I may just add a Raw Outlined Rectangle to the screen? Once I know how to do that I am pretty sure I can get it to follow the Mouse.
    -Matthew

    You can't really paint over the screen in general (I mean you can, but you've got to create a (J)Window and fill it with a screen-captured Image first) but if you're talking about screen capture over a java app, check out this class
    package tjacobs.ui.drag;
    import java.awt.BasicStroke;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Point;
    import java.awt.Stroke;
    import java.awt.event.*;
    import java.util.ArrayList;
    import java.util.Iterator;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    import tjacobs.ui.util.WindowClosingActions;
    * See the public static method addAMouseDragOutliner
    public class MouseDragOutliner extends MouseAdapter implements MouseMotionListener {
         public static final BasicStroke DASH_STROKE = new BasicStroke(1.0f, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_BEVEL, 10.0f, new float[] {8, 8}, 0);
         public static final boolean RECTANGLE = true;
         public static final boolean OVAL = false;
         private boolean mUseMove = false;
         private Point mStart;
         private Point mEnd;
         private boolean mShape = RECTANGLE;
         private Component mComponent;
         private MyRunnable mRunner= new MyRunnable();
         private ArrayList mListeners = new ArrayList(1);
         public MouseDragOutliner() {
              super();
         public MouseDragOutliner(boolean useMove) {
              this();
              mUseMove = useMove;
         public void setShape(boolean b) {
              mShape = b;
         public void mouseDragged(MouseEvent me) {
              doMouseDragged(me);
         public void mousePressed(MouseEvent me) {
              mStart = me.getPoint();
         public void mouseEntered(MouseEvent me) {
              mStart = me.getPoint();
         public void mouseReleased(MouseEvent me) {
              Iterator i = mListeners.iterator();
              Point end = me.getPoint();
              while (i.hasNext()) {
                   ((OutlineListener)i.next()).mouseDragEnded(mStart, end);
              //mStart = null;
         public void mouseMoved(MouseEvent me) {
              if (mUseMove) {
                   doMouseDragged(me);
         public     void addOutlineListener(OutlineListener ol) {
              mListeners.add(ol);
         public void removeOutlineListener(OutlineListener ol) {
              mListeners.remove(ol);
         private class MyRunnable implements Runnable {
              public void run() {
                   Graphics g = mComponent.getGraphics();
                   if (g == null) {
                        return;
                   Graphics2D g2 = (Graphics2D) g;
                   Stroke s = g2.getStroke();
                   g2.setStroke(DASH_STROKE);
                   int x = Math.min(mStart.x, mEnd.x);
                   int y = Math.min(mStart.y, mEnd.y);
                   int w = Math.abs(mEnd.x - mStart.x);
                   int h = Math.abs(mEnd.y - mStart.y);
                   g2.setXORMode(Color.WHITE);
                   if (mShape == RECTANGLE) g2.drawRect(x, y, w, h);
                   else g2.drawOval(x, y, w, h);
                   g2.setStroke(s);
         public void doMouseDragged(MouseEvent me) {
              mEnd = me.getPoint();
              if (mStart != null) {
                   mComponent = me.getComponent();
                   mComponent.repaint();
                   SwingUtilities.invokeLater(mRunner);
         public static MouseDragOutliner addAMouseDragOutliner(Component c) {
              MouseDragOutliner mdo = new MouseDragOutliner();
              c.addMouseListener(mdo);
              c.addMouseMotionListener(mdo);
              return mdo;
         public static interface OutlineListener {
              public void mouseDragEnded(Point start, Point finish);
         public static void main(String[] args) {
              JFrame f = new JFrame("MouseDragOutliner Test");
              Container c = f.getContentPane();
              JPanel p = new JPanel();
              //p.setBackground(Color.BLACK);
              c.add(p);
              MouseDragOutliner outliner = addAMouseDragOutliner(p);
              outliner.setShape(OVAL);
              f.setBounds(200, 200, 400, 400);
              f.addWindowListener(new WindowClosingActions.Exit());
              f.setVisible(true);
    }

  • Creating an Automation program to switch screen resolution?

    Can anybody tell me the steps necessary to create an automation (i.e. just double-click on the icon and it will execute the action) to switch my screen display from whatever it is currently set to,
    to 1280 x 1024 stretched and then have it CONFIRM the setting.
    I change the screen resolutions to a variety of different settings whether I'm playing a game, running a movie off Netflix to my HDTV or just reading and writing email. I know I can turn on the DISPLAY monitor icon on the top right of the screen, click on it and it will show me the most recent settings I've used, and allow me to change it from there, but I'd like to create a automation that will do it with one icon click from the desktop.
    I've got a secondary little keyboard with trackpad that I use when working the computer from the couch for movies and such, but the trackpad is not as easy to manipulate quickly and accurately as the mouse which is back at the mac mini computer, so an automation would speed things up.
    I've tried recording my actions using AUTOMATOR, but when I play it back, it appears to be working (cursor moving to the DISPLAY icon and highlighting the correct resolution) but the screen resolution doesn't actually change as it does when I originally recorded it.
    So I'd like to try it using the correct commands, but I'm still new to AUTOMATOR and can't find SYSTEM PREFERENCES and DISPLAY options commands.
    Any assistance would be appreciated.
    Thanks.

    there i found out how to award the dukes. Now could you help us with the following man, i also need help with the game of life but i have another task to complete.
    here is what i have to do: -
    - write a simple animation in which one or more faces (smiley or sad)bounce around a window.
    - Note that all faces start at a random position in the window, and have a random initial direction (NE, NW,
    SE or SW). The direction of travel of a face only changes when the face bounces off a side of the window.
    - You should ensure that when a face does bounce off the side of the window, its new direction of travel is appropriate (i.e. if it is traveling SW and bounces off the bottom of the screen, it should then be traveling NW).
    - The user should be prompted for the number of faces, and the type of each face (Sad or Smiley) should be chosen randomly.
    - When a face collides with the edge of the window, it should �bounce� as the screenshots illustrate. You can ignore collisions between faces.
    - Each face should be implemented as an object that knows how to draw itself to an JFrame instance.
    - ALL behaviours that are common to both Smiley and Sad faces should be in the Face superclass. This includes most of the drawing routines (e.g. the circle on which the eyes and mouth are drawn, as well as the
    eyes) and the methods for moving the face around the screen and detecting when a face has reached the edge of the screen.
    - Some behaviours will be unique to the subclasses (e.g. the method for drawing the mouth). You should ensure that all classes have a draw method, and that the draw method in the subclasses invokes the draw
    method of the superclass whenever necessary.
    - To achieve the animation, use the following simple algorithm: clear the entire screen, draw all the faces onto the screen, delay for 10 milliseconds, then move each face by exactly one pixel in the direction of travel and repeat.
    Could you please help me do the above.
    i'll award 10 dukes.

  • Create transparency image from shape

    Hi,
    I'd like to create the application that create the transparency image from drawing data. the code is as follows.
    BufferedImage img = new BufferedImage(350,350,BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = img.createGraphics();
    GeneralPath gp = new GeneralPath(GeneralPath.WIND_NON_ZERO);
    gp.moveTo(100,100);     gp.lineTo(100,200);
    gp.lineTo(200,200);     gp.lineTo(200,100); gp.closePath();
    g2.setPaint(Color.yellow);
    g2.fill(gp);
    g2.setStroke(new BasicStroke(2));
    g2.setPaint(Color.red);
    g2.draw(gp);
    File outFile = new File("outimg.png");
    ImageIO.write(img,"png",outFile);
    I can create the image from such code, but the image is not transparent since the background is all black. What additional coding I need to make it transparent?
    Thanks,
    Sanphet

    1. use a PixelGrabber to convert the image into a pixel array
    2. (assuming pixel array called pixelArray) :
    if (pixelArray[loopCounter] == 0xFFFFFFFF) { //assuming the black your seeing is not a fully transparent surface
        pixelArray[loopCounter] = pixelArray[loopCounter] & 0x00FFFFFF; //sets alpha channel for all black area to 0, thus making it fully transparent
    }3. recreate an Image using MemoryImageSource
    I'm sure there is a quicker solution using some built in java functions...but hey, I dont' know it!! :)
    Here's a sample class that utilizes these techniques:
    * To start the process, click on the window
    * Restriction (next version upgrade) :
    *     - firstImage must be larger
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import javax.swing.*;
    public class AdditiveBlendingTest extends javax.swing.JFrame implements MouseListener, ActionListener, WindowListener {
        static final int ALPHA = 0xFF000000; // alpha mask
        static final int MASK7Bit = 0xFEFEFF; // mask for additive/subtractive shading
        static final int ZERO_ALPHA = 0x00FFFFFF; //zero's alpha channel, i.e. fully transparent
        private Image firstImage, secondImage, finalImage; //2 loades image + painted blended image
        private int firstImageWidth, firstImageHeight, secondImageWidth, secondImageHeight;
        private int xInsets, yInsets; //insets of JFrame
        //cliping area of drawing, and size of JFrame
        private int clipX = 400;
        private int clipY = 400;
        //arrays representing 2 loades image + painted blended image
        private int[] firstImageArray;
        private int [] secondImageArray;
        private int [] finalImageArray;
        //system timer, used to cause repaints
        private Timer mainTimer;
        //used for double buffering and drawing the components
        private Graphics imageGraphicalSurface;
        private Image doubleBufferImage;
        public AdditiveBlendingTest() {
            firstImage = Toolkit.getDefaultToolkit().getImage("Image1.jpg");
            secondImage = Toolkit.getDefaultToolkit().getImage("Image2.gif");
         //used to load image, MediaTracker process will not complete till the image is fully loaded
            MediaTracker tracker = new MediaTracker(this);
            tracker.addImage(firstImage,1);
         try {
             if(!tracker.waitForID(1,10000)) {
              System.out.println("Image1.jpg Load error");
              System.exit(1);
         } catch (InterruptedException e) {
             System.out.println(e);
         tracker = new MediaTracker(this);
         tracker.addImage(secondImage,1);
         try {
             if(!tracker.waitForID(1,10000)) {
              System.out.println("Image2.gif Load error");
              System.exit(1);
         } catch (InterruptedException e) {
             System.out.println(e);
         //calculate dimensions
         secondImageWidth = secondImage.getWidth(this);
         secondImageHeight = secondImage.getHeight(this);
         firstImageWidth = firstImage.getWidth(this);
         firstImageHeight = firstImage.getHeight(this);
         //creates image arrays
         firstImageArray = new int[firstImageWidth * firstImageHeight];
            secondImageArray = new int[secondImageWidth * secondImageHeight];
         //embeded if statements will be fully implemented in next version
         finalImageArray = new int[((secondImageWidth >= firstImageWidth) ? secondImageWidth : firstImageWidth) *
                 ((secondImageHeight >= firstImageHeight) ? secondImageHeight : firstImageHeight)];
         //PixelGrabber is used to created an integer array from an image, the values of each element of the array
         //represent an individual pixel.  FORMAT = 0xFFFFFFFF, with the channels (FROM MSB) Alpha, Red, Green, Blue
         //each taking up 8 bits (i.e. 256 possible values for each)
         try {
             PixelGrabber pgObj = new PixelGrabber(firstImage,0,0,firstImageWidth,firstImageHeight,firstImageArray,0,firstImageWidth);
             if(pgObj.grabPixels() && ((pgObj.getStatus() & ImageObserver.ALLBITS) != 0)){
         } catch (InterruptedException e) {
             System.out.println(e);
         try {
             PixelGrabber pgObj = new PixelGrabber(secondImage,0,0,secondImageWidth,secondImageHeight,secondImageArray,0,secondImageWidth);
             if (pgObj.grabPixels() && ((pgObj.getStatus() & ImageObserver.ALLBITS) !=0)) {
         } catch (InterruptedException e) {
             System.out.println(e);
         //adds the first images' values to the final painted image.  This is the only time the first image is involved
         //with the blend
         for(int cnt = 0,large = 0; cnt < (secondImageWidth*secondImageHeight);cnt++, large++){
             if (cnt % 300 == 0 && cnt !=0){
              large += (firstImageWidth - secondImageWidth);
             finalImageArray[cnt] = AdditiveBlendingTest.ALPHA + (AdditiveBlendingTest.ZERO_ALPHA & firstImageArray[large]) ;
         //final initializing
         this.setSize(clipX,clipY);
         this.enable();
         this.setVisible(true);
         yInsets = this.getInsets().top;
         xInsets = this.getInsets().left;
         this.addMouseListener(this);
         this.addWindowListener(this);
         doubleBufferImage = createImage(firstImageWidth,firstImageHeight);
         imageGraphicalSurface = doubleBufferImage.getGraphics();
        public void mouseEntered(MouseEvent e) {}
        public void mouseExited(MouseEvent e) {}
        public void mousePressed(MouseEvent e) {}
        public void mouseReleased(MouseEvent e) {}
        public void windowActivated (WindowEvent e) {}
        public void windowDeiconified (WindowEvent e) {}
        public void windowIconified (WindowEvent e) {}
        public void windowDeactivated (WindowEvent e) {}
        public void windowOpened (WindowEvent e) {}
        public void windowClosed (WindowEvent e) {}
        //when "x" in right hand corner clicked
        public void windowClosing(WindowEvent e) {
         System.exit(0);
        //used to progress the animation sequence (fires every 50 ms)
        public void actionPerformed (ActionEvent e ) {
         blend();
         repaint();
        //begins animation process and set's up timer to continue
        public void mouseClicked(MouseEvent e) {
         blend();
         mainTimer = new Timer(50,this);
         mainTimer.start();
         repaint();
         * workhorse of application, does the additive blending
        private void blend () {
         int pixel;
         int overflow;
         for (int cnt = 0,large = 0; cnt < (secondImageWidth*secondImageHeight);cnt++, large++) {
             if (cnt % 300 == 0 && cnt !=0){
              large += (firstImageWidth - secondImageWidth);
             //algorithm for blending was created by another user, will give reference when I find
             pixel = ( secondImageArray[cnt] & MASK7Bit ) + ( finalImageArray[cnt] & MASK7Bit );
             overflow = pixel & 0x1010100;
             overflow -= overflow >> 8;
             finalImageArray[cnt] = AdditiveBlendingTest.ALPHA|overflow|pixel ;
         //creates Image to be drawn to the screen
         finalImage = createImage(new MemoryImageSource(secondImageWidth, secondImageHeight, finalImageArray,
              0, secondImageWidth));
        //update overidden to eliminate the clearscreen call.  Speeds up overall paint process
        public void update(Graphics g) {
         paint(imageGraphicalSurface);
         g.drawImage(doubleBufferImage,xInsets,yInsets,this);
         g.dispose();
        //only begins painting blended image after it is created (to prevent NullPointer)
        public void paint(Graphics g) {
         if (finalImage == null){
             //setClip call not required, just added to facilitate future changes
             g.setClip(0,0,clipX,clipY);
             g.drawImage(firstImage,0,0,this);
             g.drawImage(secondImage,0,0,this);
         } else {
             g.setClip(0,0,clipX,clipY);
             g.drawImage(finalImage,0,0,this);
        public static void main( String[] args ) {
         AdditiveBlendingTest additiveAnimation = new AdditiveBlendingTest();
         additiveAnimation.setVisible(true);
         additiveAnimation.repaint();

  • Advance level drawing problem with Jframe and JPanel need optimize sol?

    Dear Experts,
    I m trying to create a GUI for puzzle game following some kind of "game GUI template", but i have problems in that,so i tried to implement that in various ways after looking on internet and discussions about drawing gui in swing, but i have problem with both of these, may be i m doing some silly mistake, which is still out of my consideration. please have a look at these two and recommend me one of them, which is running without problems (flickring and when you enlarge window the board draw copies (tiled) everywhere,
    Note: i don't want to inherit jpanel or Jframe
    here is my code : import java.awt.BorderLayout;
    public class GameMain extends JFrame {
         private static final long serialVersionUID = 1L;
         public int mX, mY;
         int localpoints = 0;
         protected static JTextField[][] squares;
         protected JLabel statusLabel = new JLabel("jugno");
         Label lbl_score = new Label("score");
         Label lbl_scorelocal = new Label("local score");
         protected static TTTService remoteTTTBoard;
         // Define constants for the game
         static final int CANVAS_WIDTH = 800; // width and height of the game screen
         static final int CANVAS_HEIGHT = 600;
         static final int UPDATE_RATE = 4; // number of game update per second
         static State state; // current state of the game
         private int mState;
         // Handle for the custom drawing panel
         private GameCanvas canvas;
         // Constructor to initialize the UI components and game objects
         public GameMain() {
              // Initialize the game objects
              gameInit();
              // UI components
              canvas = new GameCanvas();
              canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
              this.setContentPane(canvas);
              this.setDefaultCloseOperation(EXIT_ON_CLOSE);
              this.pack();
              this.setTitle("MY GAME");
              this.setVisible(true);
         public void gameInit() {     
         // Shutdown the game, clean up code that runs only once.
         public void gameShutdown() {
         // To start and re-start the game.
         public void gameStart() {
         private void gameLoop() {
         public void keyPressed(KeyEvent e) {
         public void keyTyped(KeyEvent e) {
         public void gameKeyReleased(KeyEvent e) {
              PuzzleBoard bd = getBoard();
              for (int row = 0; row < 4; ++row) {
                   for (int col = 0; col < 4; ++col) {
                        if (e.getSource() == squares[row][col]) {
                             if (bd.isOpen(col, row)) {
                                  lbl_score.setText("Highest Score = "
                                            + Integer.toString(bd.getPoints()));
                                  setStatus1(bd);
                                  pickSquare1(col, row, squares[row][col].getText()
                                            .charAt(0));
         protected void pickSquare1(int col, int row, char c) {
              try {
                   remoteTTTBoard.pick(col, row, c);
              } catch (RemoteException e) {
                   System.out.println("Exception: " + e.getMessage());
                   e.printStackTrace();
                   System.exit(1);
         // method "called" by remote object to update the state of the game
         public void updateBoard(PuzzleBoard new_board) throws RemoteException {
              String s1;
              for (int row = 0; row < 4; ++row) {
                   for (int col = 0; col < 4; ++col) {
                        squares[row][col].setText(new_board.ownerStr(col, row));
              lbl_score.setText("Highest Score = "
                        + Integer.toString(new_board.getPoints()));
              setStatus1(new_board);
         protected void setStatus1(PuzzleBoard bd) {
              boolean locals = bd.getHave_winner();
              System.out.println("local win" + locals);
              if (locals == true) {
                   localpoints++;
                   System.out.println("in condition " + locals);
                   lbl_scorelocal.setText("Your Score = " + localpoints);
              lbl_score
                        .setText("Highest Score = " + Integer.toString(bd.getPoints()));
         protected PuzzleBoard getBoard() {
              PuzzleBoard res = null;
              try {
                   res = remoteTTTBoard.getState();
              } catch (RemoteException e) {
                   System.out.println("Exception: " + e.getMessage());
                   e.printStackTrace();
                   System.exit(1);
              return res;
         /** Custom drawing panel (designed as an inner class). */
         class GameCanvas extends JPanel implements KeyListener {
              /** Custom drawing codes */
              @Override
              public void paintComponent(Graphics g) {
                   // setOpaque(false);
                   super.paintComponent(g);
                   // main box; everything placed in this
                   // JPanel box = new JPanel();
                   setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
                   // add(statusLabel, BorderLayout.NORTH);
                   // set up the x's and o's
                   JPanel xs_and_os = new JPanel();
                   xs_and_os.setLayout(new GridLayout(5, 5, 0, 0));
                   squares = new JTextField[5][5];
                   for (int row = 0; row < 5; ++row) {
                        for (int col = 0; col < 5; ++col) {
                             squares[row][col] = new JTextField(1);
                             squares[row][col].addKeyListener(this);
                             if ((row == 0 && col == 1) || (row == 2 && col == 3)
                             || (row == 1 && col == 4) || (row == 4 && col == 4)
                                       || (row == 4 && col == 0))
                                  JPanel p = new JPanel(new BorderLayout());
                                  JLabel label;
                                  if (row == 0 && col == 1) {
                                       label = new JLabel("1");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 4 && col == 0) {// for two numbers or
                                       // two
                                       // blank box in on row
                                       label = new JLabel("2");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 1 && col == 4) {
                                       label = new JLabel("3");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 4) {
                                       label = new JLabel("4");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else {
                                       label = new JLabel("5");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  label.setOpaque(true);
                                  label.setBackground(squares[row][col].getBackground());
                                  label.setPreferredSize(new Dimension(label
                                            .getPreferredSize().width, squares[row][col]
                                            .getPreferredSize().height));
                                  p.setBorder(squares[row][col].getBorder());
                                  squares[row][col].setBorder(null);
                                  p.add(label, BorderLayout.WEST);
                                  p.add(squares[row][col], BorderLayout.CENTER);
                                  xs_and_os.add(p);
                             } else if ((row == 2 && col == 1) || (row == 1 && col == 2)
                                       || (row == 3 && col == 3) || (row == 0 && col == 3)) {
                                  xs_and_os.add(squares[row][col]);
                                  // board[ row ][ col ].setEditable(false);
                                  // board[ row ][ col ].setText("");
                                  squares[row][col].setBackground(Color.RED);
                                  squares[row][col].addKeyListener(this);
                             } else {
                                  squares[row][col] = new JTextField(1);
                                  // squares[row][col].addActionListener(this);
                                  squares[row][col].addKeyListener(this);
                                  xs_and_os.add(squares[row][col]);
                   this.add(xs_and_os);
                   this.add(statusLabel);
                   this.add(lbl_score);
                   this.add(lbl_scorelocal);
              public void keyPressed(KeyEvent e) {
              public void keyReleased(KeyEvent e) {
                   gameKeyReleased(e);
              public void keyTyped(KeyEvent e) {
         // main
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                   @Override
                   public void run() {
                        new GameMain();
      thanks a lot for your time , consideration and efforts.
    jibby
    Edited by: jibbylala on Sep 20, 2010 6:06 PM

    jibbylala wrote:
    thanks for mentioning as i wasn't able to write complete context here.Yep thanks camickr. I think that Darryl's succinct reply applies here as well.

  • Help with drawing strings on JFrame?!?!

    Hey guys, I'm really new to Java (just started AP Comp Sci last month), and we had a project to build a Mastermind application using numbers, which I did. However, I'm trying to learn more on my own, and was hoping to use the example code my teacher gave me to output what I want to say to a JFrame instead of just the command prompt.
    Here is the code for my Mastermind class:
    Code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Mastermind extends JFrame
         public static void main(String args[])
              int master[] = new int[4];
              int win = 0;
              for(int x = 0; x<4; x++)
                   master[x] = (int)(Math.random()*10);
              System.out.println();
              do {
                   int guess[] = new int[4];
                   int countMaster[] = new int[4];
              String numguess = JOptionPane.showInputDialog("Enter your guess (4 digits, please)");
              for (int x = 0;x<4;x++)
                   guess[x] = (numguess.charAt(x)-48);
              int correctlyPlaced = 0;
              int correct = 0;
              for (int x = 0;x<4;x++)
                   if(master[x] == guess[x])
                        correctlyPlaced += 1;
              for (int x = 0; x<4;x++)
                             for (int y = 0; y<4;y++)
                                  if((guess[x]==master[y]) && (countMaster[y]==0)) {
                                       correct++;
                                       countMaster[y]=1;
                                       y=5;
              System.out.print("Guess:\t\t\t");
              for (int x = 0;x<4;x++) {
                   System.out.print(guess[x]);
              System.out.println();
              System.out.println("Correct:\t\t"+correct);
              System.out.println("Correctly Placed:\t"+correctlyPlaced);
              if (correctlyPlaced==4) {
                   win=1;
         } while(win<1);
         System.out.println("You win!");
              System.exit(0);
    And here is the example code that my teacher gave me for how to draw a string on a JFrame:
    Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Fonts extends JFrame {
         public Fonts()
              super("Using Fonts");
              setSize(420,125);
              show();
         public void paint(Graphics g)
              super.paint(g);
              g.setFont(new Font("Serif", Font.BOLD, 12));
              g.drawString("Serif 12 point bold.",20,50);
         public static void main(String args[])
              Fonts application = new Fonts();
              application.setDefaultCloseOperation (
                   JFrame.EXIT_ON_CLOSE);
    I would like to be able to put "Guess," "Correct," and "Correctly Placed," on a JFrame, with their respective variables. Any ideas? Thank you!!!

    800045 wrote:
    And DrClap, I get that, but I'm not sure how to put my existing code into the class file that uses the JFrame.You wouldn't put your existing code in there. Your existing code is designed to run as a console app and most of it is concerned with the machinery of getting input from the user. If you want to write it as a Swing app, then you wouldn't need any code which writes to a JFrame in the first place.
    So if your goal for learning on your own is to write GUI applications instead of console applications, then go off and read the Swing tutorials. Right now you're going down the wrong road. However if you're trying to learn something else on your own (I can't tell what that might be) then explain what it is you're trying to learn.

  • Inability to draw simple graphics in Java properly (threads and JFrame)

    I am trying to use a thread to continually draw randomly positioned and randomly sized squares in the middle of a JFrame window. I have got 'something' working with the following code, however when run, the actual window doesn't come up properly. If I resize the window it does, and I get the result I wanted, but when the window is first opened it does not fully draw itself on screen. Can anybody help here? I am a bit of a novice when it comes to Java
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    public class TestDraw extends JFrame implements Runnable {
    //DECLARE VARIABLES
         private JLabel lblText;
         private JButton btnBegin;
         private JPanel contentPane;
         private int CoordX, CoordY,SizeX, SizeY, Colour;     // Co'ords for drawing the squares
         Random random = new Random();                              // Random numbers (for square dimensions and colours)
         int n_1 = 450, n_2 = 130, n_3 = 100, n_4 = 4;          // The different ranges of randoms I require
         Thread squares = new Thread(this);                         // Implements a new thread
    //END OF DECLARE VARIABLES
    // CALLS INITIAL PROCEDURE, SETS VISIBLE ETC
         public TestDraw() {
              super();
              initializeComponent();
              this.setVisible(true);
    // INITIALISATION PROCEDURE CALL
         private void initializeComponent() {
              lblText = new JLabel();
              btnBegin = new JButton();
              contentPane = (JPanel)this.getContentPane();
              // lblText
              lblText.setText("This should draw squares on screen...");
              // btnBegin
              btnBegin.setText("Start");
              btnBegin.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        btnBegin_actionPerformed(e);
              // contentPane
              contentPane.setLayout(null);
              addComponent(contentPane, lblText, 10,300,364,18);
              addComponent(contentPane, btnBegin, 144,10,101,28);
              // TestDraw
              this.setTitle("TestDraw Program for CM0246");
              this.setLocation(new Point(0, 0));
              this.setSize(new Dimension(390, 350));
    // POSITION COMPONENTS ON SCREEN
         private void addComponent(Container container,Component c,int x,int y,int width,int height)     {
              c.setBounds(x,y,width,height);
              container.add(c);
    // EVENT HANDLING PROCEDURES
         private void btnBegin_actionPerformed(ActionEvent e) {
              System.out.println("\nAction Event from btnBegin called...");
              squares.start(); //STARTS THE SQUARES DRAWING THREAD (Draws random squares on screen)
    // THE MAIN METHOD (STARTS THE PROGRAM)
         public static void main(String[] args) {
              TestDraw bobdole = new TestDraw();
    // THE SQUARE DRAWINGS THREAD (SHOULD DRAW RANDOM SIZED AND COLOURED SQUARES IN RANDOM PLACES)
         public void run() {
              System.out.println("Thread running if this prints");
                   while(true) {
                        int int_1 = random.nextInt(n_1);     // chooses random int for X co'ord
                        int int_2 = random.nextInt(n_2)+70;     // chooses random int for Y co'ord
                        int int_3 = random.nextInt(n_3)+10;     // chooses random int for X dimension
                        int int_4 = random.nextInt(n_3)+10;     // chooses random int for Y dimension
                        CoordX = int_1;
                        CoordY = int_2;
                        SizeX  = int_3;
                        SizeY  = int_4;
                        repaint();
                        try {
                             squares.sleep(500);
                        catch (InterruptedException e) {
                             System.out.println(e);
    // THE PAINT METHOD ATTATCHED TO THE SQUARES THREAD
         public void paint( Graphics g ) {
              System.out.print("Colour" + Colour);
              g.setColor(Color.blue);
              g.fillRect(CoordX, CoordY, SizeX, SizeY);
    // END OF PROGRAM

    I don't see any problem when I run the program but.. In general you shouldn't paint directly on a frame by overloading the paint method. You should rather create a custom component on which you draw.
    But if you do overload paint, make sure you call super.paint before doing anything else.
    More information in this tutorial: http://java.sun.com/docs/books/tutorial/uiswing/painting/index.html

Maybe you are looking for

  • Parse Exception for &

    Hi I am using the following code for parsing an XML using DOM: String xml = <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE cXML SYSTEM "http://xml.cXML.org/schemas/cXML/1.2.019/cXML.dtd"> <cXML payloadID="[email protected]"       xml:lang=

  • Substitution variable in Dynamic Calc

    Hi, We are using Essbase 9.3.0 on Windows and are seeing this behavior in our BSO cubes. When we use a substitution variable in a Scenario member with Dynamic Calc (not store) setting, after the first retrieve, if we change the value of the substitut

  • Doubt about sub totaling in Report Painter

    Hi, I am new to the report painter and i want to know that is there a possibility of performing the sub total in the output. Suppose,i had defined a row and column and in the row i had given the range of the Account Numbers and in the column i had de

  • How to convert PDF with accented letters that are not Unicode?

    Hello all, I have a PDF letter that is written in Spanish. When I copy and paste the Spanish word: organización ... it is pasted to Noepad or Word as: organizaci ´ on The word displays properly in the PDF, however I believe it was created originally

  • Thinking of selling Adobe Illustrator cs6 software, can it be used on other people's computers if I sell it? l

    Thinking of selling my Adobe Illustrator cs6, Mac compatible software plus the Classroom in a Book with lessons CD. I'd really like Photoshop instead.  I've never sold software, can it be used on other people's computers if I sell it? I'd have to uni