So basically im creating a GUI that allows the user to select a file, this file is check to be a .wav file. Then this file's data is graphed through JFreechart.
This graph or image created by Jfreechart i want to put into the JFrame.
The problem is that the code:
ImageIcon myIcon1 = new ImageIcon("blah.jpg");
JLabel graphLabel1 = new JLabel(myIcon1);
southContent.add(graphLabel1);
must be created & declared in the method where i create the JFrame ( must be added to the frame )
thus i cannot dynamically update the image to new created graphs, depending on what file the user selects. ( on selection of a new file, via button a new graph image is created )
is there a way to force
ImageIcon myIcon1 = new ImageIcon("blah.jpg");
JLabel graphLabel1 = new JLabel(myIcon1);
southContent.add(graphLabel1);
to update to the new image ( in the same direcotry, with the same name )
or is there a way using Mapping to set the image name ("blah.jpg") dynamically with a counter?
here is my 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);
}
}
}
Just add the JLabel to its container as you usually do. Then, once you created the image and you have an instance of an ImageIcon, just call the setIcon() method for the JLabel.
Using something like this should allow displaying both images of the waveform, as well as new images of the waveform.
try {
//ChartUtilities.saveChartAsJPEG(
// new File("C:/location/chart1.jpg"), chart, 1000, 600);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ChartUtilities.saveChartAsPNG(baos, chart, 1000, 600);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
BufferedImage image = ImageIO.read(bais);
// !!!!! this is where we need to set the ImageIcon..
graphLabel1.setIcon(new ImageIcon(image));
} catch (IOException e) {
e.printStackTrace();
System.err.println("Error occured: " + e + "");
}
OTOH you might look to increasing the memory size and generate the entire waveform in one pass, then display the label in a scroll pane.
Thanks to Dan and Andrew Thompson, i have a working product.
I used a counting variable to count teach time the "OpenAction" button was selected.
i then used this variable to make dynamic names for each image i created through JFreechart.
Thus i used .setIcon to reset the icon image to each new created image with a new name.
.setIcon does not seem to work if you are trying to reset the label to a Image icon that has the same name as the previously selected Image icon.
the finished code segment looks like:
ImageIcon myIcon1 = new ImageIcon("C:/location/chart"+CounterVariable+".png");
graphLabel1.setIcon(myIcon1);
for example this will create charts;
chart1
chart2
chart3
and so forth.
Related
Hi I am unsure on how to format my animated gif images to let them show on Jars created on eclipse.
try {
//ImageIcon titleIcon = new ImageIcon(ImageIO.read(getClass().getResource("title.gif")));
title = new ImagePicture (new ImageIcon(ImageIO.read(getClass().getResource("title.gif"))), 0, 0);
//title = new ImagePicture (new ImageIcon("title.gif"), 0, 0);
}//end try
catch (IOException e) {
}//end catch
//set title bounds
title.setBounds(260, 0, 400, 100);
That is my code right now for an animated GIF, Thank you for your input.
Hard to give a good example without more context, but you can try adding the ImageIcon to a JLabel like this.
URL url = this.getClass().getResource("title.gif");
Icon title = new ImageIcon(url);
JLabel titleLbl = new JLabel(title);
//You have to add titleLbl to a container after this, of course
I am trying to give my interface a new function, but I have encountered some obstacles. I want to enlarge image on JLabel when mouseEnters.
Here is how my JLabels looks:
int sacle = 50 //Size of my JLabel Icon
int zoom = 10 // How much the icon should enlarge
imageIcon = new ImageIcon(new ImageIcon(myClass.class.getResource(Picture))
.getImage().getScaledInstance(scale, scale, Image.SCALE_SMOOTH));
JLabel stackIsGreat = new JLabel();
stackIsGreat.setIcon(imageIcon);
//and I add multiple of such JLabels`
And the code goes on and on. I wanted to creat a function and add it to mouseListener, so all will behave the same. I wanted to achive that with:
//inside external method
activeLabel = (javax.swing.JLabel)(e.getSource());
ImageIcon temp = (ImageIcon) activeLabel.getIcon();
But there is no way I know I could get use of this, because java says I need Image to create my enlarged ImageIcon
ImageIcon enlarged = new ImageIcon((Image).getScaledInstance(scale + zoom, scale + zoom, Image.SCALE_SMOOTH))
How can I retrive the image used to crate the JLabel from code.
Any help would be appreciated.
I want to enlarge image on JLabel when mouseEnters.
Instead of creating your own MouseListener you could use a JButton to give you the rollover effect:
Something like:
JButton button = new JButton(...);
button.setBorderPainted( false );
ImageIcon icon = (ImageIcon)button.getIcon();
Image image = icon.getImage();
Image scaled = image.getScaledImage(...);
button.setRolloverIcon( new ImageIcon( scaled ) );
I am trying to do a fairly basic swing GUI where a user can enter a url, choose a local file location etc. I am using multiple layout managers including boxlayout, borderlayout and flowlayout. The code is below.
My problem is that some of the components are moving around when the user puts text into the optionsTxt jtextarea. Anyone know where I should start to stop this happening?
Setup menu bar
JButton menu_File = new JButton("File");
JButton menu_Edit = new JButton("Edit");
JToolBar toolBar = new JToolBar();
toolBar.add(menu_File);
toolBar.add(menu_Edit);
//Setup options area
JPanel options = new JPanel();
options.setBorder(BorderFactory.createTitledBorder("Options"));
BoxLayout layout_Options = new BoxLayout(options, BoxLayout.Y_AXIS);
options.setLayout(layout_Options);
JLabel optionsLblURL = new JLabel("Enter URL:");
optionsTxtUrl = new JTextArea(1,15);
JLabel chooseDestLbl = new JLabel("Choose save location:");
chooseDest = new JButton("Browse");
chooseDest.addActionListener(this);
options.add(optionsLblURL);
options.add(optionsTxtUrl);
options.add(chooseDestLbl);
options.add(chooseDest);
//Setup launch area
JPanel launch = new JPanel();
launch.setBorder(BorderFactory.createTitledBorder("Launch"));
launchBtnStart = new JButton("Start Download");
launchBtnStart.setVerticalAlignment(SwingConstants.CENTER);
launchBtnStart.setHorizontalAlignment(SwingConstants.CENTER);
launchBtnStart.addActionListener(this);
launch.add(launchBtnStart);
//Setup reporting area
JPanel logging = new JPanel();
logging.setBorder(BorderFactory.createTitledBorder("Log"));
BoxLayout layout_Logging = new BoxLayout(logging, BoxLayout.Y_AXIS);
logging.setLayout(layout_Logging);
JTextArea loggingTxt = new JTextArea(3,10);
loggingTxt.setEditable(false);
logging.add(pb);
logging.add(loggingTxt);
//Add components to window
BorderLayout borderLayout = new BorderLayout();
setLayout(borderLayout);
add("North", toolBar);
add("West", options);
add("East", launch);
add("South", logging);
setVisible(true);
"My problem is that some of the components are moving around when the user puts text into the optionsTxt jtextarea. Anyone know where I should start to stop this happening?"
Start by putting your JTextArea in a ScrollPane and setLineWrap(true) and setWrapStyleWord(true). You may want to consider doing this with both JTextAreas you have
JTextArea optionsTxtUrl = new JTextArea(1,15);
optionsTxtUrl.setLineWrap(true);
optionsTxtUrl.setWrapStyleWord(true);
JScrollPane scroll = new JScrollPane(optionsTxtUrl);
options.add(scroll); // take out options.add(optionsTxtUrl);
This will make your lines wrap when they reach the right edge of the text area
public void setWrapStyleWord(boolean word) - Sets the style of wrapping used if the text area is wrapping lines. If set to true the lines will be wrapped at word boundaries (whitespace) if they are too long to fit within the allocated width. If set to false, the lines will be wrapped at character boundaries. By default this property is false.
public void setLineWrap(boolean wrap) - Sets the line-wrapping policy of the text area. If set to true the lines will be wrapped if they are too long to fit within the allocated width. If set to false, the lines will always be unwrapped. A PropertyChange event ("lineWrap") is fired when the policy is changed. By default this property is false.
If this doesn't solve your problem, you should edit your post with a Minimal, Complete, Tested and Readable example so we can test out your problem.
I am writing a code to make an image file of a chart appearing on a panel. For that purpose I create the buffered image of that and then use ImageIO.write(). It works but it only displays the panel(grey coloured panel) but does not show the chart present on that panel. What to do in this case?? Here is my code
com.objectplanet.chart.NonFlickerPanel p =
new com.objectplanet.chart.NonFlickerPanel(new BorderLayout());
p.add("Center", chart); // this statements adds the chart in the center of the panel
ChartPanel.add("Center", p);
ChartPanel.setSize(500, 200);
ChartPanel.show();
int w = ChartPanel.getWidth();
int h = ChartPanel.getHeight();
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi.createGraphics();
ChartPanel.paint(g);
ChartPanel.printAll(g);
File f = new File("D:\\image.png");
try {
// png is an image format (like gif or jpg)
ImageIO.write(bi, "png", f);
} catch (IOException ex) {
ex.printStackTrace();
}
Well i solved the problem .Anyone facing the same problem ,here is the solution
Use paintall function rather than just paint function
Pretty straightforward issue. My Java AWT (not Swing) label is simply not showing up. Most of the following code isn't even being used (for debugging this issue).
Just a note: this is within a Frame's constructor (and yes I have added several other panels and such that work just fine). Secondly, the frame's layout has been set to null.
I'm stumped.
File inf = new File("instructions.txt");
Label ilb;
if(inf.exists())
{
Log.v("Loading instructions");
try
{
FileInputStream fis = new FileInputStream(inf);
byte[] insb = new byte[65535];
fis.read(insb);
fis.close();
String inst = new String(insb);
ilb = new Label("test", Label.LEFT);
File fntfile = new File("font/pf_tempesta_seven.ttf");
Font infnt = null;
try {
FileInputStream ffis = new FileInputStream(fntfile);
infnt = Font.createFont(Font.TRUETYPE_FONT, ffis);
ffis.close();
} catch (FontFormatException e) {
Log.e("Could not format LCD font!", e);
} catch (IOException e) {
Log.e("Could not read LCD font file!", e);
}
if(infnt == null)
infnt = new Font("Trebuchet MS", Font.PLAIN, 8);
else
infnt = infnt.deriveFont(8.0f);
//ilb.setFont(infnt);
//ilb.setForeground(new Color(123, 123, 123));
//ilb.setPreferredSize(new Dimension(350, 400));
//ilb.setSize(350, 400);
//ilb.setLocation(580, 190);
Log.d("adding label");
add(ilb);
} catch(IOException e) {
Log.e("Could not read instructions!", e);
}
}else
Log.w("Instructions file not found!");
1) for todays GUI use Swing JComponents (starts with J) rather than prehistoric AWT Label
2) for your issue could be better use JTextArea with method append()
3) you have got issues with Concurency (in Swing) AWT / Swing is single threaded and all output to the GUI must be wrapped into invokeLater
4) for better help sooner you have edit your question with SSCCE
As #JBNizet suggested, null layouts don't work with all AWT components.
I was thrown off since my Panels were positioned just fine with a null layout on my Frame, whereas Labels require a basic layout in order to display. I was tempted to go as far as saying all other components had the same 'feature', but another part of my code proved that point wrong:
// Load Image
Log.v("Loading header image");
_iBG = new ImageIcon("img/hpcount_top_bg.png").getImage();
// Set size
setSize(1024, 152);
setPreferredSize(new Dimension(1024, 152));
// Set position
setLocation(0, 0);
// Set visible
setVisible(true);
// Set layout
setLayout(null);
// Add children
add(new Exit()); // Exit extends java.awt.Button
The above code (which is located within the constructor of a class extending java.awt.Panel) works perfectly.
My workaround is to put the label inside another Panel with a layout (messy, but it works) and position that panel within the Frame absolutely to achieve the same effect.