Scanner br = new Scanner(System.in);
int num = br.nextInt();
Integer a = Integer.valueOf(num);
System.out.println(a.toBinaryString(num));
System.out.println(a.toOctalString(num));
System.out.println(a.toHexString(num));
gunjannigam 28 Junior Poster
Thanks, will try the SAVE_DIALOG advice immediatly.
I'm talking about the "Open" and "Cancel" buttons.
There is a checkbox in properties controlButtonsAreShown. You can uncheck it to remove the buttons
gunjannigam 28 Junior Poster
I am using the netbeans gui builder.
I dragged a filechooser onto my frame, and it does almost everything I want it to do.
How do I remove the buttons? I dont need them - the user just has to select a file, or type in a file name, the buttons are unused.
Also, if a user types in a file name in the "File name" Text field, how do I get that file name?
I tried "fileChooser.getSelectedFile()" but that only returns a value if the user has actually highlighted an existing file. The idea is to get the file name the the user entered and create a new file with that name.
Anyone have an idea?
Which buttons are you talking about?
If you want to create a new File with given name then You need to use the SAVE_DIALOG mode (which can be set in Dialog type in properties of that fileChooser) to create a file with the given name
gunjannigam 28 Junior Poster
After forst two lines you can try this.
for(int i=0;i<3;i++)
System.out.println(linha.split(" ")[i]);
gunjannigam 28 Junior Poster
Hi guys, I'm returning this, it is similar to how you percieve dollars, $"32.95" etc. I calculate it in cents which is an int, but the problem is the second half cuts off the 10s of cents part if the number is less than that. eg/ 32.08. Any ideas ? i know i need an if but i cant think how to write it.
public String toString() { return (cents / 100)+ "." + (cents % 100); }
You can either do it by using if then else statement by using this
if((cents%100) < 10)
return (cents / 100)+ "." + "0"+(cents % 100);
else
return (cents / 100)+ "." + "0"+(cents % 100);
You can also you use a Numberformat class.
import java.text.*;
NumberFormat formatter = new DecimalFormat("0.00");
return (formatter.format(cents/100.0));
gunjannigam 28 Junior Poster
I have no idea what to do, it keeps on saying can not find constructor Time(int, int)
here is my Patient Class
//Patient Class store patient details such as name, age /* * Field declaration for patient, which stores each input to indicated type * p stands for patient (abbreviation) * Task 2.1 */ public class Patient { private int pReference; private String pName; private String gpName; private int pDateD; private int pDateM; private int pDateY; public static Time pArrived; public static Time pTreated; // Constrcutor resets objects // Each field is set // Task 2.2 public Patient (int refre, String name, String gp, int day, int month, int year) { pDateD = day; pDateM = month; pDateY = year; pArrived = null; pTreated = null; pReference = refre; gpName = gp; pName = name; } public void SetArrivalTime (int hour, int minute) { SetArrivalTime(hour, minute); } public Patient() { super(); } // Accessor returns patient reference // Task 2.3 public int getPatientNo() { return pReference; } // Accessor returns GP name given to gpName // Task 2.3 public String getGPName() { return gpName; } // Accessor returns date of birth in correct format // Task 2.3 public String getDOB() { char dash = '/'; return "" + pDateD + dash + pDateM + dash + pDateY; } // Mutator setting time // Task 2.4 public void setArrivalTime (int hour, int minute) { pArrived = new Time (hour, minute); //error happens here } public void setTreatmentStart(int hour, int minute) { …
gunjannigam 28 Junior Poster
I have a 2D image of a map. What I want to do is
1) Paint this image in a 3D Canvas. And then rotate it with the help of mouse
2) Secondly do some path planning, i.e If I select 2-3 points in space on top of that map I need to join them using a line or some curve. This points will not be on the same plane.
I dont have much idea about the 3D graphics so can anybody suggest where and what to start reading to solve out the problem
gunjannigam 28 Junior Poster
Remove line 81 to 88( the write code)
Edit line where u write to file as
outputStream.println(seatList.get(count)?1:0);
Here is the complete code of your ReservationSystem
package airlinereservationsystem;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import java.io.PrintWriter;
import java.io.FileNotFoundException;
import java.util.ArrayList;
public class ReservationSystem extends JFrame implements ActionListener
{
private int SC = 12;
private JLabel userInstructions = new JLabel("Click the button" +
" representing the seat you want " +
"to reserve the seat");
private JButton[] buttonArray = new JButton[12];
private JButton exitButton = new JButton("Click to Exit");
private ArrayList<Boolean> seatList = new ArrayList<Boolean>(SC);
String fileName = "c:/temp/projectData.text";
public ReservationSystem()
{
super("Air Maybe Airline Reservation System");
//addWindowListener(new WindowDestroyer( ));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPane = getContentPane( );
contentPane.setLayout(new BorderLayout( ));
JPanel InstructionsPanel = new JPanel( );
JPanel buttonPanel = new JPanel( );
JPanel exitPanel = new JPanel( );
//add listener to the exit button
exitButton.addActionListener(this);
InstructionsPanel.add(userInstructions);
contentPane.add(InstructionsPanel, BorderLayout.NORTH);
buttonPanel.setLayout(new GridLayout(4,3));
for (int i=0;i<SC;i++)
{
buttonArray[i] = new JButton("Seat " + (i+1));
buttonArray[i].addActionListener(this);
buttonPanel.add(buttonArray[i]);
seatList.add(i, true);
}
contentPane.add(buttonPanel,BorderLayout.CENTER);
exitPanel.add(exitButton);
contentPane.add(exitPanel,BorderLayout.SOUTH);
pack();
}
@SuppressWarnings("static-access")
public void actionPerformed(ActionEvent e)
{
String confirm = "Are you sure you want to book this seat?";
int write;
for (int i = 0; i < SC; i++)
{
if (e.getActionCommand( ).equals("Seat " +(i + 1)))
{
int choice = JOptionPane.showConfirmDialog(null, confirm, "Confirm",
JOptionPane.YES_NO_OPTION);
if(choice == JOptionPane.YES_OPTION)
{
buttonArray[i].setText("Booked");
seatList.set(i, false);
}
}
if (e.getActionCommand( ).equals("Booked"))
{
JOptionPane.showMessageDialog(null, "This seat is already booked. Please …
TotalHack commented: Very helpful. Solved my issue. +0
gunjannigam 28 Junior Poster
to see the parameters required use javap command with the class file whose method u r looking for......
for this particular problem see the link
http://java.sun.com/j2se/1.4.2/docs/api/java/awt/geom/Arc2D.Float.html
I now what I have to enter to draw an Arc using Arc2D.Float. But I dont know how to calculate those paramemters. It asks for the upper left corner of the ellipse, width and height and the start and extent of arc. I only know its a circular arc therefore it will same width and height as diameter of arc required but I dont know how to calulate the upper left corner of ellipse and start and extent of arc. For this I will probally require the center of the circle whose part is this arc. But I dont know how to do this.
gunjannigam 28 Junior Poster
Append this in your code in main function only
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
And always use code tags while posting code
gunjannigam 28 Junior Poster
How to draw a circluar arc of given radius say 20 passing from two Given points. I have seen the function Arc2D.Float but can figure out how to find the required parameters for the contructor and also for QuadCurve2D cant figure out the control point.
gunjannigam 28 Junior Poster
You can use QuadCurve2D to accomplish the task.It takes two end points as input and a control point for deviation.
The syntax is as follows :
Graphics2D g; QuadCurve2D.Double l = new QuadCurve2D.Double(x0,y0,x1,y1,x2,y2); g.draw(l);
x0,y0 is the first point where line intersects circle and x3,y3 is the other point of line intersection.
x2,y2 is the control point that causes deviation.
How do I calculate the control point. I have been given whats the radius of arc. Also do I have perform all the mathematics to calculate the equation of circle and line then find out their intersection point by solving out the quadratic or is there any other way to get the intersection points.The circle is not centered at origin so its gonna be huge calculation otherwise.
gunjannigam 28 Junior Poster
I have drawn a cirlce and 2 line which intersects the circle using 2D Graphics. Now I want to draw an arc between the intersection point.
The attached pic can show very clearly wht i want. The black portion is drawn. The red part is to be drawn. The radius of arc can vary. But it need to cut the circle at the same point where the line intersects the circle
gunjannigam 28 Junior Poster
My problem statement is to draw a map from the given images whose Latitude and Longitude information is stored in database. Initial point Latitude and Longitude is given and then they will change in every 200 ms. I have to plot a map once and on top of the map I paint the path traveled wrt new changing Latitude and Longitude.
I have plotted the map using JLabel class and then I want to paint upon it. The problem is that in each repaint call old line vanishes and new will draw. I dont want to remove the old line. I have thought of storing all the points in a ArrayList and then appending new points to it and then painting the complete ArrayList after 200 ms. But is there any other more efficient way so that only new line is painted on JLabel and old remains.
Below is certain code I have written to draw the images given the initial images
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.*;
import java.io.*;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import javax.swing.*;
import java.sql.*;
import java.util.ArrayList;
public class MovingObject extends JLabel
{
int centerPointX,centerPointY;
int imageWidth,imageHeight;
float Lat,Lon;
float initLat,initLon;
float oldLat,oldLon;
BufferedImage image;
String image_name,image_name1;
float imageLeftLat,imageLeftLon,imageRightLat,imageRightLon;
JFrame frame;
DatagramPacket packet;
byte[] buffer = new byte[256];
byte[] read_float = new byte[4];
float[] pack_rec = new float[25];
DatagramSocket dsocket;
int img1;
ImageIcon imgicon;
float centerLat,centerLon;
ArrayList ar;
public MovingObject()
{
try {
frame = new JFrame("Map");
frame.add(this); …
gunjannigam 28 Junior Poster
Call paintComponent constructor
Use this as the 1st line of code in paintComponent method
super.paintComponent(g);
gunjannigam 28 Junior Poster
After I ask the user to enter a number here
System.out.println("Enter a number");
number = scan.nextInt();
I would like print the id of each salesperson that exceeded that value and the amount of their sales. I Also want to print the total number of salespeople whose sales exceeded the value entered. So I would think I would need some kind of for loop and several print statements. This is what I am thinking for my for loop.
for (int i=0; number<i; i++)
Line 1 to line 56 is good. After that is where I am trying to put my for loop.//**************************************************************** // Sales.java // // Reads in and stores sales for each of 5 salespeople. Displays // sales entered by salesperson id and total sales for all salespeople. // // **************************************************************** import java.util.Scanner; public class Sales { public static void main(String[] args) { final int SALESPEOPLE = 5; int[] sales = new int[SALESPEOPLE]; int sum; Scanner scan = new Scanner(System.in); for (int i=0; i<sales.length; i++) { System.out.print("Enter sales for salesperson " + (i+1) + ": "); sales[i] = scan.nextInt(); } System.out.println("\nSalesperson Sales"); System.out.println("--------------------"); sum = 0; int maximum = sales[0]; int minimum = sales[0]; int a=1, b=1; for (int i=0; i<sales.length; i++) { if(maximum < sales[i]) { maximum = sales[i]; a = i+1; } if(minimum > sales[i]) { minimum = sales[i]; b = i+1; } System.out.println(" " + (i+1) + " " + sales[i]); sum += sales[i]; } System.out.println("\nTotal sales: " + sum); System.out.println("The …
gunjannigam 28 Junior Poster
After searching for examples on the net, I found this:
Assuming your file is like this:And you run this:
RandomAccessFile raf = new RandomAccessFile("fileName","rw"); FileChannel fc = raf.getChannel(); fc.position(0); fc.write(ByteBuffer.wrap("1234".getBytes())); fc.close(); raf.close();
You will get this:
But if you write this:fc.write(ByteBuffer.wrap("1234567".getBytes()));
You will get this:
Thanks a lot for your suggestion. I also tried this and geting this abnormal behavior. I dont know whats the reason. Can you suggest a reason and how to rectify it . Actually I am writing a file with a blank line in its start, and then counting the no of line written afterward. I have to write an integer,i.e. the no of lines written in the file, in that blank line.Initially I was just writing the newline escape character("\n"). Due to this my next line was getting edited instead of inserting that in blank space. But then I tried to give some space and some tabs at beginning it will write that some no of digits. But if the no is too big it will again overwrite my data......
How to overcome this????
gunjannigam 28 Junior Poster
One suggestion is to read the entire file and then write again what you want at the first line and the write the rest of the data read
Well I also thought but the thing is there are approximately 10000 lines of data, and each line containing 500 bytes of data . Again reading and writing file not be a efficient way. Isn't there any other option of doing that
gunjannigam 28 Junior Poster
I have a file which is already written till some lines. I have a blank line at the start of the file and I want to write in that line using Java.
I thought creating a FileWriter object by using FileWriter(filename, true) and then a BufferedWriter object will start writing from top. But its appending at the end of file. I dont want to destroy my data of file already written. How can I do that.
gunjannigam 28 Junior Poster
I have a toolbar and various buttons in. There is always a dashed line displyad along the borders on last button clicked. Aslo there are some sliders in my panel. When I try to adjust the value of a slider it also has a dashed border. This border is only on the last selected values either buttons or sliders. I dont know what it is called. What I want is that these dashed borders should not be displayed.
You can see in the image what i am talking about
gunjannigam 28 Junior Poster
As per my knowledge if you want to import an external API than that API should be present at \jre\lib\ext jar so that the classes are recognised by the javac or g++ compiler.
gunjannigam 28 Junior Poster
I want to implement the following Task
1) Read till end of file
2) In each Line of the file there is a time mentioned. You need no call a method( code of which I have already written)
3)Wait for the time mentioned in that line of file and then again read the next line of file
I want to implement this code. It will start when I press a start button and can be stopped in the middle if I press a stop button
Also this time delay mentioned mentioned in the file is approximately 70 ms. I want to avoid using Thread.sleep() in an infinite loop
Is there way a to use Timer class to implement the above code.
gunjannigam 28 Junior Poster
I am trying to read from a text file which of size 1 MB, and contains 5000 lines of data.
Following is the code of class which I am using to read from the file
public class PlayFile extends Timer implements ActionListener{
File filename;
BufferedReader out;
//float frameid,prev_frameid;
public PlayFile(File file, int interval)
{
super(interval,null);
FileInputStream fstream = null;
try {
filename = file;
fstream = new FileInputStream(file);
DataInputStream in = new DataInputStream(fstream);
out = new BufferedReader(new InputStreamReader(in));
this.addActionListener(this);
out.readLine();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
fstream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public void actionPerformed(ActionEvent e)
{
try {
if(out.ready())
{
String br = out.readLine();
String[] inputfile = new String[69];
for(int i = 0;i<69;i++)
inputfile[i]= br.split("\t")[i];
for(int i = 0;i<69;i++)
System.out.print(inputfile[i]+" ");
System.out.println();
//playData(inputfile);
}
else
this.stop();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
It reads 25 lines of data and after that it starts giveing the following exception.
java.io.IOException: Read error
at java.io.FileInputStream.readBytes(Native Method)
at java.io.FileInputStream.read(FileInputStream.java:199)
at java.io.DataInputStream.read(DataInputStream.java:132)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:264)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:306)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:158)
at java.io.InputStreamReader.read(InputStreamReader.java:167)
at java.io.BufferedReader.fill(BufferedReader.java:136)
at java.io.BufferedReader.readLine(BufferedReader.java:299)
at java.io.BufferedReader.readLine(BufferedReader.java:362)
at dynamicgraph.GPlot$PlayFile.actionPerformed(GPlot.java:817)
at javax.swing.Timer.fireActionPerformed(Timer.java:271)
at javax.swing.Timer$DoPostEvent.run(Timer.java:201)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
The only line no indiacted for my program in the error is
dynamicgraph.GPlot$PlayFile.actionPerformed(GPlot.java:817)
and this line contains the readLine() method to read the file. I am not able to guess the reason why does it stop reading after 25 lines
gunjannigam 28 Junior Poster
i updated my class like so:
/** * Write a description of class CatapultTester here. * * @author (your name) * @version (a version number or a date) */ import java.util.*; public class CatapultTester { public static void main(String[] args) { ArrayList<Catapult> catapultInfo = new ArrayList<Catapult>(); catapultInfo.add(new Catapult(20, 0.43)); catapultInfo.add(new Catapult(25, 0.52)); catapultInfo.add(new Catapult(30, 0.61)); catapultInfo.add(new Catapult(35, 0.69)); catapultInfo.add(new Catapult(40, 0.78)); catapultInfo.add(new Catapult(45, 0.87)); catapultInfo.add(new Catapult(50, 0.95)); //print header System.out.println(" Projectile Distance (feet)"); System.out.println(" MPH \t 25 deg \t 30 deg \t 35 deg \t 40 deg \t 45 deg \t 50 deg \t 55 deg"); System.out.println("==============================================================================================================="); NumberFormat formatter = new DecimalFormat("0.00"); for (int counter = 0; counter < catapultInfo.size(); counter++) { System.out.print("\t"+formatter.format(catapultInfo.get(counter).distanceFeet)); } } }
when i try to compile i get cannot find symbol class number format
You missed to import java.text.* class for Numberformat
gunjannigam 28 Junior Poster
Hi,
I am trying Serial Port Communication in Linux using Javacomm API and RxTx. I'm configured RxTx as per the documentation. But I received an error as follows,
Exception in thread "main" java.lang.UnsatisfiedLinkError:com.sun.comm.SunrayInfo.isSessionActive()Z.
Would you help me please..
Did u configure it using this link http://www.agaveblue.org/howtos/Comm_How-To.shtml
I also tried this link and probally got the same message as error.
Which version of Linux are you using. I will suggest that you only use Rxtx API,(instead of using both JavaComm and Rxtx). For installation of that u can dowlnoad the binary from http://rxtx.qbang.org/pub/rxtx/rxtx-2.1-7-bins-r2.zip
and copy RXTXComm.jar to your jre/lib/ext folder and libRxtxSerial.so and libRxtxParallel.so in your jre/lib/i386 folder
This jre folder must be inside your jdk folder.
Also import gnu.io.* instead of javax.comm.* in your code
gunjannigam 28 Junior Poster
Either make avg public or pass it from the main method where you might be calling your function myFlagged
gunjannigam 28 Junior Poster
Sorry I dont why are you printing the same value multiple times in your for loop. The value of counter will only increase once And why are you using printf??? If you want to print only till two places of decimal better use NumberFormatter class.And if you want all of them printed in one line use print statement.
Probally this might be what you want.
/**
* Write a description of class CatapultTester here.
*
* @author (your name)
* @version (a version number or a date)
*/
import java.util.*;
import java.text.*;
public class CatapultTester
{
public static void main(String[] args)
{
ArrayList<Catapult> catapultInfo = new ArrayList<Catapult>();
catapultInfo.add(new Catapult(20, 0.43));
catapultInfo.add(new Catapult(25, 0.52));
catapultInfo.add(new Catapult(30, 0.61));
catapultInfo.add(new Catapult(35, 0.69));
catapultInfo.add(new Catapult(40, 0.78));
catapultInfo.add(new Catapult(45, 0.87));
catapultInfo.add(new Catapult(50, 0.95));
//print header
System.out.println(" Projectile Distance (feet)");
System.out.println("MPH\t25 deg\t30 deg\t35 deg\t 40 deg\t 45 deg\t 50 deg\t 55 deg");
System.out.println("===============================================================================================================");
NumberFormat formatter = new DecimalFormat("0.00");
for (int counter = 0; counter < catapultInfo.size(); counter++)
{
System.out.print("\t"+formatter.format(catapultInfo.get(counter).distanceFeet));
}
}
}
gunjannigam 28 Junior Poster
Im writing this in netbeans. Here is the code:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package accounttoolssilverberg;/**
*
* @author Administrator
*/
public class accountToolsSilverberg {double a[];
int i;public accountToolsSilverberg() {
a = new double[1000];
for (i = 0; i < 1000; i++) {
a = Math.random() * 1000000;
}
}public double[] getArray() {
return a;
}public double myMax() {
double max = 0;
for (i = 0; i < 1000; i++) {
if (max < a) {
max = a;}
}
return max;
}public double myMin() {
double min = 0;
for (i = 0; i < 1000; i++) {
if (min > a) {
min = a;
}
}
return min;
}
public double myAVG(){
double sum = 0;
for (i = 0; i < 1000; i++){
sum = sum + a;
}
double avg;
avg = sum/1000;
return avg;
}}
public class accountTooltestsilverberg {public static void main(String[] args) {
accountToolsSilverberg test = new accountToolsSilverberg();
test.getArray();
System.out.println("Maximum account balance: $"+test.myMax());
System.out.println("Minimum account balance: $"+test.myMin());
System.out.println("Average account balance: $"+test.myAVG());
}}
It is a program getting account balances from random …
gunjannigam 28 Junior Poster
Another Panel with the size of the battery ?
and by Panel I mean JPanel, because the component on witch you place the tooltip must be a swing component not awt.
Well that worked. But now I have a diff problem due to this. I am having different panels below my battery panel(inseterted into tabs). So when I dont make those panels visible my tooltip shows.But when I make them visible there is no tooltip. Is it becuase of overlapping panels. I have tried setting opaque property of other panels as false but still tooltip doesnt show
gunjannigam 28 Junior Poster
i have created jar file when i am double click jar file i got error could not find main class program will exit
i am setting jar properties file mycomputer->tools->folderoptions->filetypes->jdk->javaw
i have created manifest file also i am using windows xp operating system
can anybody tell wha t is the problem?
thanks in advance
The problem you state shows that the system can not find the main class. Either you have specified a wrong location in the main class or you or not using the correct command to create jar file. I will suggest to use an IDE like NetBeans since they can easily create a jar file for you. If you are using a manifest file then remeber that you need to use new line after the name of main class.
gunjannigam 28 Junior Poster
Hi,
You can add a mouse listener to your panel and use setToolTip() method for your Panel, like this:
// in JPanel constructor // ... addMouseListener(new MouseAdapter() { public void mouseEntered(MouseEvent me){ mouseEnteredHandler(me); } }); // ... constructor ends // ... // private method private void mouseEnteredHandler(MouseEvent me) { this.setToolTipText("value of the battery"); }
of course you could update the tooltip text when the value of the battery is changed and remove the mouse listener ... and many other ways ... maybe :)
... if your panel is bigger then the size of your rectangles, you might need to find another component to add the tooltip
read more about using tooltips here
Thanks for a valuable suggestion. But as you said my panel is bigger than my rectangle. The panel contains so many other components. I only need that it should show the tooltip only when I enter the mouse on top of that rectangle. What other component can I use? Please suggest something. A component on which I can paint a rectangle. Then add tooltip to it at then place it at a specific location on a panel,i.e. using null Layout manager.
gunjannigam 28 Junior Poster
I want to draw a battery meter. For this I am painting my panel with Filled Rectangles using AWT Graphics class. Is it possible that I can add a tooltip so that whenver a mouse is pointed on the top of the rectangle a text is displayed(which will be the value of the battery)?
gunjannigam 28 Junior Poster
I want to know that can I run a code which extend JPanel and uses JFrame without running the x11 server on ubuntu. I read something about Headless but its not working.
gunjannigam 28 Junior Poster
The
super.paintComponent()
call just let's the component perform whatever normal painting the super class would if the method weren't overridden.To the OP: you may want to glance over this bit of info on the Swing painting mechanism: http://java.sun.com/docs/books/tutorial/uiswing/painting/closer.html
Your paintComponent() code is painting the JPanel portion and then paintChildren() renders the other components (such as the label with image) on top of that JPanel area.
If you created a class that extended JLabel you could paint over its icon image just fine by placing your custom code after a super.paintComponent() call.
Well I couldn't get what you meant about what I shall do. I am painting after calling the super.paintCOmponent call. What I should do. Please describe it once again
gunjannigam 28 Junior Poster
I needed to draw an image and paint a needle on it. Since my image is stationary(it doesnt change) I dont want to paint it each time I call repaint. Thats why I thought of using JLabel with an Icon image. The problem is I cant paint anything on top of label. If I use drawImage method I can paint on it.
Following is my code
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Stroke;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Gunjan Nigam
*/
public class Odometer extends JPanel {
int start1X,start1Y;
int image1x,image1y;
BufferedImage img;
float speed;
public Odometer()
{
super(null);
try
{
JFrame frame = new JFrame("Chariot");
frame.setSize(1280, 720);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
Toolkit toolkit = Toolkit.getDefaultToolkit();
frame.setLocation((int) ((toolkit.getScreenSize().getWidth()-1280)/2), (int) ((toolkit.getScreenSize().getHeight()-700)/2));
this.setBackground(Color.BLACK);
frame.add(this);
frame.setResizable(false);
ImageIcon myImage1 = new ImageIcon(getClass().getResource("/images/od.PNG"));
image1x=myImage1.getIconWidth();
image1y=myImage1.getIconHeight();
JLabel image1 = new JLabel(myImage1);
image1.setOpaque(true);
add(image1);
img = ImageIO.read(getClass().getResource("/images/od.PNG"));
frame.setVisible(true);
image1.setBounds((getWidth()-image1x)/2,(getHeight()-image1y)/2,image1x,image1y);
speed=0;
DataGenerator dg = new DataGenerator(90);
dg.start();
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
start1X = (getWidth())/2;
start1Y = (getHeight())/2;
//System.out.println(start1X+" "+start1Y);
//g2d.drawImage(img,(getWidth()-image1x)/2,(getHeight()-image1y)/2,image1x,image1y,null);
g2d.setColor(Color.white);
AffineTransform affineTransform = g2d.getTransform();
AffineTransform newTransform = (AffineTransform)(affineTransform.clone());
g2d.setPaint(Color.orange);
g2d.transform(newTransform.getRotateInstance((speed*30-210)/57.29,start1X,start1Y));
int[]coordinateXs={start1X,start1X+100,start1X+107,start1X+100,start1X};
int[]coordinateYs={start1Y-5,start1Y-5,start1Y,start1Y+5,start1Y+5};
g2d.fillPolygon(coordinateXs,coordinateYs,5);
Stroke stroke = new BasicStroke(3);
g2d.setStroke(stroke);
g2d.drawLine(start1X+105,start1Y,start1X+130,start1Y);
stroke=new …
gunjannigam 28 Junior Poster
Hey, I have a question about Java Applets. I wrote a small applet(just one file) and could run it in my web browser, by making this html file:
<APPLET CODE="MyApplet.class" WIDTH=400 HEIGHT=400> </APPLET>
And it worked just fine.
I am going to make a bigger project and I am going to make it an applet.
How is this gonna work if I have many classes and packages?
Does only Main class extends JApplet? Or each class should extend JApplet?
Do I have to specify all *.class in html code?
Thanks for your help, I appreciate it.
Only your main class needs to be specified in that HTML code. And make sure all the files your Main class requires are in the same Package as Main Class.Only Main Class needs to extend JApplet.
gunjannigam 28 Junior Poster
Well Couldnt get completely what you wanted.
Do u want to create a Panel with this image and Radio Button on it?
You can use the paintComponent to paint the image and setBounds method to translate your Button to the exact coordinte you want. But remember for using setBounds method your Layout should be set to null
gunjannigam 28 Junior Poster
(1)You can make you own Color Using Color Class Constructor with RGB Values. Search for Exact Color value you want
You can use new Color(100,149,237); or adjust these values as per your requirement
(2) You can use paint method to paint your image
maybe this can help
import java.awt.*;
import javax.swing.*;
class loginScreen extends JFrame
{
public loginScreen()
{
setDefaultCloseOperation(EXIT_ON_CLOSE);
ImagePanel panel = new ImagePanel("test.gif");
panel.add(new JButton("OK"));
getContentPane().add(panel);
pack();
setLocationRelativeTo(null);
}
class ImagePanel extends JPanel
{
Image img;
public ImagePanel(String file)
{
setPreferredSize(new Dimension(600, 400));
try
{
img = javax.imageio.ImageIO.read(new java.net.URL(getClass().getResource(file), file));
}
catch(Exception e){}//do nothing
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if(img != null) g.drawImage(img,0,0,getWidth(),getHeight(),this);
}
}
public static void main(String[] args){new loginScreen().setVisible(true);}
}
Ezzaral commented: Helpful +25
gunjannigam 28 Junior Poster
I am using Java Comm API to send some data on Serial Port and Again Checking it back. The Problem is that I am not able to get the correct data back always. Sometime I see a garbage value there.
Here is my Code
Setup SerialPort For Sending Data
public void setUpSerialPort()
{
CommPortIdentifier portId = null;
try
{
portId = CommPortIdentifier.getPortIdentifier("COM7");
} catch (NoSuchPortException ex) {
JOptionPane.showMessageDialog(null, "Sorry no such port exists.Please check your connections");
serialflag=false;
}
try
{
mySerialPort = (SerialPort) portId.open("AutoPilot on COM7",5000);
//configure the port
} catch (PortInUseException ex) {
JOptionPane.showMessageDialog(null, "Sorry port already in use by other device.\nClose all other applications that might be accessing this port");
serialflag=false;
}
//configure the port
try
{
mySerialPort.setSerialPortParams(115200,mySerialPort.DATABITS_8,mySerialPort.STOPBITS_1,mySerialPort.PARITY_NONE);
mySerialPort.setFlowControlMode(mySerialPort.FLOWCONTROL_NONE);
mySerialPort.setInputBufferSize(1);
mySerialPort.setOutputBufferSize(1);
} catch (Exception e){JOptionPane.showMessageDialog(null, "Sorry could not connect due to Windows error. Please retry");serialflag=false;}
System.out.println(mySerialPort.getInputBufferSize());
System.out.println(mySerialPort.getBaudRate()+" "+ mySerialPort.getDataBits()+" "+" "+mySerialPort.getStopBits()+" "+mySerialPort.getParity()+" "+mySerialPort.getFlowControlMode());
try
{
in = new DataInputStream(mySerialPort.getInputStream());
} catch (IOException ex) {
ex.printStackTrace();
}
try
{
mySerialPort.addEventListener(this);
mySerialPort.notifyOnDataAvailable(true);
} catch (TooManyListenersException e) {System.out.println("couldn't add listener");}
}
Code where I send Data
byte[] message = new byte [14];
int crc=0;
byte[] mesg;
byte[] arr = new byte [2];
mesg="#".getBytes();
message[0] = mesg[0];
mesg = "UP".getBytes();
message[1] = mesg[0];
message[2] = mesg[1];
arr = shortToByteArray((short)slider1.getValue());
message[4] = arr[0];
message[3] = arr[1];
arr = shortToByteArray((short)slider2.getValue());
message[6] = arr[0];
message[5] = arr[1];
arr = shortToByteArray((short)slider3.getValue());
message[8] = arr[0];
message[7] = arr[1];
mesg = frameId1.getBytes();
message[9] = mesg[0];
message[10] = mesg[1];
for(int i=0;i<11;i++)
crc=crc^message[i];
//mesg =
mesg …
gunjannigam 28 Junior Poster
You could take a look at http://java.freehep.org/demo/LegoPlot/
which is a demo of the 3D plotting package in FreeHEP.
Well I have seen that demo before but I was not able to find the code.
Is there any link where I can find some link to develop some code...................
gunjannigam 28 Junior Poster
go with opengl(open graphics library) or jogl (java opengl).
Well I havent use OpenGL before. So could you guide me how to do this with JOG
gunjannigam 28 Junior Poster
I want to add a splash screen to my application. The problem is that whatever splashscreen I have seen on net are basically extending JWindow/JFrame and My application extends JPanel. Now Due to this I am not able to display my application after SplacshScreen is complete.
gunjannigam 28 Junior Poster
Can anyone suggest a open source llibrary for plotting 3D graphs . More precisely dynamic graphs. I was using jfreechart but that is only for 2D plots. I need a library so that I can plot 3D graphs.............
gunjannigam 28 Junior Poster
Then write a method that:
if value is negative return "empty String" else return the value
You need to explain your problem better and show some code
Well I finally worked it out..........
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.text.FieldPosition;
import java.text.NumberFormat;
import java.text.ParsePosition;
class MyNumberFormat extends NumberFormat {
@Override
public StringBuffer format(double number, StringBuffer toAppendTo,
FieldPosition pos) {
if(number>=0)
return toAppendTo.append(number);
else
return toAppendTo.append("");
}
@Override
public StringBuffer format(long number, StringBuffer toAppendTo,
FieldPosition pos) {
if(number>=0)
return toAppendTo.append(number);
else
return toAppendTo.append("");
}
@Override
public Number parse(String source, ParsePosition parsePosition) {
throw new UnsupportedOperationException();
}
}
gunjannigam 28 Junior Poster
Hello,
This is for you.
public class CustomNumberType extends Number{ public double doubleValue() { return 0; } public float floatValue() { return 0; } public int intValue() { return 0; } public long longValue() { return 0; } }
Implement your logic in this class.
Regards,
Sorry, I couldnt get you Puneet.
Wht I need in output is a object of class NumberFormat or ChoiceFormat which will have a label empty string for a -ve value and the number itself for +ve and zero values..................
gunjannigam 28 Junior Poster
I want to create a custom NumberFormat which returns empty string for negative values and the double number iteslf for +ve and zero values. Please guide me....................