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
Related
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 want to give a visual indication that a node has been transferred to clipboard with a "Cut" action. One intuitive look used by at least one proprietary OS is to make this the same image, but slightly transparent.
I'd quite like to know whether it is in fact possible somehow to use the icons used by the Windoze OS (W7)... but I'd be more intrigued if it were possible to interfere in some way (in the renderer) with the Icon, by somehow messing with the Graphics object used by Icon.paintIcon() ... just for a given node, obviously. I'm not clear where an Icon goes hunting for the Graphics object it uses when it is painted ... any enlightenment would be most welcome.
later
Many thanks to MadProgrammer. Spotted this possibility as a way of extracting obfuscated visuals with a view to their manipulation: https://home.java.net/node/674913 ... it works. Putting code here in case of broken link...
public class IconTest {
public static void main(String[] args) {
Icon leafIcon = UIManager.getIcon("Tree.leafIcon");
// ... ("Tree.closedIcon") ("Tree.openIcon")
BufferedImage img1 = new BufferedImage(leafIcon.getIconWidth(),
leafIcon.getIconHeight(), BufferedImage.TYPE_INT_RGB);
Graphics g = img1.createGraphics();
g.drawImage(((ImageIcon) leafIcon).getImage(), 0, 0, null);
g.dispose();
try {
ImageIO.write(img1, "PNG", new File("leafIcon.png"));
} catch (IOException e) {
System.out.println("Error writing to file leafIcon" + ", e = " + e);
System.exit(0);
}
}
}
Then use MadProgrammer's technique to alter the image in any way one likes: change transparency, colour, etc. Great stuff.
I'd quite like to know whether it is in fact possible somehow to use the icons used by the Windoze OS (W7)
FileSystemView#getSystemIcon will give you the OS's icon representation of a given File, for example...
Icon icon = FileSystemView.getFileSystemView().getSystemIcon(new File("ThatImportantDoc.docx"));
I want to give a visual indication that a node has been transferred to clipboard with a "Cut" action. One intuitive look used by at least one proprietary OS is to make this the same image, but slightly transparent.
You need to paint the previous Icon to BufferedImage, which has had a AlphaComposite applied to it, for example
BufferedImage img = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
g2d.setComposite(AlphaComposite.SrcOver.derive(0.5f));
icon.paintIcon(null, g2d, 0, 0);
g2d.dispose();
You then need to wrap the resulting BufferedImage in a ImageIcon, which allows you to pass the image as a Icon to the rest of the API.
JPanel panel = new JPanel();
panel.add(new JLabel(icon));
panel.add(new JLabel(new ImageIcon(img)));
JOptionPane.showMessageDialog(null, panel, "Icon", JOptionPane.PLAIN_MESSAGE);
To get this to finally work, you will need to provide a TreeCellRenderer capable of supporting your functionality. Have a look at How to Use Trees for more details
Just one tweak enabling me to do what I mainly wanted to do: get the UI images "from the source code".
public class IconTest {
public static void main(String[] args) {
// OS folder icon
// Icon icon = FileSystemView.getFileSystemView().getSystemIcon(new File("."));
// proprietary word processor
// Icon icon = FileSystemView.getFileSystemView().getSystemIcon(new File("Doc1.docx"));
// taken from PNG file
// Icon icon = new ImageIcon( "openIcon.png" );
// taken directly from the Java images held somewhere (?) in the code
Icon icon = UIManager.getIcon("Tree.leafIcon");
// Icon icon = UIManager.getIcon("Tree.openIcon");
// ... ("Tree.closedIcon") ("Tree.openIcon")
BufferedImage img = new BufferedImage( icon.getIconWidth(),
icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
g2d.setComposite(AlphaComposite.SrcOver.derive( 0.5f));
icon.paintIcon(null, g2d, 0, 0);
g2d.dispose();
JPanel panel = new JPanel();
panel.add(new JLabel(icon));
panel.add(new JLabel(new ImageIcon(img)));
JOptionPane.showMessageDialog(null, panel, "Icon", JOptionPane.PLAIN_MESSAGE);
}
}
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.
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.
Is there a way in Java Swing to show text in small caps (small capitals)?
http://en.wikipedia.org/wiki/Small_caps
I have loaded a custom font which supports small caps via Font.createFont(). The text should be rendered somehow in small caps. Is this possible in JLabel, JTextPane or some other component?
You can try that, it works : (I get the font here for test : http://www.fonts101.com/fonts/view/Uncategorized/28374/Tahoma_Small_Cap.aspx)
String labelText ="Dfd";
JLabel lbl = new JLabel(labelText);
Font g=null;
Font g2=null;
try {
InputStream myStream = new BufferedInputStream(new FileInputStream("/home/alain/Bureau/tahomscb/tahomscb.ttf"));
g = Font.createFont(Font.TRUETYPE_FONT, myStream);
g2 = g.deriveFont(Font.PLAIN, 24);
} catch (Exception ex) {
ex.printStackTrace();
System.err.println("font not loaded.");
}
lbl.setFont(g2);
this.add(lbl); //this is the parent component