0

The code I have written so far has two panel, one for text and another for graph. Using JFileChooser I open a text file and the content is displayed on a textarea. Now I want to draw a simple line chart using the data in the text file which will be displayed in the other panel. The graph should be drawn using AWT/Swing libraries only. Any help would be appreciated.

The data in the text file:

Title: Randon Number Graph
Xlabel: Possible Range
Ylabel: Typical Value
start: -100.5
interval: 20.25
40, 90.2, 101.654, 60.2, 90.2, 100.2, 95.22, 101, 99.99, 124, 128, 64.3, 32.1

My code so far:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;

public class GUI extends JFrame implements MenuListener, ActionListener, KeyListener {

public GUI() {
    // Setting Title, size and layout
    setTitle("Data Visualiser");
    setSize(730, 350);
    setLayout(new BorderLayout());

    // Creates a menubar for a JFrame
    final JMenuBar menuBar = new JMenuBar();

    // Add the menubar to the frame
    setJMenuBar(menuBar);

    // Define and add two drop down menu to the menubar, "file" and "help"
    JMenu fileMenu = new JMenu("File");
    JMenu helpMenu = new JMenu("Help");
    menuBar.add(fileMenu);
    menuBar.add(helpMenu);

    // adding menu items and icons to the "file" drop down menu,
    final JMenuItem openAction = new JMenuItem("Open", new ImageIcon("images/Open-icon.png"));

    final JMenuItem saveAction = new JMenuItem("Save", new ImageIcon("images/save-file.png"));

    final JMenuItem exitAction = new JMenuItem("Exit", new ImageIcon("images/exit-icon.png"));

    final JMenuItem aboutAction = new JMenuItem("About", new ImageIcon("images/about-us.png"));


    //////////////////////////////////////////////////////////////////////////////////////////////


    // Create a text area.
    final JTextArea textArea = new JTextArea("");
    textArea.setFont(new Font("Serif", Font.BOLD, 16));
    textArea.setLineWrap(true);
    textArea.setWrapStyleWord(true);
    textArea.setEditable(false);
    JScrollPane textScrollPane = new JScrollPane(textArea);
    // textArea.add(textScrollPane, BorderLayout.CENTER); //add the
    // JScrollPane to the panel

    // Scrollbars
    textScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    textScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

    textScrollPane.setPreferredSize(new Dimension(350, 350));
    textScrollPane.setBorder(
            BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Textual Representation"),
                    BorderFactory.createEmptyBorder(5, 5, 5, 5)));


    // Create an graphics pane.
    JTextArea graphicsArea = new JTextArea("");
    graphicsArea.setFont(new Font("Serif", Font.BOLD, 16));
    graphicsArea.setLineWrap(true);
    graphicsArea.setWrapStyleWord(true);
    graphicsArea.setEditable(false);
    JScrollPane graphicsScrollPane = new JScrollPane(graphicsArea);
    // Scrollbars
    graphicsScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    graphicsScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

    graphicsScrollPane.setPreferredSize(new Dimension(350, 350));
    graphicsScrollPane.setBorder(
            BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Graphical Representation"),
                    BorderFactory.createEmptyBorder(5, 5, 5, 5)));

    // Put the graphics pane and the text pane in a split pane.
    JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, textScrollPane, graphicsScrollPane);
    splitPane.setOneTouchExpandable(true);
    splitPane.setResizeWeight(0.5);

    JPanel rightPane = new JPanel(new GridLayout(1, 0));
    rightPane.add(splitPane);

    // Put everything together.
    JPanel leftPane = new JPanel(new BorderLayout());
    add(rightPane, BorderLayout.LINE_END);


    ////////////////////////////////////////////////////////////////////////////////////////////////////////////


    // file menu shortcut
    fileMenu.setMnemonic(KeyEvent.VK_F);

    fileMenu.add(openAction);
    // openAction.addActionListener(this);
    openAction.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent arg0) {
            if (arg0.getSource().equals(openAction)) {

                // using JFileChooser to open the text file
                JFileChooser fileChooser = new JFileChooser();

                if (fileChooser.showOpenDialog(fileChooser) == JFileChooser.APPROVE_OPTION) {
                    fileChooser.setCurrentDirectory(new File(System.getProperty("user.home"))); // setting
                                                                                                // current
                                                                                                // directory
                    File file = fileChooser.getSelectedFile();
                    BufferedReader br = null;

                    try {
                        FileReader fr = new FileReader(file); // using
                                                                // filereader
                                                                // to read
                                                                // the text
                                                                // file
                        br = new BufferedReader(fr);
                        textArea.read(br, file);

                        Scanner f = new Scanner(br);
                        String line1 = f.nextLine();

                        String line = br.readLine();
                        while (line != null) {
                            // textArea.append(line + "\n");
                            line = br.readLine();
                            textArea.read(br, textArea); // here we read in
                                                            // the text file

                            // file content validation
                            while ((line = br.readLine()) != null) {
                                if (line.startsWith("Title:")) {
                                    textArea.append(line + "\n");
                                } else {
                                    JOptionPane.showMessageDialog(new JFrame(), "Invalid format.", "ERROR!",
                                            JOptionPane.ERROR_MESSAGE);
                                }
                                if (line1.startsWith("XLabel:")) {
                                    textArea.append(line1 + "\n");
                                } else {
                                    JOptionPane.showMessageDialog(new JFrame(), "Invalid format.", "ERROR!",
                                            JOptionPane.ERROR_MESSAGE);
                                }
                                if (line1.startsWith("YLabel:")) {
                                    textArea.append(line1 + "\n");
                                } else {
                                    JOptionPane.showMessageDialog(new JFrame(), "Invalid format.", "ERROR!",
                                            JOptionPane.ERROR_MESSAGE);
                                }
                            }

                        }

                    } catch (FileNotFoundException e) {
                        JOptionPane.showMessageDialog(new JFrame(), "File not found!", "ERROR!",
                                JOptionPane.ERROR_MESSAGE); // error message
                                                            // if file not
                                                            // found
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        if (br != null) {
                            try {
                                br.close();
                            } catch (IOException e) {
                            }
                        }
                    }

                }
            }
        }
    });

    fileMenu.add(saveAction);
    fileMenu.add(exitAction);

    // exit button shortcut
    exitAction.setMnemonic(KeyEvent.VK_X);
    exitAction.addActionListener(new ActionListener() {

        // setting up exit button
        public void actionPerformed(ActionEvent arg0) {
            if (arg0.getSource().equals(exitAction)) {
                System.exit(0);
            }
        }
    });

    fileMenu.addSeparator();

    helpMenu.addSeparator();
    helpMenu.add(aboutAction);
    // about button shortcut
    aboutAction.setMnemonic(KeyEvent.VK_A);
    aboutAction.addActionListener(new ActionListener() {
        // clicking on about button opens up a dialog box which contain
        // information about the program
        public void actionPerformed(ActionEvent arg0) {
            JOptionPane.showMessageDialog(menuBar.getComponent(0),
                    "This program is based on the development of a data visualization tool.",
                    "About Us", JOptionPane.PLAIN_MESSAGE);
        }
    });

}

@Override
public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void menuCanceled(MenuEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void menuDeselected(MenuEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void menuSelected(MenuEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void keyPressed(KeyEvent arg0) {
    /*if (arg0.getKeyChar() == 'x') {
        System.exit(0);
    }*/
}

@Override
public void keyReleased(KeyEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void keyTyped(KeyEvent arg0) {
    // TODO Auto-generated method stub

    }
}
luke
  • 51
  • 9
  • *"How to draw line graph in Java from text file?"* Do the [Performing Custom Painting Lesson](https://docs.oracle.com/javase/tutorial/uiswing/painting/) of the tutorial. VTC as 'too broad'. – Andrew Thompson Apr 24 '16 at 00:03
  • 1
    BTW - 2 points. 1) It will be necessary to break the problem into parts and work out how to do each part. The parts I suggest are a) Load the text file (which it seems you have done) b) Parse the text into usable objects (like for each line of text, produce a `GraphDataPoint` object and add it to a list structure) c) Draw the list of `GraphDataPoints` (possibly scaled) to custom component that displays them to the user (or a `BufferedImage`). Note that for the third part, to create example code, it would hard code the data so it can be easily parsed into the collection of `GraphDataPoint`s. .. – Andrew Thompson Apr 24 '16 at 00:08
  • 1
    .. 2) And speaking of an 'example'. For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). And I mean that, as opposed to over 250 lines of code (some of which seems unnecessary/unrelated to the stated problem). – Andrew Thompson Apr 24 '16 at 00:12
  • @AndrewThompson Hello sir, I am fairly new to java, so any example code would be helpful. And the graph should be drawn using AWT/Swing libraries, I have updated the description. Sorry for the confusion. – luke Apr 24 '16 at 00:42
  • Looking over the code it seems at the stage of point (b) parse the data. Is that right? *"any example code would be helpful"* People might choose to explain in code, but please refrain from requesting it. – Andrew Thompson Apr 24 '16 at 00:49
  • I am reading each line using the following method: in = new BufferedReader(new FileReader(file)); while ((line = in.readLine()) != null) { textArea.append(line + "\n"); if (line.startsWith("Title")) { title = line.split(":")[1].trim(); } – luke Apr 24 '16 at 00:51
  • *"I am reading each line using the following method"* Yes, I noticed that in the code. There is an easier way to load text into a `JTextComponent`, but that is beside the point, since your method to read and load the file seems to work. So the next step is to parse that `String` in the text field, into an `Object` that might be called .. a `LineGraph` .. right? I'd earlier suggested some `GraphPoint` objects, the `LineGraph` would have a collection of those, as well as attributes for the title, `xLabel` & `yLabel`, & the `start` & `interval`. The code needs to define these (min.) 2 objects. – Andrew Thompson Apr 24 '16 at 01:15
  • `graphicsArea` should be a `JPanel`. – trashgod Apr 24 '16 at 04:17

0 Answers0