问题描述
我编写了一个 Java GUI 程序,它打开一个文本文件并读取左侧面板中的数据.现在我想在右侧面板上显示从同一文件读取的数据的图形.
我已经使用 JFileChooser
打开文件并读取数据并将它们显示在文本区域上.我希望使用二维 X-Y 图显示从文件中读取的数据.应使用数据文件中指定的标签信息标记图形的轴.X 轴上的值应从指定的 x 轴起始值开始,间隔以由 x 轴间隔值确定的速率递增.Y 轴上的值需要根据数据本身确定.图中绘制的每个点都应使用单线连接.
我使用了几种方法,但都没有奏效.我尝试将文本文件中的每一行作为数组读取,并将数组用作数据集,但效果不佳.请帮我根据文本文件中的数据绘制图表.任何帮助,将不胜感激.谢谢.
P.S 该图应仅使用 AWT/Swing 库绘制.
文件上的数据如下:
标题:年龄对能力的影响Xlabel:年龄Ylabel:能力开始:0间隔:150, 3, 4.2, 7, 5.1, 10, 3.2
以下是我迄今为止编写的代码:
import java.awt.BorderLayout;导入 java.awt.Dimension;导入 java.awt.Font;导入 java.awt.GridLayout;导入 java.awt.List;导入 java.awt.TextArea;导入 java.awt.event.ActionEvent;导入 java.awt.event.ActionListener;导入 java.awt.event.KeyEvent;导入 java.awt.event.KeyListener;导入 java.io.BufferedReader;导入 java.io.File;导入 java.io.FileNotFoundException;导入 java.io.FileReader;导入 java.io.IOException;导入 java.io.InputStreamReader;导入 java.math.BigDecimal;导入 java.util.ArrayList;导入 java.util.Scanner;导入 javax.swing.BorderFactory;导入 javax.swing.ImageIcon;导入 javax.swing.JFileChooser;导入 javax.swing.JFrame;导入 javax.swing.JLabel;导入 javax.swing.JMenu;导入 javax.swing.JMenuBar;导入 javax.swing.JMenuItem;导入 javax.swing.JOptionPane;导入 javax.swing.JPanel;导入 javax.swing.JScrollPane;导入 javax.swing.JSplitPane;导入 javax.swing.JTextArea;导入 javax.swing.event.MenuEvent;导入 javax.swing.event.MenuListener;导入 org.jfree.chart.ChartFactory;导入 org.jfree.chart.ChartPanel;导入 org.jfree.chart.JFreeChart;导入 org.jfree.chart.plot.PlotOrientation;导入 org.jfree.data.general.DefaultPieDataset;导入 org.jfree.data.xy.XYSeries;导入 org.jfree.data.xy.XYSeriesCollection;@SuppressWarnings("串行")公共类 GUI 扩展 JFrame {private String[] readLines = new String[6];公共图形用户界面(){//设置标题、大小和布局setTitle("数据可视化工具");setSize(950, 1000);setLayout(new BorderLayout());//为 JFrame 创建一个菜单栏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("");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);//添加//JScrollPane 到面板//滚动条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)));//创建一个图形窗格.JPanel graphicsArea = new JPanel();//graphicsArea.setFont(new Font("Serif", Font.BOLD, 16));JScrollPane graphicsScrollPane = new JScrollPane(graphicsArea);//滚动条graphicsScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);graphicsScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);graphicsScrollPane.setPreferredSize(new Dimension(550, 550));graphicsScrollPane.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("图形表示"),BorderFactory.createEmptyBorder(5, 5, 5, 5)));//将图形窗格和文本窗格放在一个拆分窗格中.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);//把所有东西放在一起.JPanel leftPane = new JPanel(new BorderLayout());添加(右窗格,BorderLayout.LINE_END);//////////////////////////////////////////////////////////////////////////////////////////////////////////////文件菜单快捷方式fileMenu.setMnemonic(KeyEvent.VK_F);fileMenu.add(openAction);//openAction.addActionListener(this);openAction.addActionListener(new ActionListener() {公共无效动作执行(ActionEvent arg0){如果 (arg0.getSource().equals(openAction)) {//使用 JFileChooser 打开文本文件JFileChooser fileChooser = new JFileChooser();if (fileChooser.showOpenDialog(fileChooser) == JFileChooser.APPROVE_OPTION) {//fileChooser.setCurrentDirectory(new//File(System.getProperty("user.home")));//环境//当前的//目录文件文件 = fileChooser.getSelectedFile();BufferedReader br = null;尝试 {//FileReader fr = new FileReader(file);扫描仪 f = 新扫描仪(文件);for (int i = 0; i <6; i++) {readLines[i] = f.nextLine();textArea.setText(textArea.getText() + readLines[i] + "
");String array[] = readLines[i].split(" ");}} catch (FileNotFoundException e) {JOptionPane.showMessageDialog(new JFrame(), "找不到文件!", "错误!",JOptionPane.ERROR_MESSAGE);//错误信息//如果文件不是//成立} catch (NullPointerException e) {//System.out.println(e.getLocalizedMessage());} 最后 {如果(br != null){尝试 {br.close();} catch (IOException e) {e.printStackTrace();}}}}}}});fileMenu.add(saveAction);fileMenu.add(exitAction);//退出按钮快捷键exitAction.setMnemonic(KeyEvent.VK_X);exitAction.addActionListener(new ActionListener() {//设置退出按钮公共无效动作执行(ActionEvent arg0){如果 (arg0.getSource().equals(exitAction)) {System.exit(0);}}});fileMenu.addSeparator();helpMenu.addSeparator();helpMenu.add(aboutAction);//关于按钮快捷键aboutAction.setMnemonic(KeyEvent.VK_A);aboutAction.addActionListener(new ActionListener() {//点击关于按钮打开一个对话框,其中包含//关于程序的信息公共无效动作执行(ActionEvent arg0){JOptionPane.showMessageDialog(menuBar.getComponent(0),"该程序基于数据可视化工具的开发.
"+ "基本概念是制作一个读取原始文本数据的软件,
"+ "分析该数据,然后以图形方式将其呈现给用户.","关于我们", JOptionPane.PLAIN_MESSAGE);}});}}
从你的例子开始,注意以下几点:
为您的
graphicsArea
使用ChartPanel
;然后,您的openAction()
可以简单地调用setChart()
.在
creatChart()
中解析选中的文件;显示了标题和数据行,但其余属性留作练习.考虑使用
import java.awt.BorderLayout;导入 java.awt.EventQueue;导入 java.awt.Font;导入 java.awt.event.ActionEvent;导入 java.awt.event.ActionListener;导入 java.awt.event.KeyEvent;导入 java.io.BufferedReader;导入 java.io.File;导入 java.io.FileReader;导入 java.io.IOException;导入 javax.swing.BorderFactory;导入 javax.swing.ImageIcon;导入 javax.swing.JFileChooser;导入 javax.swing.JFrame;导入 javax.swing.JMenu;导入 javax.swing.JMenuBar;导入 javax.swing.JMenuItem;导入 javax.swing.JOptionPane;导入 javax.swing.JScrollPane;导入 javax.swing.JSplitPane;导入 javax.swing.JTextArea;导入 org.jfree.chart.ChartFactory;导入 org.jfree.chart.ChartPanel;导入 org.jfree.chart.JFreeChart;导入 org.jfree.data.xy.XYSeries;导入 org.jfree.data.xy.XYSeriesCollection;//* @see https://stackoverflow.com/a/36764715/230513 */公共类 GUI 扩展 JFrame {公共图形用户界面(){super("数据可视化器");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"));最终 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("文本表示"),BorderFactory.createEmptyBorder(5, 5, 5, 5)));ChartPanel graphicsArea = new ChartPanel(null);graphicsArea.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("图形表示"),BorderFactory.createEmptyBorder(5, 5, 5, 5)));JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, textScrollPane, graphicsArea);splitPane.setOneTouchExpandable(true);splitPane.setResizeWeight(0.5);添加(splitPane,BorderLayout.LINE_END);fileMenu.setMnemonic(KeyEvent.VK_F);fileMenu.add(openAction);openAction.addActionListener(new ActionListener() {@覆盖公共无效动作执行(ActionEvent arg0){如果 (arg0.getSource().equals(openAction)) {JFileChooser fileChooser = new JFileChooser(new File("."));if (fileChooser.showOpenDialog(fileChooser) == JFileChooser.APPROVE_OPTION) {文件文件 = fileChooser.getSelectedFile();graphicsArea.setChart(creatChart(file));}}}私人 JFreeChart creatChart(文件文件){字符串标题 = null;字符串 xAxisLabel = null;字符串 yAxisLabel = null;BufferedReader in = null;int 开始 = 0;整数间隔 = 0;字符串数据 = 空;字符串行 = null;尝试 {in = new BufferedReader(new FileReader(file));while ((line = in.readLine()) != null) {textArea.append(line + " ");if (line.startsWith("Title")) {title = line.split(":")[1].trim();}//在这里解析其他行if (!line.contains(":")) {数据 = 行;}}} catch (IOException ex) {ex.printStackTrace(System.err);}XYSeries 数据集 = new XYSeries(file.getName());for (String s : data.split(",")) {dataset.add(start, Double.valueOf(s));开始 += 间隔;}返回 ChartFactory.createXYLineChart(title,xAxisLabel, yAxisLabel, new XYSeriesCollection(dataset));}});fileMenu.add(saveAction);fileMenu.add(exitAction);exitAction.setMnemonic(KeyEvent.VK_X);exitAction.addActionListener(new ActionListener() {@覆盖公共无效动作执行(ActionEvent arg0){如果 (arg0.getSource().equals(exitAction)) {System.exit(0);}}});fileMenu.addSeparator();helpMenu.addSeparator();helpMenu.add(aboutAction);aboutAction.setMnemonic(KeyEvent.VK_A);aboutAction.addActionListener(new ActionListener() {@覆盖公共无效动作执行(ActionEvent arg0){JOptionPane.showMessageDialog(null,"可视化工具.","关于我们", JOptionPane.PLAIN_MESSAGE);}});盒();setLocationRelativeTo(null);设置可见(真);}公共静态无效主(字符串 [] args){EventQueue.invokeLater(() -> {新的图形用户界面();});}}
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.
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.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.
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] + " "); 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. " + "The basic concept is to produce a piece of software which reads in raw textual data, " + "analyses that data, then presents it graphically to the user.", "About Us", JOptionPane.PLAIN_MESSAGE); } }); } }
解决方案Starting from your example, note the following:
Use a
ChartPanel
for yourgraphicsArea
; then, youropenAction()
can simply invokesetChart()
.Parse the chosen file in
creatChart()
; the title and data lines are shown, but the remaining attributes are left as an exercise.Consider using
Properties
for your file format;To change the chart panel's default size, override
getPreferredSize()
as shown here.Swing GUI objects should be constructed and manipulated only on the event dispatch thread.
For a single chart, replace
ChartPanel
withJPanel
and overridepaintComponent()
to perform the rendering. You can transform coordinates using the approach is outlined here or here.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://stackoverflow.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 + " "); 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(); }); } }
这篇关于如何使用文本文件中的数据集在 Java 中绘制折线图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!