I have written a Java GUI program which opens a text file and reads the data in the left panel. Now I want to display a graph of the data read from the same file on the right panel.
我编写了一个Java GUI程序,它打开一个文本文件并读取左侧面板中的数据。现在我想在右侧面板上显示从同一文件中读取的数据图表。
I have used JFileChooser
to open files and read the data and display them on a text area. I want the data read from the file to be displayed using a two dimensional X-Y graph. The axis of the graph should be labeled using the label information specified in the data file. The values on the X-axis should begin from the x-axis start value specified, with intervals which increment at a rate determined by the x-axis interval value. The values on the Y-axis will need to be determined from the data itself. Each point plotted on the graph should be joined using a single line.
我使用JFileChooser打开文件并读取数据并将其显示在文本区域。我希望使用二维X-Y图显示从文件读取的数据。应使用数据文件中指定的标签信息标记图表的轴。 X轴上的值应从指定的x轴起始值开始,间隔以x轴间隔值确定的速率递增。 Y轴上的值需要根据数据本身确定。绘制在图表上的每个点应使用单行连接。
I have used several methods but none worked. I have tried reading each line on the text file as arrays and use the arrays as the dataset, but it didn't work as well. Please help me plot a graph from the data on the text file. Any help would be appreciated. Thanks.
我使用了几种方法,但都没有用。我已经尝试将文本文件中的每一行作为数组读取并使用数组作为数据集,但它也不能正常工作。请帮我从文本文件中的数据绘制图表。任何帮助,将不胜感激。谢谢。
P.S The graph should be plotted using AWT/Swing libraries only.
P.S图表应仅使用AWT / Swing库绘制。
The data on the file is as follows:
该文件的数据如下:
Title: Effect of Age on Ability
Xlabel: Age
Ylabel: Ability
start: 0
interval: 15
0, 3, 4.2, 7, 5.1, 10, 3.2
Following are my code which I have written so far:
以下是我到目前为止编写的代码:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.List;
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.math.BigDecimal;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
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;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
@SuppressWarnings("serial")
public class GUI extends JFrame {
private String[] readLines = new String[6];
public GUI() {
// Setting Title, size and layout
setTitle("Data Visualiser");
setSize(950, 1000);
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, 550));
textScrollPane.setBorder(
BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Textual Representation"),
BorderFactory.createEmptyBorder(5, 5, 5, 5)));
// Create an graphics pane.
JPanel graphicsArea = new JPanel();
//graphicsArea.setFont(new Font("Serif", Font.BOLD, 16));
JScrollPane graphicsScrollPane = new JScrollPane(graphicsArea);
// Scrollbars
graphicsScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
graphicsScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
graphicsScrollPane.setPreferredSize(new Dimension(550, 550));
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);
Scanner f = new Scanner(file);
for (int i = 0; i < 6; i++) {
readLines[i] = f.nextLine();
textArea.setText(textArea.getText() + readLines[i] + "\n");
String array[] = readLines[i].split(" ");
}
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(new JFrame(), "File not found!", "ERROR!",
JOptionPane.ERROR_MESSAGE); // error message
// if file not
// found
} catch (NullPointerException e) {
// System.out.println(e.getLocalizedMessage());
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
});
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. \n"
+ "The basic concept is to produce a piece of software which reads in raw textual data, \n"
+ "analyses that data, then presents it graphically to the user.",
"About Us", JOptionPane.PLAIN_MESSAGE);
}
});
}
}
1 个解决方案
#1
3
Starting from your example, note the following:
从您的示例开始,请注意以下事项:
-
Use a
ChartPanel
for yourgraphicsArea
; then, youropenAction()
can simply invokesetChart()
.使用ChartPanel作为graphicsArea;然后,你的openAction()可以简单地调用setChart()。
-
Parse the chosen file in
creatChart()
; the title and data lines are shown, but the remaining attributes are left as an exercise.在creatChart()中解析所选文件;显示标题和数据行,但剩余的属性保留为练习。
-
Consider using
Properties
for your file format;考虑使用属性作为文件格式;
-
For greater flexibility, use
Action
as shown here.要获得更大的灵活性,请使用此处所示的Action。
-
To change the chart panel's default size, override
getPreferredSize()
as shown here.要更改图表面板的默认大小,请覆盖此处所示的getPreferredSize()。
-
Swing GUI objects should be constructed and manipulated only on the event dispatch thread.
应该仅在事件派发线程上构造和操作Swing GUI对象。
P.S. The graph should be plotted using AWT/Swing libraries only.
附:应仅使用AWT / Swing库绘制图表。
For a single chart, replace ChartPanel
with JPanel
and override paintComponent()
to perform the rendering. You can transform coordinates using the approach is outlined here or here.
对于单个图表,将ChartPanel替换为JPanel并覆盖paintComponent()以执行渲染。您可以使用此处或此处概述的方法转换坐标。
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
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.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
//* @see https://*.com/a/36764715/230513 */
public class GUI extends JFrame {
public GUI() {
super("Data Visualiser");
setDefaultCloseOperation(EXIT_ON_CLOSE);
final JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu fileMenu = new JMenu("File");
JMenu helpMenu = new JMenu("Help");
menuBar.add(fileMenu);
menuBar.add(helpMenu);
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"));
final JTextArea textArea = new JTextArea(8, 16);
textArea.setFont(new Font("Serif", Font.BOLD, 16));
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setEditable(false);
JScrollPane textScrollPane = new JScrollPane(textArea);
textScrollPane.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("Textual Representation"),
BorderFactory.createEmptyBorder(5, 5, 5, 5)));
ChartPanel graphicsArea = new ChartPanel(null);
graphicsArea.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("Graphical Representation"),
BorderFactory.createEmptyBorder(5, 5, 5, 5)));
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, textScrollPane, graphicsArea);
splitPane.setOneTouchExpandable(true);
splitPane.setResizeWeight(0.5);
add(splitPane, BorderLayout.LINE_END);
fileMenu.setMnemonic(KeyEvent.VK_F);
fileMenu.add(openAction);
openAction.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if (arg0.getSource().equals(openAction)) {
JFileChooser fileChooser = new JFileChooser(new File("."));
if (fileChooser.showOpenDialog(fileChooser) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
graphicsArea.setChart(creatChart(file));
}
}
}
private JFreeChart creatChart(File file) {
String title = null;
String xAxisLabel = null;
String yAxisLabel = null;
BufferedReader in = null;
int start = 0;
int interval = 0;
String data = null;
String line = null;
try {
in = new BufferedReader(new FileReader(file));
while ((line = in.readLine()) != null) {
textArea.append(line + "\n");
if (line.startsWith("Title")) {
title = line.split(":")[1].trim();
}
// parse other lines here
if (!line.contains(":")) {
data = line;
}
}
} catch (IOException ex) {
ex.printStackTrace(System.err);
}
XYSeries dataset = new XYSeries(file.getName());
for (String s : data.split(",")) {
dataset.add(start, Double.valueOf(s));
start += interval;
}
return ChartFactory.createXYLineChart(title,
xAxisLabel, yAxisLabel, new XYSeriesCollection(dataset));
}
});
fileMenu.add(saveAction);
fileMenu.add(exitAction);
exitAction.setMnemonic(KeyEvent.VK_X);
exitAction.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if (arg0.getSource().equals(exitAction)) {
System.exit(0);
}
}
});
fileMenu.addSeparator();
helpMenu.addSeparator();
helpMenu.add(aboutAction);
aboutAction.setMnemonic(KeyEvent.VK_A);
aboutAction.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null,
"Visualization tool.",
"About Us", JOptionPane.PLAIN_MESSAGE);
}
});
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
new GUI();
});
}
}
#1
3
Starting from your example, note the following:
从您的示例开始,请注意以下事项:
-
Use a
ChartPanel
for yourgraphicsArea
; then, youropenAction()
can simply invokesetChart()
.使用ChartPanel作为graphicsArea;然后,你的openAction()可以简单地调用setChart()。
-
Parse the chosen file in
creatChart()
; the title and data lines are shown, but the remaining attributes are left as an exercise.在creatChart()中解析所选文件;显示标题和数据行,但剩余的属性保留为练习。
-
Consider using
Properties
for your file format;考虑使用属性作为文件格式;
-
For greater flexibility, use
Action
as shown here.要获得更大的灵活性,请使用此处所示的Action。
-
To change the chart panel's default size, override
getPreferredSize()
as shown here.要更改图表面板的默认大小,请覆盖此处所示的getPreferredSize()。
-
Swing GUI objects should be constructed and manipulated only on the event dispatch thread.
应该仅在事件派发线程上构造和操作Swing GUI对象。
P.S. The graph should be plotted using AWT/Swing libraries only.
附:应仅使用AWT / Swing库绘制图表。
For a single chart, replace ChartPanel
with JPanel
and override paintComponent()
to perform the rendering. You can transform coordinates using the approach is outlined here or here.
对于单个图表,将ChartPanel替换为JPanel并覆盖paintComponent()以执行渲染。您可以使用此处或此处概述的方法转换坐标。
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
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.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
//* @see https://*.com/a/36764715/230513 */
public class GUI extends JFrame {
public GUI() {
super("Data Visualiser");
setDefaultCloseOperation(EXIT_ON_CLOSE);
final JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu fileMenu = new JMenu("File");
JMenu helpMenu = new JMenu("Help");
menuBar.add(fileMenu);
menuBar.add(helpMenu);
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"));
final JTextArea textArea = new JTextArea(8, 16);
textArea.setFont(new Font("Serif", Font.BOLD, 16));
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setEditable(false);
JScrollPane textScrollPane = new JScrollPane(textArea);
textScrollPane.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("Textual Representation"),
BorderFactory.createEmptyBorder(5, 5, 5, 5)));
ChartPanel graphicsArea = new ChartPanel(null);
graphicsArea.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("Graphical Representation"),
BorderFactory.createEmptyBorder(5, 5, 5, 5)));
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, textScrollPane, graphicsArea);
splitPane.setOneTouchExpandable(true);
splitPane.setResizeWeight(0.5);
add(splitPane, BorderLayout.LINE_END);
fileMenu.setMnemonic(KeyEvent.VK_F);
fileMenu.add(openAction);
openAction.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if (arg0.getSource().equals(openAction)) {
JFileChooser fileChooser = new JFileChooser(new File("."));
if (fileChooser.showOpenDialog(fileChooser) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
graphicsArea.setChart(creatChart(file));
}
}
}
private JFreeChart creatChart(File file) {
String title = null;
String xAxisLabel = null;
String yAxisLabel = null;
BufferedReader in = null;
int start = 0;
int interval = 0;
String data = null;
String line = null;
try {
in = new BufferedReader(new FileReader(file));
while ((line = in.readLine()) != null) {
textArea.append(line + "\n");
if (line.startsWith("Title")) {
title = line.split(":")[1].trim();
}
// parse other lines here
if (!line.contains(":")) {
data = line;
}
}
} catch (IOException ex) {
ex.printStackTrace(System.err);
}
XYSeries dataset = new XYSeries(file.getName());
for (String s : data.split(",")) {
dataset.add(start, Double.valueOf(s));
start += interval;
}
return ChartFactory.createXYLineChart(title,
xAxisLabel, yAxisLabel, new XYSeriesCollection(dataset));
}
});
fileMenu.add(saveAction);
fileMenu.add(exitAction);
exitAction.setMnemonic(KeyEvent.VK_X);
exitAction.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if (arg0.getSource().equals(exitAction)) {
System.exit(0);
}
}
});
fileMenu.addSeparator();
helpMenu.addSeparator();
helpMenu.add(aboutAction);
aboutAction.setMnemonic(KeyEvent.VK_A);
aboutAction.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null,
"Visualization tool.",
"About Us", JOptionPane.PLAIN_MESSAGE);
}
});
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
new GUI();
});
}
}