Input file which contains 2D coordinates for a rectangle - java

I am struggling to read in 2D coordinates from an input file which should then create rectangles in a rectangle class. I am wondering how I would go about starting this as I am new to programming, such as how to layout the coordinates in the file and how to read them in using like a X1 Y1 X2 Y2 format to create a rectangle in the rectangle class. Thanks.

Read BufferedReader from https://www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/ . It is an example of bufferedReader which is reading per line. Using this, you can put your text files values to your program.
This is a program I created for you
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFileExample2 {
//variable for file name with specified file path
private static final String FILENAME = "\*your directory*\filename.txt";
//List variable -> higher level of array because List is a flexible array
private static List<double> coordinates = new ArrayList<double>();
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader(FILENAME))) {
//this will add values from your textfile per line to List
while ((coordinates.add(br.readLine())) != null) { }
} catch (IOException e) {
e.printStackTrace();
}
}
}
This will solve one of your issue but this is just for you to move on not to solve all issues.
Your textfile should contain values like this
12
32
23
12
4 points for coordinates but per line. Your List coordinates will have it by running while ((coordinates.add(br.readLine())) != null) { }
research how to use list . It's a great thing to know.
Now study how to implement GUI using either JFrame or Applet.
Issues:
GUI : using JFrame
Read Text File : using BufferedReader
Array : using List, a higher level of array

Related

iText7 setRotation() not working properly

I'm making a small Java program that can modify an existing PDF, and save the changes in a new PDF, using iTextPDF 7. I started with a rotating feature, using setRotation() on a PdfDocument, but my PDF output is rotating 90 degree less than the value I put as a parameter.
So setRotation(90) makes no changes,
setRotation(180) does a single clockwise change,
setRotation(270) does a double turn (180 degree rotation).
etc..
Here's my Code:
import java.io.IOException;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
public class rotateMyPDF {
public static void main(String[] args) throws IOException {
PdfReader in_pdf = new PdfReader("in.pdf");
PdfDocument pdfDoc = new PdfDocument(in_pdf, new PdfWriter("out.pdf"));
for (int i=1; i<=pdfDoc.getNumberOfPages(); i++) {
pdfDoc.getPage(i).setRotation(270); //error here?
}
pdfDoc.close();
System.out.println("done.");
}
}
Seems like a bug? Or is there an error in my code? Or is this intended functionality?
If I put setRotation(0), the PDF pages are rotated 90 degrees counter clockwise!
You appear to misunderstand the setRotation method. It does not add to the current rotation but it sets the rotation value.
Thus, if your page already had page rotation applied, setting the same value with setRotation will change nothing etc.
Your source page appears to already be rotated by 90°. That would explain the observation:
So setRotation(90) makes no changes,
setRotation(180) does a single clockwise change,
setRotation(270) does a double turn (180 degree rotation).
etc..
Simply first read the current rotation value with getRotation, add the desired extra rotation, and then set that sum using setRotation.

(Java) Producing image by reading from a text-file filled with digits

I'm a complete beginner in Java programming and I'm interested to learn more about its concepts.
Recently, I've been given an exercise which instructs me to display two versions of a picture. The picture to be displayed is provided in the form of a data file of 40,000 digits that are arranged in rows (although there is no marker between rows) and it starts from the top of the picture. So the first digit represents the top left corner of the picture and the last is the bottom right.
Basically, what the exercise wants me to construct a program that plots a dot in one of two colours for each digit. If the digit is in the range 0 to 3 the output should be one colour and for digits in the range 4 to 9 the dot should be in the other colour.
I understand I have to use arrays and also loops to perform this. I'm familiar with the fillEllipse, drawEllipse, drawRectangle and fillRectangle but this exercise is nothing I've attempted before.
Any hints on how to make this work? Your help would be greatly appreciated.
As a hint, rather than a complete solution, I would suggest looking into creating a java.awt.image.BufferedImage, and then set the colors of the individual pixels using the setRGB() method. You would then display this image using drawImage() on your Graphics object.
All what you need is how to read the digits from the file and put it into two dimension array
check this tutorial for how to read a file
Then you have to draw each pixel on a fram or a Panel
check this Java basic graphics tutorial
I hope this could help!
use Scanner to read the data like :
Scanner sc = new Scanner(new File("path_to_your_digits_file"));
int[][] digits= new int [200][200];
String line;
while(sc.hasNext()){//this means there is still a line to go
line = sc.nextLine();
//split the line and fill the array . or read char by char ,
// i dont know how your file looks like, it's just some simple string manipulation here
}
int x;
BufferedImage img = new BufferedImage(200,200,BufferedImage.TYPR_INT_RGB);
for(int i=0;i<200;i++){
for(int j=0;i<200;j++){
if(digits[i][j]>0 && digits[i][j]<=3){
x=//some color code;
}else{
x=//some other color code;
} //not sure about this loop , again idk the structure of your file;
img.setRGB(i,j,x);
}
}
JLabel lbl = new JLabel();
lbl.setSize(200,200);
ImageIcon ico=new ImageIcon(img);
lbl.setIcone(ico);
lbl.setVisible(true);
JFrame frame = new Jframe();
frame.setSize(500,500);
frame.add(lbl);
frame.setVisible(true);

How to output all of the text in my JtextArea to a save file?

Hello there fellow stackers! I'm having a problem creating a proper save function for my game. The main problem I am having is capturing all of the data inside of my J text area named display. The display reflects what moves have been made so far in the game, and at the top of the display it says "Welcome to Togiz Kumalak".
My problem is that when I save the game, it only records the first line of text to the file instead of all lines.
an example is:
Welcome to Togiz Kumalak
Player 1 Cup 1
Player 2 Cup 3
and so on. When I save the file, only the top line will be shown.
Here is my current code for the save Listener.
class SaveListener implements ActionListener
{
String a = display.getText();
JFileChooser myChooser= new JFileChooser();
public void actionPerformed(ActionEvent event)
{
String fileName;
myChooser.setCurrentDirectory(new File("."));
myChooser.showSaveDialog(null);
fileName = myChooser.getSelectedFile().getPath();
try
{
OutputStream file = new FileOutputStream(fileName);
PrintStream printStream = new PrintStream(file);
printStream.print(a);
printStream.close();
/* Version 11, 23.1. Scroll pane and text area support when saving. */
}
catch(IOException e)
{
System.out.println("Problem making or writing to an output stream.");
System.out.println(e);
}
}
}
Use the write(...) method of the JTextArea API instead of trying to create your own method.
..having a problem creating a proper save function for my game
Given the word 'proper' (my emphasis) I have to point out that the proper way to save/load games is according to a 'game state model' as opposed to a 'game state model crudely translated to lines of text'.
That game state model might be saved a number of ways depending upon the complexity of the data, but should use very different serialization methods (with less work done encoding/decoding the data in our code) than this approach uses.

Continuously read from file and do an action

I want to continuously read from a text file, and change the color of a box I have shown on the canvas when a certain line is read (the text file is going to be constantly updating). Right now, I have a green square drawn on the canvas and three "test" lines in the text file, and when it reaches the third line of the text file I would like to change the the square to Red.
Here is my code, from two files (myCanvas.java and myFileReader.java). Any point in the right direction is greatly appreciated.
public class myCanvas extends Canvas{
public myCanvas(){
}
public void paint(Graphics graphics){
graphics.setColor(Color.green);
graphics.fillRect(10, 10, 100, 100);
graphics.drawRect(10,10,100,100);
}
public static void main(String[] args){
myCanvas canvas = new myCanvas();
JFrame frame = new JFrame("Live GUI");
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(canvas);
frame.setVisible(true);
myFileReader read = new myFileReader();
read.readFromFile();
if(myFileReader.strLine == "This is the third line."){
//change color
}
}
public class myFileReader{
public static String strLine;
public void readFromFile()
{
try{
FileInputStream fstream = new FileInputStream(System.getProperty("user.dir")+"\\sample.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
while (true){
strLine = br.readLine();
if(strLine == null) {
Thread.sleep(1000);
}
}
}
catch (Exception ex){
System.err.println("Error: " + ex.getMessage());
}
}
}
Here is a way you can do it without much changes to your code.
Create a local variable in your MyCanvas class called currentColor of type Color. FYI, the convention in Java is to have class names start with a capital letter.
Update your paint() method to set the color of the rectangle to the new variable currentColor, instead of the static green value.
In your main method, you can do canvas.currentColor = <new color here>; and then canvas.repaint(). The repaint() function call will erase the canvas and redraw it using your paint() function.
I don't think your FileReader will work well with a file that's constantly being modified though.
Simply add a counter and increment it each time you read a line. When the counter reaches the third line use an if statement to do your task
Try this
1.Use BreakIterator class, with its static method getLineInstance(),
this will help you identify every line in the file.
2. Create an HashMap with the colour as Key, and its RGB as Value.
3. Parse every word in the line, which is obtained from
BreakIterator.getLineInstance().
4. Compare it with the Key in the HashMap,
if the word in the line happens to match the Key in
the HashMap, then colour the box with the Value of the Key.

save Linked List in Notepad.txt

I draw many triangle polygons and store it in Linked List. My problem is that, when I store the drawing in a Notepad file, the data is unreadable (weird symbol). When I try to print it using println the output is like this java.awt.Polygon#1d6096.
How to store the coordinate of the polygon in Notepad?
...
java.util.List<Polygon> triangles = new LinkedList<Polygon>();
String pathname = "eyemovement.txt";
...
int[] xs = { startDrag.x, endDrag.x, midPoint.x };
int[] ys = { startDrag.y, startDrag.y, midPoint.y };
triangles.add(new Polygon(xs, ys,3));
...
public void actionPerformed(ActionEvent e) {
if(e.getSource() == saveBtn){
try {
FileOutputStream fos = new FileOutputStream(pathname);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(triangles);
oos.flush();
oos.close();
fos.close();
}
catch (Exception ex) {
System.out.println("Trouble writing display list vector");
}
}
EDITED:
I have tried all the suggestions but still I can't managed to get the output as the following. I have tried the "Printwriter" as well, but I cant solved the problem. Help me, please, my head is so heavy with this :-(
I draw the triangles, make changes, and store it in Linked List. After finished drawing, and make changes, I click save button and save it in Notepad.txt with hope that I will get the output in Notepad like this:
40 60 50 this line represents vertices Xs of triangle 1
40 40 50 this line represents vertices Ys of triangle 1
60 80 70 triangle 2
60 60 70
100 120 110 triangle 3
100 100 110
If you just want to store co-ordinates, and only want to write one way (into the file) then you should write an override method on your Polygon:
String toString() {
return this.x + ", " + this.y;
}
or something similar.
Of course the data is unreadable. It is "Data", not "Text". You have to read the file again with the ObjectInputStream class. Use the method `readObject(); This method returns an Object. Of course you have to cast it on this way:
Object o = ois.readObject(); // ois is the ObjectInputStream
List<Polygon> list = new ArrayList<Polygon>((List) o));
I think you just want to save the triangle to continue working with it after closing your program.
Nobody actually posted the absolute simplest way to do this, so here it goes.
Take a Polygon p, output a string representing the x/y coordinates of p (assuming p has at least 1 point) of the form "(x1 y1, x2 y2, x3 y3, ...)":
System.out.print("(" + p.xpoints[0] + p.ypoints[0]);
for (int i = 0; i < p.npoints; i++) {
System.out.print(", " + p.xpoints[i] + " " + p.ypoints[i]);
}
System.out.println(")");
I start with a test case.
import java.awt.Polygon;
import junit.framework.TestCase;
public class PolygonTest extends TestCase {
public void testToString() throws Exception {
Polygon polygon = new Polygon();
polygon.addPoint(0, 1);
polygon.addPoint(1, 1);
polygon.addPoint(1, 0);
assertEquals("(0,1;1,1;1,0)", polygon.toString());
}
}
I'm assuming here that you are using the awt Polygon class. This test fails, because awt's Polygon class doesn't override the default behavior. But Polygon has lots of good stuff in it you don't want to lose (maybe), so to add the new behavior we want (a toString() method), let's change this just a little bit:
import java.awt.Polygon;
import junit.framework.TestCase;
public class PolygonTest extends TestCase {
public void testToString() throws Exception {
Polygon polygon = new Triangle();
polygon.addPoint(0, 1);
polygon.addPoint(1, 1);
polygon.addPoint(1, 0);
assertEquals("(0,1;1,1;1,0)", polygon.toString());
}
}
This doesn't even compile, because the Triangle class doesn't exist yet. So let's create it (I'm using eclipse; I'll run QuickFix to create the class for me):
import java.awt.Polygon;
public class Triangle extends Polygon {
}
And now the test compiles, but fails as before. So let's write the toString() method:
import java.awt.Polygon;
public class Triangle extends Polygon {
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("(");
for (int i = 0; i < npoints; i++)
sb.append(String.format("%s,%s;", xpoints[i], ypoints[i]));
sb.deleteCharAt(sb.length() - 1); // get rid of the final semicolon
sb.append(")");
return sb.toString();
}
}
and now the test passes.
Note that I changed the format a little from what you requested, because I think you probably want to be able to distinguish between the point (5, 17) and the point (51, 7).

Categories