【发布时间】:2012-10-02 07:03:42
【问题描述】:
所以基本上我创建了一个允许用户选择文件的 GUI,该文件被检查为 .wav 文件。然后这个文件的数据通过JFreechart 绘制出来。 这个由 Jfreechart 创建的图形或图像我想放入 JFrame 中。 问题是代码:
ImageIcon myIcon1 = new ImageIcon("blah.jpg");
JLabel graphLabel1 = new JLabel(myIcon1);
southContent.add(graphLabel1);
必须在我创建 JFrame 的方法中创建和声明(必须添加到框架中) 因此,我无法根据用户选择的文件将图像动态更新为新创建的图形。 (在选择新文件时,通过按钮创建一个新的图形图像)
有没有办法强制
ImageIcon myIcon1 = new ImageIcon("blah.jpg");
JLabel graphLabel1 = new JLabel(myIcon1);
southContent.add(graphLabel1);
更新到新镜像(在同一个目录,同名)
或者有没有办法使用映射来通过计数器动态设置图像名称(“blah.jpg”)?
这是我的SSCCE
public class gui extends JFrame {
ImageIcon myIcon1 = new ImageIcon("C:/location/chart1.jpg");
JLabel graphLabel1 = new JLabel(myIcon1);
gui() {
// create Pane + contents & listeners...
JPanel content = new JPanel();
JPanel southContent = new JPanel();
content.setLayout(new FlowLayout());
content.add(open_File);
// Jfreechart graph image -- not visible until selected
graphLabel1.setVisible(false);
// this is the graph image being added to the panel
southContent.add(graphLabel1);
southContent.setLayout(new FlowLayout());
// add action listeners to buttons
open_File.addActionListener(new OpenAction());
// set Pane allignments & size...
this.setContentPane(content);
this.add(southContent, BorderLayout.SOUTH);
this.setTitle("Count Words");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(1100, 720);
this.setLocationRelativeTo(null);
}
// opening selected file directory.
class OpenAction implements ActionListener {
public void actionPerformed(ActionEvent ae) {
/// gets user selection ( file ) and procesess .wav data into array
/// loops through array creating X series for JfreeChart
// Add the series "series" to data set "dataset"
dataset.addSeries(series);
// create the graph
JFreeChart chart = ChartFactory.createXYLineChart(
".Wav files", // Graph Title
"Bytes", // X axis name
"Frequency", // Y axis name
dataset, // Dataset
PlotOrientation.VERTICAL, // Plot orientation
true, // Show Legend
true, // tooltips
false // generate URLs?
);
try {
ChartUtilities.saveChartAsJPEG(
new File("C:/location/chart1.jpg"), chart, 1000, 600);
} catch (IOException e) {
System.err.println("Error occured: " + e + "");
}
// !!!!! this is where i need to set the ImageIcon added to the
// panel in "gui" to this new created Graph image ("chart1.jpg")
// as above
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// sets the image label itself to visible as a new image has been
// added ot it
graphLabel1.setVisible(true);
}
}
}
【问题讨论】:
-
“必须在我创建 JFrame 的方法中创建和声明” 这都可以通过将
graphLabel1设置为对后来的方法,或者我不知道你在说什么。 ..或者可能两者兼而有之。为了尽快获得更好的帮助,请发帖SSCCE。 -
我相信 graphLabel1 是类级别的。很抱歉给您带来不便,我发布了 SSCCE。
-
1) 我不明白为什么有人会使用 JPEG 对图表进行编码。试试PNG。 2)
// !!!!! this is where i need to set the ImageIcon..不。这样做的地方应该在 try 中,直接在代码正在尝试的语句之后。如果失败,则设置图标毫无意义。 3)似乎磁盘访问只是为了确保显示图像。这使得它变得不必要。使用writeChartAsPNG(..)w。鲍斯。
标签: java image swing jlabel imageicon