d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Java Reading From File Printing To Graphics Window
Add Reply New Topic New Poll
Member
Posts: 17,594
Joined: Mar 13 2009
Gold: 0.00
Sep 17 2015 09:51pm
I need to create a PieChart that reads from a file and displays the results in the graphics window.

If the text file reads:

"swallow 10
magpie 5
fairywren 7
osprey 2
fantail 3"

It should display the birds name in the graphics window. I also need to work out the percentage but I can work on that once I get past this small part.

So my question is, in java how do you read from a text file and print out the string to a graphics window, instead of command prompt?

Even if I am given a completely separate, simple example that is fine also.

Here is my code so far.

Code
import javax.swing.*;

public class Main {

public static void main(String[] args) {

JFrame f = new JFrame("Pie chart");
f.setSize(600, 350);
f.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
f.add(new PieChart());
f.setVisible(true);
}

}


Code
import java.awt.*;
import javax.swing.*;

public class PieChart
extends JComponent {

public void paintComponent(Graphics g) {

Graphics2D g2 = (Graphics2D) g.create();
Graphics2D g3 = (Graphics2D) g.create();
g3.setColor(Color.BLACK);
g2.setColor(Color.BLUE);
for (int i = 0; i < 5; i = i + 1) {
g2.fillRect(230, 20 * i + 50 , 20, 20);
g3.drawString("swallow", 255, 20 * i + 65);
g3.drawString("37.0%", 385, 20 * i + 65);
}
g2.fillArc(50, 50, 150, 150, 0, 360);
}

}


So it needs to display: swallow, magpie, fairywren, osprey, fantail.

Here is the current display so far.

Member
Posts: 32,925
Joined: Jul 23 2006
Gold: 3,804.50
Sep 17 2015 10:05pm
Quote (CPK001 @ Sep 17 2015 11:51pm)

So my question is, in java how do you read from a text file and print out the string to a graphics window, instead of command prompt?


it looks like you already solved the second part? so you only need to know how to read a text file?

A little out of date, but this is how i learned it a long time ago:

https://www.caveofprogramming.com/java/java-file-reading-and-writing-files-in-java.html#readtext

a quick google search will reveal other examples.
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll