gunjannigam 28 Junior Poster

I got it working. Thanks mKorbel. With KeyBindings I don't have to care upon Focusable

gunjannigam 28 Junior Poster

@JamesCherrill

not (-:please to stop to catch the Focus:-) if you'd implements KeyBinding then you could stop to care about Focus, FocusRecycle, SubSystem Fosuc, this best Swing Listener for HardWare KeyBoard, (-: and in all cases better as memoninic as you suggested in other thread:-)

Thanks I will try to that also . Can you give me a good working example of how to implement KeyBinding. I was trying to use Oracle one but could not get it working.

gunjannigam 28 Junior Poster

You may need to setFocusable(true); on your JPanel followed by requestFocus();

Thanks that worked perfectly fine. I assumed that JPanel must be having the focus but it didn't.

gunjannigam 28 Junior Poster

Here is a simple form if my code with KeyListener not working. Listener is added to my main panel. The main Panel has the focus but still keyListner is not working. Have a look at it

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */



import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;

/**
 *
 * @author gunjan
 * @copyright gunjan 2011
 */
public class Example extends JPanel implements ActionListener,KeyListener
{
    Dimension screenSize;
    Point currentPoint;
    public static void main(String[] args)
    {
        Example path = new Example();
    }
    public Example()
    {
        
            JFrame frame = new JFrame();
            screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            frame.setSize(screenSize);
            frame.setUndecorated(true);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.setBackground(Color.black);
            addKeyListener(this);
            frame.getContentPane().add(this);
            this.createPopupMenu();
            
            frame.setVisible(true);
        
    }
    
    public void keyTyped(KeyEvent e) {
        //throw new UnsupportedOperationException("Not supported yet.");
        System.out.println(e);
    }

    public void keyPressed(KeyEvent e) {
        //throw new UnsupportedOperationException("Not supported yet.");
        System.out.println(e);
    }

    public void keyReleased(KeyEvent e) {
        //throw new UnsupportedOperationException("Not supported yet.");
        System.out.println(e);
    }
    @Override
    public void paint(Graphics g)
    {
        super.paint(g);
        Graphics2D g2d = (Graphics2D)g;
        
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        if(currentPoint!=null)
        {
            g2d.setColor(Color.white);
            g2d.fillOval((int) (currentPoint.getX() - 3), (int) (currentPoint.getY() - 3), 6,6);
        }

    }
    public void createPopupMenu() {
        JMenuItem menuItem;

        //Create the popup menu.
        JPopupMenu popup = new JPopupMenu();
        menuItem = new JMenuItem("Loitre");
        menuItem.addActionListener(this);

        popup.add(menuItem);
        menuItem = new JMenuItem("Eight");
        menuItem.addActionListener(this);
        popup.add(menuItem);

        menuItem = new JMenuItem("Ring");
        menuItem.addActionListener(this);
        popup.add(menuItem);
        //Add listener to the text area …
gunjannigam 28 Junior Poster

Here is the complete code

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */



import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;

/**
 *
 * @author gunjan
 * @copyright gunjan 2011
 */
public class Path extends JPanel implements ActionListener,KeyListener
{
    Dimension screenSize;
    ArrayList<Point> eightPoints;
    ArrayList<ArrayList<Point>> eightList;
    ArrayList<ArrayList<Point>> ringList;
    ArrayList<Point> ringPoints;
    ArrayList<ArrayList<Point>> loitreList;
    ArrayList<Point> loitrePoints;
    String statusBar,mouseCoord;
    private int currentFig =0;
    Point currentPoint;
    public static void main(String[] args)
    {
        Path path = new Path();
    }
    public Path()
    {
        JFrame frame = new JFrame();
        screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        frame.setSize(screenSize);
        frame.setUndecorated(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
               
        this.setBackground(Color.black);
        addKeyListener(this);
        frame.getContentPane().add(this);
        statusBar = "Ready";
        ringPoints = new ArrayList<Point>();
        ringList = new ArrayList<ArrayList<Point>>();
        eightPoints = new ArrayList<Point>();
        eightList = new ArrayList<ArrayList<Point>>();
        loitrePoints = new ArrayList<Point>();
        loitreList = new ArrayList<ArrayList<Point>>();
        setMouseCoord(MouseInfo.getPointerInfo().getLocation());
        this.createPopupMenu();
        
        frame.setVisible(true);
    }
    private void setMouseCoord(Point p)
    {
        mouseCoord = "X: "+(int)p.getX()+"  Y: "+(int)p.getY();
    }
    @Override
    public void paint(Graphics g)
    {
        super.paint(g);
        Graphics2D g2d = (Graphics2D)g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g2d.setStroke(new BasicStroke(2));
        for(int i=0;i<loitreList.size();i++)
        {
            ArrayList<Point> pointList = loitreList.get(i);
            Point point1 = pointList.get(0);
            Point point2 = pointList.get(1);

            double radius = point1.distance(point2);
            g2d.setColor(Color.white);
            g2d.fillOval((int)point1.getX()-3, (int)point1.getY()-3, 6,6);
            g2d.drawOval((int)(point1.getX()-radius), (int)(point1.getY()-radius),(int)(2*radius), (int) (2 * radius));
            
        }
        for(int i=0;i<eightList.size();i++)
        {
            ArrayList<Point> pointList = eightList.get(i);
            Point point1 = pointList.get(0);
            Point point2 = pointList.get(1);
            g2d.setColor(Color.white); …
gunjannigam 28 Junior Poster

I am attaching my complete code, which I was currently developing. I am not able to get why doesn't my KeyListener work. None of the KeyListener events are fires on pressing the keyboard. Please have a look and tell me the flaws in my code

Path.java

gunjannigam 28 Junior Poster
Impossible to test without the images. To debug this, I'd add more printlns to see the how the code flow goes. When does the 4 second wait occur? What causes the next load of the images to be done?

The four second wait occurs when the image is read from the hard disk and loaded into a buffer. This four seconds wait is called in about every 20 sec. The GUI should work with old images and after new images are loaded in next buffer in the next paint call if will draw new images.
I have attached my two codes here which I use
Example.java

UDPBroadCastServer.java


I am not able to attach the images with zip file. I am attaching a URL where I have uploaded my zip file of images. Images

gunjannigam 28 Junior Poster

Running a seperate thread doesn't gaurentee that the images would be loaded by the time repaint(); is called.
My speculation is that the JRE is putting on some kind of locking mechanism to the ArrayList until the il (ImageLoader) thread completes its job. thereby paint() of your main GUI would be waiting for the resource to be freed by your thread.

So, a good option would be to run multiple threads (provided your CPU usage levels are nominal during execution )where-in each Thread tries to load , one image out of the 25.

I'm not sure. But I think this is whats happening.

Yaa, that is what is currently happening. I will try to use multiple threads.

One thread for all would be sufficient. Too many threads will actually take longer unless your PC has that many extra cores.

My PC has four cores. I will try to use multiple threads and will see what's the esult

Does the code call createImageBuffer when it needs the images and wait until they are loaded to proceed and so freeze the GUI by doing the call on the GUI's thread?

Can the loading of the images be done in the background on another thread while the user is interacting with the GUI so that when the need for the next batch of images comes, they will already have been loaded?

AFAIK, The Main thread is completely different from the other thread that calls createImageBuffer. But the thread is started …

gunjannigam 28 Junior Poster

Its spending the time in reading images from disk. createImageBuffer creates a buffer of 25 images and in this code it taking 4 sec of time in Image.read(). That code is called each time my centerimage change, i.e. after approximately 25 sec.
So after each 25 sec I call createImageBuffer() and then my GUI with other code is stuck for 4 sec approximately till the ImageIO.read is not complete

gunjannigam 28 Junior Poster

Its taking more than 3-4 sec, and during that time my UI is hanged.

I am posting some relevant part of my code

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package hsi;

import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 *
 * @author gunjan
 */
public class Example extends JPanel 
{
    int originX,originY,radii;
    float heading,headingBug;
    float range;
    float currentLat, currentLon;
    BasicStroke dashed;

    float minRange;
    
    String mapImage,oldMapImage="/images/map/mumbai/NA.png";
    int screenWidth,screenHeight;
    ArrayList<ArrayList<BufferedImage>> imageList;
    public Example()
    {
        try {
            JFrame frame = new JFrame();
            screenWidth = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth();
            screenHeight = (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight();
            frame.setSize(screenWidth,screenHeight);
            frame.setUndecorated(true);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setBackground(Color.black);
            frame.getContentPane().add(this);
            originX = screenWidth / 2;
            originY = screenHeight - 150;
            radii = originX - 100;
            heading = 90;
            headingBug = 0;
            //repaint();
            imageList = createImageBuffer(oldMapImage);
            range = 4;
            minRange = 0.1f;
            currentLat =18.92f;
            currentLon = 72.780f;
            
            
            new UDPClient(this).start();
            //addMouseListener(this);
            mapImage = "/images/map/NA.png";
           
            frame.setVisible(true);

        }catch (Exception ex) {
            Logger.getLogger(Example.class.getName()).log(Level.SEVERE, null, ex);
        } 
    }
    public static void main(String[] args)
    {
        new Example();
    }
    public void paint(Graphics g)
    {
        try {
            Graphics2D g2d = (Graphics2D) g;
            Composite origComposite = g2d.getComposite();
            NumberFormat formatter = new DecimalFormat("000");
            String str = formatter.format(heading);
            
            g2d.setColor(Color.black);
            g2d.fillRect(0, 0, screenWidth, screenHeight);
            double translateY = (19.2983446067557 - currentLat) % 0.0202768935753;
            double translateX = (currentLon - 72.7742958068848) % 0.0300407409668;
            int …
gunjannigam 28 Junior Poster

In my application, I have to draw 25 images of 700*500 pixels. I am trying to use ImageIO.read() method, which is called by creating another Thread. Its taking too much time to read images. I thought since i am calling the image read functions by creating another thread my another code, i.e. my GUI, should run without waiting for ImageIO.read() to complete. But my GUI being in a different thread still waits till ImageIO.read() is complete.
Is there an another way to read images in less time other than Image.read()
Can we somehow reduce the time taken by ImageIO.read() to read the images

gunjannigam 28 Junior Poster

Just attach listener to first field something like addInputMethodListener(InputMethodListener l) and then listen for inputMethodTextChanged(InputMethodEvent event) once that happens do your calculation for second field

Hi,
I tried to used InputMethodListener but the event inputMethodTextChanged was not triggered when the text in JFormattedTextField changed. Initially I also tried use propertyChange Listener but that was triggered many times even the input was not changed so I could not control it.
Here is the code

jFormattedTextField1.addInputMethodListener(this);

My class implements InputMethodListener
and these were the listeners

public void inputMethodTextChanged(InputMethodEvent event) {
        //throw new UnsupportedOperationException("Not supported yet.");
System.out.println("Text Changed");
        System.out.println("1"+event.getText());

    }

    public void caretPositionChanged(InputMethodEvent event) {
        //throw new UnsupportedOperationException("Not supported yet.");
System.out.println("Caret Changed");
         System.out.println("2"+event.getText());
    }
gunjannigam 28 Junior Poster

I want to have two textfields which will have the following validations
1) Both should be Integers
2) The value in one textfield should be a integer multiple of other

I have used two JFormattedTextFields to this. This is what i have done till now

NumberFormat updateFormat,sampleFormat;
updateFormat = NumberFormat.getNumberInstance();
updateFormat.setMaximumFractionDigits(0);
updateFormat.setParseIntegerOnly(true);
sampleFormat = NumberFormat.getNumberInstance();
sampleFormat.setMaximumFractionDigits(0);
sampleFormat.setParseIntegerOnly(true);
javax.swing.JFormattedTextField jFormattedTextField1 =new javax.swing.JFormattedTextField(updateFormat);        
javax.swing.JFormattedTextField jFormattedTextField2 = new javax.swing.JFormattedTextField(sampleFormat);

With the help of this my first part is complete
Now I am stuck with the second part, i.e. jFormattedTextField1 value should be a Integer multiple of jFormattedTextField2. I think I need to customize my NumberFormat by extending it. But How should I do that? Please help me out

gunjannigam 28 Junior Poster

I have written a code which uses RXTX Serial API for communication. Now I want to distribute a jar file for my program. The problem is that since I have used RXTX Serial API jar & dll files for this needs to be copied in java home. I wrote a code to copy this files in a correct location. Now after running the copy code if I rum my main program code it runs fine. But if I don't run my copy code first the other main program doesn't run. Fair and square. Now Since I have to distribute my code single jar file I can't ask user to run two different programs. I have to do it with one jar only. So I wrote a third program which calls my first code methods to copy the file and then my main code methods. This program is able to copy the files correctly but when it tries to run my Main program it fails saying that Serial API files are missing. And if I again try to run my program it runs perfectly. That proves the code checks for the resources before running only and any resource added during runtime doesn't count. So what I was thinking is it possible to run two java programs from one jar file one after the another like we can do with batch files?

gunjannigam 28 Junior Poster

I am using JPQL to write queries. I have an SQL as

SELECT * 
FROM  `powergenerationdatapoint` AS pgdp
INNER JOIN (

SELECT MAX( TIMESTAMP ) TIME
FROM powergenerationdatapoint
GROUP BY solarpanel_id
)maxtime ON pgdp.timestamp = maxtime.time
WHERE solarpanel_id
IN (

SELECT id
FROM solarpanel
WHERE solar_plant_id =1
)
GROUP BY solarpanel_id

This is query with Subquery in JOIN. How do I write this in JP QL

gunjannigam 28 Junior Poster

Solved using Path2D and Arc2D

gunjannigam 28 Junior Poster

I need yo draw a shape as attached in the image using Java graphics. I am struggling with the curve part. The curve part is a arc of an circle whose radius and center is known. But I have to paint the region out side of that arc. How will I do that? I was looking at Path2D.Float() and there is a guadTo function. It says it needs a control point to draw that quadratic curve. Can anybody help me understanding what this control point means. I know how to draw that arc using drawArc method but how to paint outside the arc is what I what I want to know

gunjannigam 28 Junior Poster

Does the program have to perform the UDP data transfer for every paint? If so, is this what is limiting your re-draw rate?
What Thread is the UDP activity happening on - is it called directly or indirectly from paint or paintComponent? If so, you may be blocking Swing's event dispatch thread which will cause jerky screen refreshes.

Yes the program does need to perform UDP data transfer for every paint.
I have a TimerTask which is called to first listen data by UDP and then paintComponent is called from the same object
As I have mentioned earlier I have implemented the code using two ways, firstly by drawing the Ticks and Text by Java Graphics. In this method I am getting shaky texts as I have shown in the above attached image. The texts are shaking their as they rotate
For solving the shaking problem I tried to use a second methodology in which I was drawing image, which consists of Tick and text labels. Since it was a image the text labels were not shaking but in that case I was getting jerky motion but now after using your suggestion of taking ImageIO.read the in second method I am getting a smooth motion
Thanks for your help

gunjannigam 28 Junior Poster

still not working..............

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
//<applet code=newt.class width=1200 height =1200></applet>
public class newt extends Applet //implements ActionListener
{
    BufferedImage img = null;
public void init()
{   
       try {
    img = ImageIO.read(new File("D:\Winter.jpg"));
} catch (IOException e) {}

    }
    public void paint(Graphics g)
     {
        g.drawImage(img, 10, 10, this);
      }
}

First of all import java.io.*;
Secondly use "d:/Winter.jpg" in filename isntead of "d:\Winter.jpg"

gunjannigam 28 Junior Poster

Move as much code as possible out of paint(...) - eg read the image file or create the new Font just once at startup, not on every call to paint(...).
How and how often are you updating? You should be using a javax.swing.Timer to call update the heading then repaint() pretty frequently, eg 50 mSec

I am updating at a higher rate 25msec. I am using TimerTask instead of javax.swing.Timer to schedule my task

that so hard to speak about that, if you really needed some hepl, then you have to send runnable example,

shots to the dark, common mistakes

paintCOmponent instead of paint

setOpaque(false)

I have tried using the paintComponent and set as dark example. I am attaching three codes with this. Main,java draws the current component. UDPClient sends the data to Main.java through UDP protocol. I have to finally update my data using UDP protocl

I would agree with the above suggestions to get the ImageIO.read() out of the paint() method and override paintComponent() instead of paint() unless this is an AWT Applet.

I'd also like to mention that you don't necessarily need to create another rotated instance of AffineTransform here

AffineTransform transform = (AffineTransform) (affTransform.clone());
            g2d.transform(transform.getRotateInstance(-this.getHeadingValue() / 57.29, centerX, centerY));

You should be able to simply call

g2d.rotate(-this.getHeadingValue() / 57.29, centerX, centerY)

and draw the image. Since you're restoring the original transform anyway, you can operate directly with the current transform of the graphics context.

I have tried using

AffineTransform transform = (AffineTransform) (affTransform.clone());
            g2d.transform(transform.getRotateInstance(-this.getHeadingValue() …
gunjannigam 28 Junior Poster

The flaw in your algorithm is that you are not multi[lying your change by 100. You need to multiply the change by 100 if you calculating the coins using Cent Value of the coin

gunjannigam 28 Junior Poster

I have to draw a Circular gauge using Java Graphics. Somewhat similar to the attached image, the circular gauge without the black border as in image.
I tried to use two methodologies but none of them is working perfectly
Firstly, I tried to draw everything using Java Graphics and then rotate the image as per the required input
Following is the code for that

public void paint(Graphics g)
    {
        try {
            centerX = this.getWidth() / 2;
            centerY = this.getHeight() / 2;
            Graphics2D g2d = (Graphics2D) g;
            g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2d.setPaint(new Color(74,74,86));
            g2d.fillRect(0, 0, centerX * 2, centerY * 2);
            AffineTransform affTransform = g2d.getTransform();
            AffineTransform transform = (AffineTransform) (affTransform.clone());
            g2d.transform(transform.getRotateInstance(-this.getHeadingValue() / 57.29, centerX, centerY));
            g2d.setStroke(new BasicStroke(2));
            g2d.setPaint(Color.WHITE);
            for(int i=0;i<36;i++)
            {
            AffineTransform affineTransform = g2d.getTransform();
            AffineTransform newTransform = (AffineTransform)(affineTransform.clone());
            g2d.transform(newTransform.getRotateInstance((10*i)/57.29,centerX,centerY));
            g2d.drawLine(centerX,3,centerX,18);
            if(i%9==0)
            {
            g2d.setStroke(new BasicStroke(1));
            g2d.drawLine(centerX,60,centerX,centerY);
            g2d.setStroke(new BasicStroke(2));
            g2d.setFont(new Font("Sanserif",Font.PLAIN,20));
            if(i==0) g2d.drawString("N",this.getWidth()/2-5,40);
            if(i==9) g2d.drawString("E",this.getWidth()/2-5,40);
            if(i==18) g2d.drawString("S",this.getWidth()/2-7,40);
            if(i==27) g2d.drawString("W",this.getWidth()/2-8,40);
            }
            else if(i%3==0)
            {
            g2d.setFont(new Font("Sanserif",Font.PLAIN,16));
            if(i>=10)
            g2d.drawString(Integer.toString(i),this.getWidth()/2-8,40);
            else
            g2d.drawString(Integer.toString(i),this.getWidth()/2-5,40);
            }
            g2d.setTransform(affineTransform);
            }
            g2d.setTransform(affTransform);
            g2d.drawImage(img, centerX - 25, centerY - 25, null);
        } catch (Exception ex) {
            Logger.getLogger(HeadingCircular.class.getName()).log(Level.SEVERE, null, ex);
        }

        
    }

Here

Image img

is a image object which holds the image of plane to be drawn in the center.
The problem with this methodology is that I am getting shaky mater. The digits and ticks seems to be shaking as the gauge rotates . I need the gauge to rotate smoothly

In Second methodology I tried using an Image instead of drawing the ticks …

gunjannigam 28 Junior Poster

what do you mean? form has to be display in a period of time or the form has to be filled out in a period of time? If the latter:

1) have a php session variable set to the time of page served.
1) create a javascript countdown function to start on load page.
2) update a tag with the time remaining, say every second.
3) bind the submit button to a js script that checks the state of the countdown - send if in time, message if not.
4) coz forms can be spoofed and js switched off, ensure the form handling page gets the session variable so that anybody messing with the page won't be able to beat the system.

Sorry I meant the the former one. There is a table which displays data from a database. I want that table to be updated once in every minute automatically.

gunjannigam 28 Junior Poster

I have a php page, which has different forms. One of my forms contains a table of data. I want only this form (not the complete page) to be updated in a fixed period of time. How could I do this?

gunjannigam 28 Junior Poster

Ok, will not work.
Try a HTML redirect:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<title>Your Page Title</title>
<meta http-equiv="REFRESH" content="0;url=http://www.pageToRedirect.com"></HEAD>
<BODY>
Optional page text here.
</BODY>
</HTML>

Ok,
I tried to did what u said but still i am facing problems
I have written

header("Content-Disposition: attachment; filename=$filename");
		echo $out;exit;

and then after closing php tag

<html>
<head>
<title>Your Page Title</title>
<meta http-equiv="REFRESH" content="0;url=<?php $path = "http://" . $_SERVER['SERVER_NAME'] . 
		strrev(strstr(strrev($_SERVER['PHP_SELF']),"/"))."export.php"; echo $path;?>></HEAD>
<BODY>
</BODY>
</HTML>

To redirect to my webpage

But instead of outputting the redirect information on my browser it is outputted on my file, and that too before my

$out

data.
What should I do to correct this

gunjannigam 28 Junior Poster

You need to open your attachment in a new window, with javascript:

<script>
window.open("yourFileWithAttachment.php");
</script>

Then in the main window you can redirect to another page with header.

header("Location: newPage.php");

Pardon me, If I am wrong but to use the JavaScript from my current php page I will have to echo it out from my php page and since I would have used echo will the header work??

gunjannigam 28 Junior Poster

Hi,
I am a novice programmer at PHP. I want to redirect my webpage to another webpage. The problem is that First I want to output a file as an attachment and then redirect the web page
I have used this code to output the attachment file

header("Content-Disposition: attachment; filename=$filename");
echo $out;

where

$out

is the text I want to write in my attachment file.
Now Since I have used echo here I cant use

header("location:");

to redirect my webpage. I have also tried to use ob_start() and ob_end_flush() but then my file wont be outputted as an attachment. What should I do?

gunjannigam 28 Junior Poster

Take a look at Java Tutorial - Writing/Saving an Image.

This shows how to save BufferedImage. I dont know how to cast my java.awt.Image to java.awt.image.BufferedImage. If I simply try to use typecasting it gives an error

Exception in thread "main" java.lang.ClassCastException: sun.awt.image.ToolkitImage cannot be cast to java.awt.image.BufferedImage
gunjannigam 28 Junior Poster

Hi Guy

The problem is still not solved, anyone has more ideas?

Thanks heaps

For your first problem where you cannot see the polygon is because you have not entered valid coordinates for polygon. Enter the coordinates of polygon in clockwise or anticlockwise manner.

Secondly to close your frame add this line in you init method

addWindowListener(new WindowAdapter(){
      public void windowClosing(WindowEvent we){
        System.exit(0);
gunjannigam 28 Junior Poster

I have saved generated an image using a byte[] by using

Toolkit.getDefaultToolkit().createImage(image);

where image is a byte[].

The image generated by this is of java.awt.Image instance. Now I want to save this image into my local hard disk as JPEG (the image was decoded as JPEG). How would I do that?.
I am able to draw the image using MediaTracker

gunjannigam 28 Junior Poster

No. That message says you are getting to the DB but that the DB is denying access.


Network problems would be something else, as would mistyped urls. You have either the wrong user, wrong pass, wrong db, or wrong grants.

Ok Now I think you are correct as If i enter wrong server address or wrong user or wrong password or wrong database then its result different error. This error indicates I have problem of grants. I will consult my database hosting vendor about this

gunjannigam 28 Junior Poster

I don't know too much about this PHP thing, but since PHP normally runs on a website, and that website can possibly be in the same place as the db, you have a different dynamic there. Now, all I can tell you is that this message is exactly what you get when the grants are not correct.

Then again, the message says database "db" and your code shows that the database should be "data". Recheck that as well (which would give the same error message since you will not have granted any access to the database "db").

Sorry The error message says could not connect to "data". And PHP webpage is on my local hard disk whereas database is on a database webserver. I have checked the grants on the database located at a webserver. It has remote access login privilege as well as the following privileges
Select
Insert
Update
Delete
Create
Drop
Referances
Index
Alter
Lock Table
Create Temp Table
Do I need to write http://<server ip> or only <serverip> in servername, as in this case server is at another location

gunjannigam 28 Junior Poster

Read the MySQL manual. The user administration portion. Pay close attention to the portion about Grants.

I do have Grants to all the privileges and also grant to connect from any location. I am bale to connect using PHP, but not java, so I am sure have connecting privilege

gunjannigam 28 Junior Poster

I have a database hosted at a remote location. I want to access that database. But I keep getting the error

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Access denied for user 'username'@'%' to database 'db'

This is the code that i have written

Connection con = null;
Class.forName("com.mysql.jdbc.Driver");
String username = "username";
String password = "password";
String server = "67.15.148.40"; //remote server address
String db = "data";
String url = "jdbc:mysql://"+server+"/"+db;
con = DriverManager.getConnection(url, username, password);

The username password I provide is correct as I can access the same databse using PHP and PHPmyAdmin.

gunjannigam 28 Junior Poster

When we use File.getAbsolutePath() we get the path of file as C:\BlahBlah\Blah.txt. But I want the path name as C:/BlahBlah/Blah.txt i.e instead of backward slash "\" i want a forward slash "/" in the path. How to get this. I tried to create a parsefile method.

public String parsePath(String path)
    {
        String parsedString="";        
        String[] arr = path.split("\ ");
        System.out.println(arr.length);
        for(int i=0;i<arr.length-1;i++)
            parsedString=arr[i]+"/";
        parsedString=parsedString+arr[arr.length-1];
        return parsedString;
    }

But it gives illegal space character

String[] arr = path.split("\");

What should I do?

gunjannigam 28 Junior Poster

I am writing some data to a file using FileWriter and BufferedWriter. I want that while writing in the file if somebody else wants to open the file in MS Excel, it should open only in read only mode

Here is a snippet of my FileWriter and BufferedWriter

while(true)
                    {
                        String str=Sinput.readLine();
                        String[] arr = str.split(";");
                        System.out.println(str);
                        if(arr[0].compareTo("$$")==0)
                        {
                            File file = new File(arr[1]+".txt");
                            FileWriter fstream = new FileWriter(file, true);
                            BufferedWriter out = new BufferedWriter(fstream);
                            dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
                            Date date = new Date();
                            out.write("\n"+dateFormat.format(date));
                            for(int i=1;i<6;i++)
                            {
                                out.write("\t"+arr[i]);
                            }
                            out.close();
                            }
                        }

Currently, When I try to open the file in MS Excel it opens in normal mode and due to which my program is not able to write in file and gives an excepton. What should I do?

gunjannigam 28 Junior Poster

Sorry, got it sorted out. Had firewall problem at the Client side.

gunjannigam 28 Junior Poster

port forwarding .

I was thinking the same. Tried to did that also but it didnt work. Here is what I have done till now
Server Code

//The server code Server.java:



/**
 * This is to help people to write Client server application
 *  I tried to make it as simple as possible... the client connect to the server
 *  the client send a String to the server the server returns it in UPPERCASE thats all
 */
import java.io.*;
import java.net.*;
public class Server {

	// the socket used by the server
	private ServerSocket serverSocket;
	// server constructor
	Server(int port) {

		/* create socket server and wait for connection requests */
		try
		{
			serverSocket = new ServerSocket(port);
			System.out.println("Server waiting for client on port " + serverSocket.getLocalPort());

			while(true)
			{
				Socket socket = serverSocket.accept();  // accept connection
				System.out.println("New client asked for a connection");
				TcpThread t = new TcpThread(socket);    // make a thread of it
				System.out.println("Starting a thread for a new Client");
				t.start();
			}
		}
		catch (IOException e) {
			System.out.println("Exception on new ServerSocket: " + e);
		}
	}

//	you must "run" server to have the server run as a console application
	public static void main(String[] arg) {
		// start server on port 1500
		new Server(1500);
	}

	/** One instance of this thread will run for each client */
	class TcpThread extends Thread {
		// the socket where to listen/talk
		Socket socket;
		ObjectInputStream Sinput;
		ObjectOutputStream Soutput;

		TcpThread(Socket socket) {
			this.socket = socket;
		}
		public void run() {
			/* Creating both Data …
gunjannigam 28 Junior Poster

Is it possible to access a TCP server running outside our LAN through internet? I thought we could use the router IP Addess(which I got from whatismyip.com) in the class Socket Constructor

Socket(InetAddress address, int port)

. But client wasn't able to find the server. Has anybody successfully achieved this before?

gunjannigam 28 Junior Poster

I want to Run a ftp server on my machine. My FTP Client will send the data to FTP Server (not a file but byte data). The FTP Server should listen to the data, store it in a file on the local hard disk. How can I wrote a code in JAVA to configure the server to receive data from client and store it in the file

gunjannigam 28 Junior Poster

I have old Toshiba Satellite A-80 Laptop with XP Home. I want to format my system and install Windows XP again. The problem is that my CD/DVD ROM is not functioning. I dont have an option to boot from USB in my BIOS. I dont want to purchase USB CD ROM. My BIOS has an option to boot from LAN. I surfed on net on how to boot and install xp from net, i found something about RIS Server and PXE, but I could understand nothing out of them. I dont have a Windows Server Machine. I have another machine with Win XP SP2 and Ubuntu 9.04 installed. I want to use this system to format my laptop. Can somebody guide me on how to format my laptop using another system without Windows 2003 RIS server.

gunjannigam 28 Junior Poster

Google the Java Event Dispatch Thread and read about Swing threads.
Your repaint() calls won't do anything until your event method completes, even if it sleeps in the meantime..

Thanks for your reply. I tried to solve it out by creating a new class java.util.Timer which will add the data and call the repaint periodically but that is also not working.
What are your suggestions on how to overcome this problem

gunjannigam 28 Junior Poster

I have a class which extends JPanel and implements ActionListener.
I am having 2 menuItem. When I implemented the abstract method actionPerformed(ActionEvent e) and used repaint if the event source are the menuItem paint method is not called. What can be the possible reasons?

This is what I am doing inside the ActionListener implemantation

FileInputStream fstream = null;
            try {
                JFileChooser fc = new JFileChooser();
                int returnVal = fc.showOpenDialog(frame);
                File file1 = null;
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    file1 = fc.getSelectedFile();
                }
                fstream = new FileInputStream(file1);
                br = new BufferedReader(new InputStreamReader(new DataInputStream(fstream)));
                String str;
                while ((str = br.readLine()) != null) {
                     this.repaint();
                    String[] strarr = str.split(",");
                    
                    if (strarr[0].trim().equals("$GPGGA")) {
                        //System.out.println(str);
                        String latstringint = strarr[2].trim().substring(0, 2);
                        double latstringdec = Double.parseDouble(strarr[2].trim().substring(2)) / 60;
                        if (strarr[3].trim().equals("N")) {
                            Lat = Integer.parseInt(latstringint) + latstringdec;
                        } else {
                            Lat = -(Integer.parseInt(latstringint) + latstringdec);
                        }
                        String lonstringint = strarr[4].trim().substring(0, 3);
                        double lonstringdec = Double.parseDouble(strarr[4].trim().substring(3)) / 60;
                        if (strarr[5].trim().equals("E")) {
                            Lon = Integer.parseInt(lonstringint) + lonstringdec;
                        } else {
                            Lon = -(Integer.parseInt(lonstringint) + lonstringdec);
                        }
                        System.out.println(Lat+"\t"+Lon);
                        //pos[0]= Lat;
                        //pos[1]= Lon;
                        //path.add(pos);
                                                 
                        this.repaint();
                        Thread.sleep(250);
                        
                    }
                    if (strarr[0].trim().equals("$GPVTG")) {
                        heading = Double.parseDouble(strarr[1]);
                        sog = Double.parseDouble(strarr[7]);
                        this.repaint();
                    }
                }
            } catch (Exception ex) {
                Logger.getLogger(MovingMap.class.getName()).log(Level.SEVERE, null, ex);
            }
gunjannigam 28 Junior Poster

hello can you help me i want to make my program to executable file is there a software for this to create a jar file?...hoping for your positive responds...

IDE like netbeans create your Jar file when you build your peoject.
This will help you

gunjannigam 28 Junior Poster

I want to Edit the Title of Save Dialog Box in JFileChooser from Save to Something Else. How is it possible?

gunjannigam 28 Junior Poster

There is no "override zooming and panning funtion", you'll have to write those yourself (or maybe you can find some library that implements them).

Not that hard to do, but needs some mental juggling to get the right ideas settled with how to implement them (and no, I am not going to give you the code because not only don't I have it but if I did it would probably not be mine to give away).

JFreeChart has Zooming and panning methods implemented already. You need to set you Domain Axis pannable and You can set your chartPanel zoomable by mouswheel as well as by mouse click. All this is implemented already.
Therefore I need to override those methods with my code which will be doing theese functions. I dont know those menthods.
(I never needed a code but a guided help or suggestions on how to implement it. Thats what this forum is for.)

gunjannigam 28 Junior Poster

what "is not good"?
That amount of data is utterly ridiculous to plot in one graph, no library you're going to find is going to do well with it (and JFreeChart is probably the best one out there).
Filter the data to a more reasonable few hundred points, and you'll get far better performance.
When zooming in or out, filter a different window to that same number of points.

No charting library is going to do that for you, that's all in the code that provides data to the charting library for display, code you have to provide.

By not good meant its taking a longer time to response

I was also thinking of doing the same as u suggested. Do u know how to override zooming and panning function in JFreeChart?

gunjannigam 28 Junior Poster

Hi,
I need a charting API which can plot static Line Graph for 300 million points. API should support zooming and panning of axes comfortably after plotting 300 million points. I tried with JFreechart but the result is not good for even 100 million points. Does anybody have any Idea of a API which can plot 300 million points Line Graph

gunjannigam 28 Junior Poster

I have made a few change in your BigInteger class.
Probably this might not be the most efficient way, but its working perfectly fine. I will try to make it better on weekend

package pkg;



import java.util.Scanner;


    public class BigInteger {



        private int[]  NumC;
        private int[]  NumD;
        private int[] result;

        public BigInteger(){

            NumC   = null;
            NumD   = null;
            result = null;

        }//Assessor


        public void Input(){

            Scanner keyboard = new Scanner(System.in);
            String aa;
            String bb;
            System.out.println();
            System.out.print("Enter First Number: ");
            aa = keyboard.nextLine();
            NumC = convertArray(aa);
            setNumC(NumC);


            System.out.print("Enter Second Number: ");
            bb = keyboard.nextLine();
            NumD = convertArray(bb);
            setNumD(NumD);


            System.out.println();
            System.out.print("   ");
            print(NumC);
            System.out.print(" + ");
            print(NumD);
            System.out.print(" = ");
            Add(NumC,NumD);




        }// Input


        public BigInteger(int[] a,
                          int[] b,
                          int[] c){

            this.NumC   = a;
            this.NumD   = b;
            this.result = c;

        }//Constructor

        public void setNumC (int[] a){

            NumC = a;


        }//Mutator NumC


        public void setNumD (int [] b){

            NumD = b;


        }//Mutator NumD

        public void setResult (int[] c){

            result = c;

        }//Mutator NumC

        public static int[] convertArray(String b){

            int[]arr = new int[b.length()];
            
                for (int i = 0; i < b.length(); i++){

                arr[i] = Character.digit(b.charAt(i),10);

		}

            return arr;


          }//end of toArray

        public static void flipArray(int[] b) {
            int left  = 0;
            int right = b.length-1;

            while (left < right) {

                int temp = b[left];
                b[left]  = b[right];
                b[right] = temp;

                left++;
                right--;
            }
        }//FilpArray

        public void Add (int[]a,int[]b){

            int sum = 0;
            //Swap(a,b);// makes b[] the smaller array
            flipArray(a); // filps array
            flipArray(b); // 123 becomes 321
            int[] arr1,arr2;
            if(a.length<b.length)
            {
                arr1 = …
gunjannigam 28 Junior Poster

I fixed the swap method, but even tho what you had correct the additional number, it doesn't carry the one to the next number.

Output:

Enter First Number: 99999
Enter Second Number: 1
99999 + 1 = 99990

Enter First Number: 9
Enter Second Number: 11111
9 + 11111 = 11110

Well it runs perfectly on my system. The carrry part is happening. Please post your complete code so that I can look what is happening