public class FrameDemo extends JPanel
{
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
String[] read file contents using FileArrayProvider
for loop through above String array
g2.draw(new Line2D.Double(...));
}
public static void main(String[] args)
{
JFrame frame = new JFrame("JFrame Example");
frame.add(new FrameDemo());
frame.setSize(300, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class FileArrayProvider // taken from StackOverFlow
{
public String[] readLines(String filename) throws IOException
{
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
java.util.List<String> lines = new ArrayList<String>();
String line = null;
while((line=bufferedReader.readLine())!=null)
{
lines.add(line);
}
bufferedReader.close();
return lines.toArray(new String[lines.size()]);
}
}
Hi, inside the paintComponent method where I read the file lines in order to drawlines, i get quite a bit of lines, sometimes like more than a few millions. As a consequence my frame freezes for a while… Is it the correct way of doing it? Is there any better way to do it? So that it does not freeze, and draws all the lines when it would display the frame?
You should never read a file in the paintComponent() method.
When you create the class the constructor should read the file so that all the data is in memory when it comes time to paint the component.
I also don’t understand the need to paints millions of lines. I would suggestion you draw these lines once to a BufferedImage and then you can use the BufferedImage to create an ImageIcon which can be added to a JLabel and then you just display the label on the GUI.