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
The attachment preview is chopped off after the first 10 KB. Please download the entire file.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package pathplanning;
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
{
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);
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);
g2d.fillOval((int)point1.getX()-3, (int)point1.getY()-3, 6,6);
g2d.fillOval((int)point2.getX()-3, (int)point2.getY()-3, 6,6);
//g2d.drawLine((int)point1.getX(),(int)point1.getY(),(int)point2.getX(),(int)point2.getY());
double radius = point2.distance(point1)/2;
g2d.drawOval((int)(point1.getX()-radius), (int)(point1.getY()-radius),(int)(2*radius), (int) (2 * radius));
g2d.drawOval((int)(point2.getX()-radius), (int)(point2.getY()-radius),(int)(2*radius), (int) (2 * radius));
}
for(int i=0;i<ringList.size();i++)
{
ArrayList<Point> pointList = ringList.get(i);
Point point1 = pointList.get(0);
Point point2 = pointList.get(1);
Point point3 = pointList.get(2);
double radius = point1.distance(point3);
g2d.setColor(Color.white);
g2d.fillOval((int)point1.getX()-3, (int)point1.getY()-3, 6,6);
g2d.fillOval((int)point2.getX()-3, (int)point2.getY()-3, 6,6);
//g2d.drawLine((int)point1.getX(),(int)point1.getY(),(int)point2.getX(),(int)point2.getY());
double deltaX= point2.getX()-point1.getX();
double deltaY= point2.getY()-point1.getY();
double theta = Math.atan2(deltaY, deltaX);
//g2d.drawArc(i, i, i, i, ABORT, ABORT)
g2d.drawArc((int)(point1.getX()-radius), (int)(point1.getY()-radius),(int)(2*radius), (int) (2 * radius), 90-(int) Math.toDegrees(theta),180);
g2d.drawArc((int)(point2.getX()-radius), (int)(point2.getY()-radius),(int)(2*radius), (int) (2 * radius),90-(int) Math.toDegrees(theta),-180);
int X1 = (int)(point1.getX()-radius*Math.cos(Math.PI/2+theta));
int Y1 = (int)(point1.getY()-radius*Math.sin(Math.PI/2+theta));
int X2 = (int)(point2.getX()-radius*Math.cos(Math.PI/2+theta));
int Y2 = (int)(point2.getY()-radius*Math.sin(Math.PI/2+theta));
int X3 = (int)(point1.getX()+radius*Math.cos(Math.PI/2+theta));
int Y3 = (int)(point1.getY()+radius*Math.sin(Math.PI/2+theta));
int X4 = (int)(point2.getX()+radius*Math.cos(Math.PI/2+theta));
int Y4 = (int)(point2.getY()+radius*Math.sin(Math.PI/2+theta));
g2d.drawLine(X1,Y1,X2,Y2);
g2d.drawLine(X3,Y3,X4,Y4);
}
if(!eightPoints.isEmpty() && currentFig ==2)
{
g2d.setColor(Color.white);
for(int i=0;i<eightPoints.size();i++)
{
Point currPoint = eightPoints.get(i);
g2d.fillOval((int)currPoint.getX()-3, (int)currPoint.getY()-3, 6,6);
}
}
if(!ringPoints.isEmpty() && currentFig ==3)
{
g2d.setColor(Color.white);
for(int i=0;i<ringPoints.size();i++)
{
Point currPoint = ringPoints.get(i);
g2d.fillOval((int)currPoint.getX()-3, (int)currPoint.getY()-3, 6,6);
}
}
if(ringPoints.size()==2 && currentPoint != null)
{
g2d.setColor(Color.white);
g2d.drawLine((int)ringPoints.get(0).getX(), (int)ringPoints.get(0).getY(), (int)currentPoint.getX(), (int) currentPoint.getY());
}
if(loitrePoints.size()==1 && currentPoint != null)
{
g2d.setColor(Color.white);
g2d.drawLine((int)loitrePoints.get(0).getX(), (int)loitrePoints.get(0).getY(), (int)currentPoint.getX(), (int) currentPoint.getY());
}
g2d.setColor(Color.black);
g2d.fillRect(0,(int)screenSize.getHeight()-20,(int)screenSize.getWidth(),20);
g2d.setFont(new Font("Arial",Font.BOLD,14));
g2d.setColor(Color.white);
g2d.drawString(statusBar, 10,(int)screenSize.getHeight()-5);
g2d.drawString(mouseCoord, (int)screenSize.getWidth()-100,(int)screenSize.getHeight()-5);
}
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 so the popup menu can come up.
PopupListener popupListener = new PopupListener(popup);
this.addMouseListener(popupListener);
this.addMouseMotionListener(popupListener);
this.addKeyListener(popupListener);
}
public void actionPerformed(ActionEvent e) {
//throw new UnsupportedOperationException("Not supported yet.");
//System.out.println(e);
if(e.getActionCommand().equalsIgnoreCase("Loitre"))
{
statusBar="Select Center";
loitrePoints = new ArrayList<Point>();
repaint();
currentFig = 1;
}
else if(e.getActionCommand().equalsIgnoreCase("Eight"))
{
statusBar="Select First Point";
eightPoints = new ArrayList<Point>();
repaint();
currentFig = 2;
}
else if(e.getActionCommand().equalsIgnoreCase("Ring"))
{
statusBar="Select First Point";
ringPoints = new ArrayList<Point>();
repaint();
currentFig = 3;
}
}
class PopupListener implements MouseListener,MouseMotionListener,KeyListener {
JPopupMenu popup;
PopupListener(JPopupMenu popupMenu) {
popup = popupMenu;
}
public void mousePressed(MouseEvent e) {
//System.out.println(e.getButton()+"\t"+currentFig);
if(e.getButton()==MouseEvent.BUTTON1 && currentFig==2)
{
//System.out.println(e.getButton());
if(eightPoints.isEmpty())
{
eightPoints.add(e.getPoint());
statusBar="Select Second Point";
repaint();
}
else
{
eightPoints.add(e.getPoint());
eightList.add(eightPoints);
statusBar="Ready";
repaint();
currentFig=0;
}
}
if(e.getButton()==MouseEvent.BUTTON1 && currentFig==3)
{
//System.out.println(e.getButton());
if(ringPoints.isEmpty())
{
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
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
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
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 translateImageX = (int) (700*translateX/0.0300407409668);
int translateImageY = (int) (500*translateY/0.0202768935753);
/* Draw the image, applying the filter */
AffineTransform transform1 = AffineTransform.getRotateInstance(Math.toRadians(-heading), originX, originY);
AffineTransform origTransform = g2d.getTransform();
g2d.setTransform(transform1);
for(int i=0;i<=4;i++)
{
ArrayList<BufferedImage> rowList = imageList.get(i);
for(int j=0;j<=4;j++)
{
BufferedImage mapImg = rowList.get(j);
//System.out.println(temp+"\t"+imageName);
//BufferedImage mapImg = ImageIO.read(getClass().getResource(imageName));//loadTranslucentImage(imageName, 0.5f);
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
g2d.drawImage(mapImg, originX - translateImageX+(i-2)*700, originY - translateImageY+(j-2)*500, null);
g2d.setComposite(origComposite);
}
}
g2d.setTransform(origTransform);
} catch (Exception ex) {
Logger.getLogger(Example.class.getName()).log(Level.SEVERE, null, ex);
}
}
public ArrayList<ArrayList<BufferedImage>> createImageBuffer(String currentUrl)
{
String[] imageMapArray = currentUrl.split("_");
ArrayList<ArrayList<BufferedImage>> returnList = new ArrayList<ArrayList<BufferedImage>>();
BufferedImage mapImg=null;
for(int i=-2;i<=2;i++)
{
ArrayList<BufferedImage> rowList = new ArrayList<BufferedImage>();
for(int j=-2;j<=2;j++)
{
if(imageMapArray.length==3)
{
try {
int tempY = Integer.parseInt(imageMapArray[2].substring(0, imageMapArray[2].length() - 4)) + j;
int tempX = Integer.parseInt(imageMapArray[1]) + i;
String imageName;
if (tempY <= 19 && tempY >= 0 && tempX <= 6 && tempX >= 0) {
imageName = imageMapArray[0] + "_" + tempX + "_" + tempY + ".png";
} else {
imageName = "/images/map/NA.png";
}
//RenderedOp rImage = JAI.create("url", getClass().getResource(imageName));
//mapImg = rImage.getAsBufferedImage();
mapImg = ImageIO.read(getClass().getResource(imageName));
} catch (Exception ex) {
Logger.getLogger(Example.class.getName()).log(Level.SEVERE, null, ex);
}
}
else
{
try {
mapImg = ImageIO.read(getClass().getResource("/images/map/NA.png"));
} catch (IOException ex) {
Logger.getLogger(Example.class.getName()).log(Level.SEVERE, null, ex);
}
}
rowList.add(mapImg);
}
returnList.add(rowList);
}
return returnList;
}
public class ImageLoader extends Thread
{
public void run()
{
imageList = createImageBuffer(oldMapImage);
}
}
public class UDPClient extends Thread
{
JPanel panel;
ArrayList placeInRange;
ImageLoader il;
float oldLat=0, oldLon=0;
public UDPClient(JPanel panel)
{
this.panel = panel;
il = new ImageLoader();
//ilb.start();
placeInRange = new ArrayList();
}
public String getImage(double lat, double lon)
{
double latDiff = 19.2983446067557-lat;
double lonDiff = lon - 72.7742958068848;
int latImageNo = (int) Math.ceil(latDiff/0.0202768935753);
int lonImageNo = (int) Math.ceil(lonDiff/0.0300407409668);
String mapImageName = "/images/map/mumbai_" + lonImageNo + "_" + latImageNo + ".png";
//System.out.println(mapImageName);
return mapImageName;
}
public void run()
{
DatagramPacket packet;
DatagramSocket socket = null;
byte[] buff = new byte[256];
packet = new DatagramPacket(buff,buff.length);
try {
socket = new DatagramSocket(5001);
socket.setSoTimeout(5000);
} catch (SocketException ex) {
ex.printStackTrace();
}catch (IOException ex) {
ex.printStackTrace();
}
while(true)
{
try {
socket.receive(packet);
} catch (IOException ex) {
ex.printStackTrace();
}
String received = new String(packet.getData(), 0, packet.getLength());
//System.out.println("RECEIVED: " + received);
if(received.startsWith("$INS"))
{
String[] strArray = received.split(";");
if(strArray.length==7)
{
float lat=Float.parseFloat(strArray[4]);
float lon = Float.parseFloat(strArray[5]);
//heading = Float.parseFloat(strArray[3]);
//System.out.println((oldLat-lat)*110+"\t"+(oldLon-lon)*110);
currentLat=lat;
currentLon = lon;
mapImage = getImage(lat,lon);
if(mapImage.compareToIgnoreCase(oldMapImage)!=0)
{
System.out.println("IN: "+System.currentTimeMillis());
oldMapImage = mapImage;
il.run();
System.out.println("OUT: "+System.currentTimeMillis());
}
panel.repaint(0);
}
}
}
}
}
}
The attachment preview is chopped off after the first 10 KB. Please download the entire file.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author gunjan
*/
public class UDPBroadCastServer
{
DatagramSocket serverSocket;
int clientPort;
byte[] addr = {(byte) 255, (byte) 255, (byte) 255, (byte) 255};
InetAddress address;
public static void main(String[] args)
{
UDPBroadCastServer server = new UDPBroadCastServer(5000,5001);
}
public UDPBroadCastServer(int serverPort,int clientPort)
{
try {
serverSocket = new DatagramSocket(serverPort);
serverSocket.setBroadcast(true);
serverSocket.setSoTimeout(1000*10);
this.clientPort= clientPort;
address = InetAddress.getByAddress(addr);
DataGenerator ins = new DataGenerator(50,0);
ins.start();
DataGenerator nav = new DataGenerator(200,1);
nav.start();
DataGenerator gps = new DataGenerator(50,2);
gps.start();
DataGenerator air = new DataGenerator(50,3);
air.start();
DataGenerator clr = new DataGenerator(500,4);
clr.start();
DataGenerator knt = new DataGenerator(60,5);
knt.start();
DataGenerator mag = new DataGenerator(250,6);
mag.start();
DataGenerator cal = new DataGenerator(80,7);
cal.start();
/*DataGenerator qry = new DataGenerator(1000,8);
qry.start();*/
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(false);
} catch (UnknownHostException ex) {
Logger.getLogger(UDPBroadCastServer.class.getName()).log(Level.SEVERE, null, ex);
} catch (SocketException ex) {
Logger.getLogger(UDPBroadCastServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
class DataGenerator extends Thread
{
private int stringType;
private DatagramPacket packet;
private byte[] buf = new byte[256];
float roll=0,pitch=0,heading=0,height=0,airspeed=0,pressure=100,verticalSpeed=-50,lat=18.92f,lon=72.780f;
int altitude=0000;
int time;
public DataGenerator(int time,int type)
{
this.time = time;
stringType = type;
}
public void run()
{
while(true)
{
try {
StringBuilder sb = new StringBuilder();
DecimalFormat formatter = new DecimalFormat("#.#####");
Random number = new Random();
switch (stringType) {
case 0:
sb.append("$INS;");
sb.append(formatter.format(roll));
sb.append(";");
sb.append(formatter.format(pitch));
sb.append(";");
sb.append(formatter.format(heading));
sb.append(";");
roll += 0.1f;
pitch += 0.1f;
heading +=0.15f;
if(roll>=180)
roll=-180;
if(pitch>30)
pitch=-30;
if(heading>=360)
heading=0;
sb.append(formatter.format(lat));
sb.append(";");
sb.append(formatter.format(lon));
sb.append(";");
lat +=0.00004*number.nextFloat();
lon +=0.00002*number.nextFloat();
if(lat>=19.298)
lat=18.92f;
if(lon>=72.954)
lon=72.780f;
sb.append(formatter.format(-180 + number.nextFloat() * 360));
sb.append(";");
//System.out.println("SENT: "+sb.toString());
buf = sb.toString().getBytes();
packet = new DatagramPacket(buf, buf.length, address, clientPort);
serverSocket.send(packet);
break;
case 1:
sb.append("$NAV;");
//System.out.println("SENT: "+sb.toString());
buf = sb.toString().getBytes();
packet = new DatagramPacket(buf, buf.length, address, clientPort);
serverSocket.send(packet);
break;
case 2:
sb.append("$GPS;");
for (int i = 0; i < 4; i++) {
sb.append(formatter.format(-180 + number.nextFloat() * 360));
sb.append(";");
}
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
sb.append(dateFormatter.format(new Date()));
//System.out.println("SENT: "+sb.toString());
buf = sb.toString().getBytes();
packet = new DatagramPacket(buf, buf.length, address, clientPort);
serverSocket.send(packet);
break;
case 3:
sb.append("$AIR;");
sb.append(formatter.format(airspeed));
sb.append(";");
airspeed += 0.2f;
if(airspeed>=100)
airspeed=0;
altitude+=100;
if(altitude>=99999)
altitude=00000;
sb.append(altitude);
sb.append(";");
sb.append(formatter.format(number.nextFloat() * 180));
sb.append(";");
pressure+=number.nextFloat();
if(pressure>999.9)
pressure=0;
sb.append(formatter.format(pressure));
sb.append(";");
//System.out.println("SENT: "+sb.toString());
buf = sb.toString().getBytes();
packet = new DatagramPacket(buf, buf.length, address, clientPort);
serverSocket.send(packet);
break;
case 4:
sb.append("$CLR;");
//System.out.println("SENT: "+sb.toString());
buf = sb.toString().getBytes();
packet = new DatagramPacket(buf, buf.length, address, clientPort);
serverSocket.send(packet);
break;
case 5:
sb.append("$KNT;");
for (int i = 0; i < 8; i++) {
sb.append(formatter.format(number.nextFloat() * 180));
sb.append(";");
}
verticalSpeed+=number.nextFloat()*0.1;
if(verticalSpeed>=50)
verticalSpeed = -50;
sb.append(formatter.format(verticalSpeed));
sb.append(";");
//System.out.println("SENT: "+sb.toString());
buf = sb.toString().getBytes();
packet = new DatagramPacket(buf, buf.length, address, clientPort);
serverSocket.send(packet);
break;
case 6:
sb.append("$MAG;");
for (int i = 0; i < 4; i++) {
sb.append(formatter.format(number.nextFloat() * 180));
sb.append(";");
}
//System.out.println("SENT: "+sb.toString());
buf = sb.toString().getBytes();
packet = new DatagramPacket(buf, buf.length, address, clientPort);
serverSocket.send(packet);
break;
case 7:
sb.append("$CAL;");
//System.out.println("SENT: "+sb.toString());
buf = sb.toString().getBytes();
packet = new DatagramPacket(buf, buf.length, address, clientPort);
serverSocket.send(packet);
break;
default:
sb.append("$QRY;");
//System.out.println("SENT: "+sb.toString());
buf = sb.toString().getBytes();
packet = new DatagramPacket(buf, buf.length, address, clientPort);
serverSocket.send(packet);
packet = new DatagramPacket(buf, buf.length);
serverSocket.receive(packet);
String received = new String(packet.getData(), 0, packet.getLength());
System.out.println("RECEIVED: " + received);
break;
}
Thread.sleep(time);
} catch (InterruptedException ex) {
Logger.getLogger(UDPBroadCastServer.class.getName()).
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 theil (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 thepaint()
method and overridepaintComponent()
instead ofpaint()
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() …

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JLabel;
import javax.swing.JPanel;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Gunjan Nigam
*/
public class HeadingCircular extends JPanel{
private float headingValue;
int centerX,centerY;
Image img;
JLabel label;
Font font16,font20;
BasicStroke stroke1,stroke2;
public HeadingCircular(int size,String imagename)
{
super(null);
try {
this.setSize(size, size);
img = ImageIO.read(getClass().getResource(imagename));
centerX = size / 2;
centerY = size / 2;
setOpaque(false);
font16 = new Font("Sanserif",Font.PLAIN,16);
font20 = new Font("Sanserif",Font.PLAIN,20);
stroke1 = new BasicStroke(1);
stroke2 = new BasicStroke(2);
} catch (IOException ex) {
Logger.getLogger(HeadingCircular.class.getName()).log(Level.SEVERE, null, ex);
}
}
public HeadingCircular(String imagename)
{
this(300,imagename);
}
@Override
public void paintComponent(Graphics g)
{
try {
centerX = this.getWidth() / 2;
centerY = this.getHeight() / 2;
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.setPaint(new Color(74,74,86));
g2d.fillRect(0, 0, centerX * 2, centerY * 2);
g2d.setStroke(stroke2);
g2d.setPaint(Color.WHITE);
AffineTransform affTransform = g2d.getTransform();
g2d.transform(affTransform.getRotateInstance(-this.getHeadingValue() / 57.29, centerX, centerY));
for(int i=0;i<36;i++)
{
AffineTransform affineTransform = g2d.getTransform();
g2d.transform(affineTransform.getRotateInstance((10*i)/57.29,centerX,centerY));
g2d.drawLine(centerX,3,centerX,18);
if(i%9==0)
{
g2d.setStroke(stroke1);
g2d.drawLine(centerX,60,centerX,centerY);
g2d.setStroke(stroke2);
g2d.setFont(font20);
if(i==0) g2d.drawString("N",centerX-5,40);
if(i==9) g2d.drawString("E",centerX-5,40);
if(i==18) g2d.drawString("S",centerX-7,40);
if(i==27) g2d.drawString("W",centerX-8,40);
}
else if(i%3==0)
{
g2d.setFont(font16);
if(i>=10)
g2d.drawString(Integer.toString(i),centerX-8,40);
else
g2d.drawString(Integer.toString(i),centerX-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);
}
}
/**
* @return the headingValue
*/
public float getHeadingValue() {
return headingValue;
}
/**
* @param headingValue the headingValue to set
*/
public void setHeadingValue(float headingValue) {
this.headingValue = headingValue;
}
}
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Gunjan Nigam
*/
public class Main extends JPanel{
DatagramSocket dsocket;
float[] pack_rec = new float[25];
byte[] buffer = new byte[256];
byte[] read_float = new byte[4];
HeadingCircular hc;
public Main()
{
super(null);
JFrame frame = new JFrame();
frame.setSize(1024,768);
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("check");
menuBar.add(menu);
frame.setJMenuBar(menuBar);
frame.getContentPane().add(this);
hc= new HeadingCircular("/images/plane.png");
this.add(hc);
hc.setBounds(0,300,300,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
try {
dsocket = new DatagramSocket(49001);
dsocket.setReceiveBufferSize(1);
} catch (SocketException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
Timer time = new Timer();
time.scheduleAtFixedRate(new dataReceive(), 0, 25);
}
public static void main(String[] args)
{
new Main();
}
public class dataReceive extends TimerTask
{
long time = System.currentTimeMillis();
public void run() {
long diff= System.currentTimeMillis()-time;
time = System.currentTimeMillis();
UDP();
hc.repaint();
System.out.println(diff);
}
}
public void UDP()
{
try
{
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
dsocket.setSoTimeout(1000*60);
dsocket.receive(packet);
DataInputStream data_stream = new DataInputStream(new ByteArrayInputStream(packet.getData()));
for(int i=0;i<25;i++)
{
read_float[3]=data_stream.readByte();
read_float[2]=data_stream.readByte();
read_float[1]=data_stream.readByte();
read_float[0]=data_stream.readByte();
DataInputStream data_stream1 = new DataInputStream(new ByteArrayInputStream(read_float));
pack_rec[i]=data_stream1.readFloat();
}
hc.setHeadingValue(pack_rec[2]*57.32f);
}catch(SocketTimeoutException e){JOptionPane.showMessageDialog(null, "Sorry Communication Failed and No Data Received");}
catch (SocketException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
class UDPClient
{
public UDPClient()
{
java.util.Timer time= new java.util.Timer();
time.scheduleAtFixedRate(new DataGenerator(), 0, 25);
}
public static void main(String args[]) throws Exception
{
new UDPClient();
}
class DataGenerator extends TimerTask
{
long time;
DatagramSocket clientSocket;
InetAddress IPAddress;
int port;
float[] data = new float[25];
byte[] sendData;
public DataGenerator()
{
try {
time = System.currentTimeMillis();
clientSocket = new DatagramSocket();
byte[] serverAddress = {(byte) 192, (byte) 168, (byte) 1, (byte) 48};
IPAddress = InetAddress.getByAddress(serverAddress);
port = 49001;
data[0]=-180;
data[1]=-30/57.32f;
data[3]=-300;
data[4]=-300;
data[5]=-300;
sendData= new byte[100];
} catch (UnknownHostException ex) {
Logger.getLogger(UDPClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (SocketException ex) {
Logger.getLogger(UDPClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void run() {
try {
//System.out.println(data[1]+"\t"+data[2]);
long diff = System.currentTimeMillis() - time;
time = System.currentTimeMillis();
data[0] = data[0]+0.05f;
data[1] = data[1]+(0.025f/57.32f);
data[2] = (data[2] + (0.1f/57.32f)) % (360/57.32f);
data[3] += 0.2f;
data[4] += 0.1f;
data[5] += 0.1f;
data[6] += 0.02f;
data[7] += 0.06f;
data[8] += 0.04f;
data[9] = (data[9] + 1.2f) % 1000;
data[10] = (data[10] + 0.7f) % 150;
for (int i = 11; i < 25; i++) {
data[i] = (float) Math.random();
}
if (data[0] > 180) {
data[0] = -180;
}
if(data[1]>(30/57.32f))
data[1] = -(30/57.32f);
if (data[3] > 300) {
data[3] = -300;
}
if (data[4] > 300) {
data[4] = -300;
}
if (data[5] > 300) {
data[5] = -300;
}
if (data[6] > 1.7) {
data[6] = -1.7f;
}
if (data[7] > 1.7) {
data[7] = -1.7f;
}
if (data[8] > 1.7f) {
data[8] = -1.7f;
}
for (int i = 0; i < 25; i++) {
byte[] byteData = toByta(data[i]);
sendData[4 * i + 0] = byteData[3];
sendData[4 * i + 1] = byteData[2];
sendData[4 * i + 2] = byteData[1];
sendData[4 * i + 3] = byteData[0];
}
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
clientSocket.send(sendPacket);
//System.out.println(diff);
} catch (IOException ex) {
Logger.getLogger(UDPClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
public byte[] toByta(int data) {
return new byte[] {
(byte)((data >> 24) & 0xff),
(byte)((data >> 16) & 0xff),
(byte)((data >> 8) & 0xff),
(byte)((data >> 0) & 0xff),
};
}
public byte[] toByta(float data) {
return toByta(Float.floatToRawIntBits(data));
}
}
}
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 = 99990Enter 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