How can I change my images when an action is performed? My images are stored in the project.
Declared images
image = new ImageIcon ("1.jpg");
image2 = new ImageIcon ("3.jpg");
image3 = new ImageIcon ("2.jpg");
picLabel = new JLabel(image);
ActionListener Class
public void actionPerformed(ActionEvent e){
if(e.getSource().equals(A)) {
image = new ImageIcon ("1.jpg");
//picLabel = new JLabel(image); didn't work
} else if(e.getSource().equals(B)) {
image = new ImageIcon ("2.jpg");
//picLabel = new JLabel(image2); didn't work
} else if(e.getSource().equals(C)) {
image = new ImageIcon ("3.jpg");
//picLabel = new JLabel(image3); didn't work
}
}
If you assign a new JLabel to the picLabel label, you create a new object that is not part of your UI. The existing JLabel in your UI is referenced by picLabel, so calling
picLabel.setIcon(image);
should set the Icon for the existing JLabel.
You must call
picLabel.setIcon(image);
Keep a reference to picLabel in your class and in the action listener call picLabel.setIcon(new ImageIcon("Whatever.jpg")); to change the picture.
Related
Im trying to get an image to display on a frame for a game Im creating. Rather than extend any JPanels or JFrame, I just create multiple frame classes and one action class.Im currently having trouble getting an image to display on a test frame I created. My code compiles but when I click on the frame it shuts down. Thanks!
P.S this is only part of my code. I heard its not good to post total code online.
Code:
public void testframe(){
testframe = new Frame("Main Menu");
testframe.setSize(1600,1600);
try{
myPicture = ImageIO.read(new File("basic.png"));
}
catch(IOException e){
e.printStackTrace();
//FirstFrame.setVisible(true);
//testframe.setVisible(false);
}
JLabel picLabel = new JLabel(new ImageIcon(myPicture));
testframe.add(picLabel);
//testframe.drawImage(myPicture,"png", );
testframe.setVisible(true);
}
private void showButtonDemo(){
Font myFont = new Font("Serif", Font.ITALIC | Font.BOLD, 12);
Font newFont = myFont.deriveFont(50F);
headerLabel.setText("SNAKE GAME");
headerLabel.setFont(newFont);
statusLabel.setText("By Tejas and Ashwin");
statusLabel.setFont(newFont);
Button startButton = new Button("Start Game");//begins game
Button snakecolorButton = new Button("Choose Snake Color");//selects snake color
Button themeColorButton = new Button("Choose Theme");//selects two colors(1 primary and 1 secondary)
Button InstructionsButton = new Button("Instructions");
Button testbutton = new Button("test");
testbutton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//testframe();
//testframe.setVisible(true);
FirstFrame.setVisible(false);
}
});
First, Sharing code is needed for help so if you think the code in anyway involes what you need help with share it, else wise it doesnt matter...
For the question at hand, You can use a jlable and set a iamge for it to display a png but the BEST way to do this would be to create this for a game would be to create a class (Player for example) and a render method, On render you display the image at the loc (XYZ) of the player,
ImageIcon image = new ImageIcon("C:\\Users\\Name\\Pictures\\image.png");
JLabel imageLabel = new JLabel(image);
frame.add(imageLabel);
Remember to set it as visible and set its bounds,
I'm trying to get the Thumbnail that is associated to a particular file, and then resize it. I've been testing on Mac, and haven't been able to find a solution that would allow me to achieve this.
Code so far:
import com.apple.laf.AquaIcon;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
public class TestSystemIcon extends JFrame
{
JPanel panel;
ImageIcon icon;
public TestSystemIcon()
{
panel = new JPanel();
JButton button = new JButton("Open...");
final JLabel label = new JLabel();
icon = null;
final JPanel en = new JPanel(new FlowLayout(FlowLayout.CENTER));
label.setHorizontalAlignment(SwingConstants.CENTER);
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
JFileChooser fileChooser = new JFileChooser();
if(fileChooser.showOpenDialog(null) == JFileChooser.OPEN_DIALOG)
{
File file = fileChooser.getSelectedFile();
icon = resizeIcon(getThumbnail1(file),200,200);
// icon = resizeIcon(getThumbnail2(file),200,200);
System.out.println(icon);
label.setIcon(icon);
en.add(label);
revalidate();
repaint();
}
}
});
panel.add(button);
this.add(panel,BorderLayout.NORTH);
this.add(en,BorderLayout.CENTER);
this.setSize(400,400);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public ImageIcon getThumbnail1(File file)
{
JFileChooser f = new JFileChooser();
Icon i = f.getIcon(file);
//Mac Conversion.
Image image = AquaIcon.getImageForIcon(i);
return new ImageIcon(image);
}
public ImageIcon getThumbnail2(File file)
{
return new ImageIcon(file.getPath());
}
public ImageIcon resizeIcon(ImageIcon imageIcon,int width, int height)
{
return new ImageIcon(imageIcon.getImage().getScaledInstance(width,height,Image.SCALE_SMOOTH));
}
public static void main(String[] args)
{
TestSystemIcon test = new TestSystemIcon();
test.setVisible(true);
}
}
Version1 of getting the thumbnail has following behaviour:
Can open thumbnails
Very small, scaling not suitable.
Version2 of getting thumbnail has following behaviour:
Doesn't display image, despite finding image (System.out proves this).
Except for pdf, where instead it displays the actual file, as opposed to the
thumbnail
When it does work i.e. pdf, it scales nicely.
I know I can use sun.awt.shell.ShellFolder;, however I am aiming for a cross-platform solution.
Thanks for any help
I looked at some code that I have done in the past and seems this works fine when you use JLabel with and ImageIcon, try this code that resized a large image to 100x100,
ImageIcon icon = new ImageIcon("Penguins.jpg");
Image img = icon.getImage().getScaledInstance(100,100,Image.SCALE_SMOOTH);
// if the file is not an image, but a file on the system,
Icon icon = FileSystemView.getFileSystemView().getSystemIcon(file);
Image img = ((ImageIcon) icon).getImage().getScaledInstance(100,100,Image.SCALE_SMOOTH);
ImageIcon icon1 = new ImageIcon(img);
JLabel image = new JLabel(icon1);
I would like to use JLabel(Icon) to show a Image which is from my website(http://xxx.xxx.xxx.xxx/java_pic/test.jpg).
And I have a refresh button to new a new JLabel and ImageIcon(in order to get the newest image)
The program run successfully...but when I upload a new image to override the old one(http://xxx.xxx.xxx.xxx/java_pic/test.jpg), I press the refresh button... nothing happened!
I restart my program... and the new image now appears... why?
Shouldn't it reload the image from website when I new a ImageIcon again?
public void refresh(){
URL iconUri = null;
iconUri = new URL("http://XXX.XXX.XXX.XXX/java_pic/test.jpg");
ImageIcon imageIcon = new ImageIcon(iconUri);
JLabel imageLabel = new JLabel(imageIcon);
frame.add(imageLabel);
...
...
}
when I click the refresh button, it would call the refresh()...why?
Thanks!
The image is cached. Flush to clear the cache:
imageIcon.getImage().flush();
I am trying to display a string and a BufferedImage onto a JFrame that both come as output from a method. I am not able to separate the String from the image, therefore I need to add both to the JFrame.
Here is the code I have do far and nothing is displaying. Thank you very much for your help in advance.
String path = getUserInfo("abc123"); <-- method that returns a string and a buffered image
BufferedImage image = null;
try {
image = ImageIO.read(new File(path));
} catch (IOException ex) {
Logger.getLogger(InstagramClient.class.getName()).log(Level.SEVERE, null, ex);
}
JFrame f = new JFrame();
f.setSize(400,400);
f.setVisible(true);
ImageIcon icon = new ImageIcon(image);
JLabel label = new JLabel(icon, JLabel.CENTER);
JOptionPane.showMessageDialog(null, label, "icon", -1);
You can render the string over the image using drawString(), as shown here.
Alternatively, you can use label.setText() and rely on the label's horizontal & vertical alignment for positioning, as illustrated here.
Basically, you can use the label's setText method to supply a text value for the label.
You also need to "add" the label to the frame, or it won't display anything.
String path = getUserInfo("abc123"); <-- method that returns a string and a buffered image
BufferedImage image = null;
try {
image = ImageIO.read(new File(path));
} catch (IOException ex) {
Logger.getLogger(InstagramClient.class.getName()).log(Level.SEVERE, null, ex);
}
JFrame f = new JFrame();
ImageIcon icon = new ImageIcon(image);
JLabel label = new JLabel("This is some text", icon, JLabel.CENTER);
f.add(label);
f.setVisible(true);
Hovercraft Full Of Eels actually answered my question. I wanted to return both a String and BufferedImage but now I know that is not possible. Thank you all for your help :)
I've created GUI for my application using Netbeans' GUI Builder. I am trying to display a JFrame containing a JLabel with an image, and I can't get the Image to display.
My generated code :
private void initComponents() {
//...
jLabel1 = new JLabel(new ImageIcon(myPicture));
}
And my class code:
public class GUIWindow extends javax.swing.JFrame {
BufferedImage myPicture;
/** Creates new form GUIWindow */
public GUIWindow() throws IOException {
myPicture = ImageIO.read(new File("images/logo.png"));
initComponents();
this.add(jLabel1);
}
}
but I still don't see an image ... (path to the image file is fine) its sth like:
my-project :
/build
/dist
/images/logo.png
/nbproject
/src (here I have all my source files)
/build.xml
/manifest.mf
you can use like this
URL imgSmartURL = this.getClass().getResource("your image path");
jLabel1 = new JLabel(new ImageIcon(imgSmartURL), JLabel.CENTER);
I would do something like this instead.
JLabel dice1 = new JLabel();
ImageIcon one = new ImageIcon("dice/1.png");
//set dice1 position
dice1.setLocation(20, 100);
dice1.setSize(115, 115);
dice1.setIcon(one);
gamepanel.add(dice1);
If you are using netbeans you can directly add an image to a jLabel by setting properties. Right click on the jLabel -> properties -> icon -> (if it's external image) import to project(upload your image) -> ok .
It'l be added into your jLabel.
I'd suggest you copy the image in a seperate folder(images).
Then use Toolkit.getDefaultToolkit().getImage("images/A.png");
I believe there's a similar question
private ImageIcon imageIconPrint =
new ImageIcon(getClass().getResource("/image/print.gif"));
create button and add follwing code:
jbtCanada.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jlblFlag.setIcon(imageIconCanada);
}
});
this would help i think