How to change the image of a JLabel - java

I know this was answered a few times before, but the ones i found were answered with blocks of program specific code and i was having trouble discerning what specific code actually changed the image. I'm trying to change the jlabel image on my GUI during runtime by pushing a button.
public JPanel createContentPane (){
JPanel totalGUI = new JPanel();
totalGUI.setLayout(null);
pictureArea = new JPanel();
pictureArea.setLayout(null);
pictureArea.setLocation(560, 0);
pictureArea.setSize(860, 500);
totalGUI.add(pictureArea);
picture = new JLabel(image);
picture.setLocation(0, 0);
picture.setSize(800, 800);
picture.setHorizontalAlignment(0);
pictureArea.add(picture);
//skipping other code
decision2 = new JButton("Next");
decision2.setLocation(160, 20);
decision2.setSize(70, 30);
decision2.addActionListener(this);
buttonPanel.add(decision2);
return totalGUI;
}
public void actionPerformed(ActionEvent e) {
//skipped other code
else if(e.getSource() == decision2){
//code i need for changing the image
}
}
Thank you for any help you can provide.

You're looking for JLabel's setIcon method
label.setIcon(new ImageIcon(getClass().getResource("/path/to/image.png")));

Have you tried this ?
//code i need for changing the image
call the function that has the JLabel defined, and pass the image_location eg: images/image.png
yourfunction(String imagelocation)
{
BufferedImage bufImg=ImageIO.read(new File(image_location));
jlabel.setIcon(new ImageIcon(bufImg));
}
reference:http://docs.oracle.com/javase/7/docs/api/

Related

How do I use a gif file in a Java program?

I'm trying to add a .gif image to a JButton, but can't seem to get the image to load when i run the code. I've included a screenshot. Included is the frame that's created. I'd really appreciate any help that can be provided. Stack is telling me I can't enter images yet, so it created a link for it. I'm also going to enclose the actual code here:
package java21days;
import javax.swing.*;
import java.awt.*;
public class ButtonsIcons extends JFrame {
JButton load, save, subscribe, unsubscribe;
public ButtonsIcons() {
super("Icon Frame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
//Icons
ImageIcon loadIcon = new ImageIcon("load.gif");
ImageIcon saveIcon = new ImageIcon("save.gif");
ImageIcon subscribeIcon = new ImageIcon("subscribe.gif");
ImageIcon unsubscribeIcon = new ImageIcon("unsubscribe.gif");
//Buttons
load = new JButton("Load", loadIcon);
save = new JButton("Save", saveIcon);
subscribe = new JButton("Subscribe", subscribeIcon);
unsubscribe = new JButton("Unsubscribe", unsubscribeIcon);
//Buttons To Panel
panel.add(load);
panel.add(save);
panel.add(subscribe);
panel.add(unsubscribe);
//Panel To A Frame
add(panel);
pack();
setVisible(true);
} //end ButtonsIcon Constructor
public static void main(String[] arguments) {
ButtonsIcons ike = new ButtonsIcons();
}
} //end ButtonsIcon Class
enter image description here
The easiest way is.
Label or Jbutton and what ever else supports HTML 3.5
JLabel a = new JLabel("");
add that to your container.
Haven't figured out how to enter code sorry

How to overlap a JPanel(background) and a JTextField

I am creating a log in application for someones graduation, I need several text fields and a background, I have added the background and now need to add the text fields, the problem is that they won't seem to go on top of each other.
I have tried them each separately and without one another they both work perfectly but i can't get them to stack, I have seen several answers on this site to deal with a similar problem but for this application I need to put several text fields on the background as apposed to just one, here is what I have thus far...
//creates the frame with a title as a parameter
JFrame frame = new JFrame("Sign In Sheet");
//sets the size
frame.setSize(1000, 556);
//makes it so the application stops running when you close it
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//puts it in the center of the screen
frame.setLocationRelativeTo(null);
//makes it so you can't resize it
frame.setResizable(false);
//setting the background by looking for the image
try{
frame.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("C:/Users/Gabriel R. Warner/Desktop/clouds.png")))));
}catch(IOException e){
//and prints an error message if it's not found
System.out.println("well it didn't work");
}
//adding text fields with names apropriate to function
JTextField name1 = new JTextField();
name1.setPreferredSize(new Dimension(200, 15));
name1.setBackground(Color.WHITE);
frame.add(name1);
//makes frame visible
frame.setVisible(true);
Simply stated the text field won't show up with the background and all the results only offer answers for a single text field
The problem is in this line: frame.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("C:/Users/Gabriel R. Warner/Desktop/clouds.png")))));
In this line you set a JLabel as the content pane of your JFrame. Then, you frame.add(name1); So you are adding a JTextField to a JLabel...Well this does not seem right, right?
The answer would be to create a new JPanel, add the background image to this panel, set the panel as the content pane of the frame and finally add the textfield to the panel/contentpane.
An example:
#SuppressWarnings("serial")
public class FrameWithBackgroundImage extends JFrame {
public FrameWithBackgroundImage() {
super("Sign In Sheet");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
try {
Image bgImage = loadBackgroundImage();
JPanel backgroundImagePanel = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(bgImage, 0, 0, null);
}
};
setContentPane(backgroundImagePanel);
} catch (IOException e) {
e.printStackTrace();
}
JTextField textField = new JTextField(10);
add(textField);
}
private Image loadBackgroundImage() throws IOException {
File desktop = new File(System.getProperty("user.home"), "Desktop");
File image = new File(desktop, "img.jpg");
return ImageIO.read(image);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new FrameWithBackgroundImage().setVisible(true);
});
}
}
Preview:
Worth to read question: Simplest way to set image as JPanel background

JPanel background image doesn't apply to a JPanel inside it

I'm working on a simple registration window that appears when the java app opens.
It's a JFrame, that has a JPanel in it, which has text fields, labels, and another panel which also contains text fields and labels.
My problem is that the outside panel has a background image, but it doesn't apply to the panel inside it as seen here:
Here is the whole window code:
public void start() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
ex.printStackTrace();
}
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
frame = new JFrame("Chat");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.setMaximumSize(new Dimension((int)screenSize.getWidth()-1000, (int)screenSize.getHeight()-1000));
frame.setMinimumSize(new Dimension((int)screenSize.getWidth()/2-200,(int) screenSize.getHeight()/2));
frame.setResizable(false);
welcome = new LoginPanel();
welcome.setLayout(new BoxLayout(welcome, BoxLayout.Y_AXIS));
welcome.setBorder(BorderFactory.createEmptyBorder(50, welcome.getWidth()/2-500, 50, welcome.getWidth()/2 -500));
//repaintThread = new Thread(new RepaintRunnable(frame, welcome));
//repaintThread.start();
request = new JLabel("Please fill the required fields below:");
request.setFont(new Font("Serif", Font.BOLD, 20));
request.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0));
request.setAlignmentX(Component.CENTER_ALIGNMENT);
userInfo = new JPanel();
userInfo.setLayout(new BoxLayout(userInfo, BoxLayout.Y_AXIS));
userInfo.setAlignmentX(Component.CENTER_ALIGNMENT);
Font fieldType = new Font("Serif", Font.PLAIN, 15);
PlainDocument doc = new PlainDocument();
doc.setDocumentFilter(new NameDocument());
enterFirstName = new JLabel("First name:");
enterFirstName.setAlignmentX(Component.LEFT_ALIGNMENT);
enterFirstName.setFont(fieldType);
firstName = new JTextField(20);
firstName.setMaximumSize(firstName.getPreferredSize());
firstName.setDocument(NameDocument.getNewNameDocument(NameDocument.NO_SPACE));
firstName.getDocument().addDocumentListener(new ChangeDocumentListener());
firstName.addActionListener(new ConfirmListener());
firstName.setAlignmentX(Component.LEFT_ALIGNMENT);
enterSecName= new JLabel("Surname:");
enterSecName.setAlignmentX(Component.LEFT_ALIGNMENT);
enterSecName.setFont(fieldType);
secName = new JTextField(30);
secName.setMaximumSize(secName.getPreferredSize());
secName.setDocument(NameDocument.getNewNameDocument(NameDocument.HAS_SPACE));
secName.getDocument().addDocumentListener(new ChangeDocumentListener());
secName.addActionListener(new ConfirmListener());
secName.setAlignmentX(Component.LEFT_ALIGNMENT);
enterNickname = new JLabel("Nickname (how other people will see you in chat):");
enterNickname.setAlignmentX(Component.LEFT_ALIGNMENT);
enterNickname.setFont(fieldType);
nickname = new JTextField(30);
nickname.setMaximumSize(nickname.getPreferredSize());
nickname.setDocument(NameDocument.getNewNameDocument(NameDocument.NO_SPACE));
nickname.addActionListener(new ConfirmListener());
nickname.setAlignmentX(Component.LEFT_ALIGNMENT);
userInfo.add(enterFirstName);
userInfo.add(firstName);
userInfo.add(enterSecName);
userInfo.add(secName);
userInfo.add(enterNickname);
userInfo.add(nickname);
confirm = new JButton("Submit");
confirm.setAlignmentX(Component.CENTER_ALIGNMENT);
confirm.setEnabled(false);
confirm.addActionListener(new ConfirmListener());
welcome.add(request);
welcome.add(userInfo);
welcome.add(new Box.Filler(new Dimension(10, 10), new Dimension(10, 10), new Dimension(10, 10)));
welcome.add(confirm);
frame.getContentPane().add(BorderLayout.CENTER, welcome);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
And here is the LoginPanel code(the outside JPanel):
public class LoginPanel extends JPanel {
public void paintComponent(Graphics g) {
try {
super.paintComponent(g);
BufferedImage background = ImageIO.read(new File("Background.jpg"));
g.drawImage(background, 0, 0, getWidth(), getHeight(), null);
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
it'll also be great if someone will give me advice on how to make this code better, since I'm beginner in Java.
Remember to call setOpaque(false); on any inner JPanels (and on some other components -- though not all) that cover up your image-displaying JPanel. This will allow background images to show through. You don't have to do this with JLabels as they are see-through (non-opaque) by default, but you do with JPanels.
So for you it will be:
userInfo = new JPanel();
userInfo.setOpaque(false);
One other problem is that you should never read in images from within a paintComponent method. This method may be called often, and why re-read the image when it can and should be read in only once. And more importantly, this method should be fast as possible since slowing it down needlessly will slow down the perceived responsiveness of your program. Read the image in once, and store it in a variable that is then displayed within paintComponent.
e.g.,
public class LoginPanel extends JPanel {
private BufferedImage background;
public LoginPanel(BufferedImage background) {
this.background = background;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (background != null) {
g.drawImage(background, 0, 0, getWidth(), getHeight(), this);
}
}
}
Read the image in and then pass it into the constructor of your LoginPanel class.
Not related to your problem but:
frame.getContentPane().add(BorderLayout.CENTER, welcome);
Since JDK 4 you don't need to use the getContentPane() method you can just use frame.add(...) and the component will be added to the content pane.
Also you are using the wrong add(...) method. You are using add(constraint, component). If you read the API for the method it will tell you to use the add(component, constraint) method.
So you could be using:
frame.add(welcome, BorderLayout.CENTER);

Resize JButtons in a BoxLayout

I'm trying to make a simple menu for my game. I have 4 buttons in the center and I want to make them a little bit bigger and center them.
The last part worked but I can't seem to call any of my JButtons and do a .setSize / .setPreferedSize(new Dimension()) on it.
public class mainMenu extends JFrame {
private JButton start, highscore, help, stoppen;
public mainMenu() {
super("Master Mind");
maakComponenten();
maakLayout();
toonFrame();
}
private void maakComponenten() {
start = new JButton("Start");
start.setBackground(Color.gray);
highscore = new JButton("Higscores");
help = new JButton("Help");
stoppen = new JButton("Stoppen");
}
private void maakLayout() {
JPanel hoofdmenu = new JPanel();
hoofdmenu.setLayout(new BoxLayout(hoofdmenu, BoxLayout.Y_AXIS ));
hoofdmenu.add(start);
start.setAlignmentX(CENTER_ALIGNMENT);
hoofdmenu.add(highscore);
highscore.setAlignmentX(CENTER_ALIGNMENT);
hoofdmenu.add(help);
help.setAlignmentX(CENTER_ALIGNMENT);
hoofdmenu.add(stoppen);
stoppen.setAlignmentX(CENTER_ALIGNMENT);
super.add(hoofdmenu);
}
private void toonFrame() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
setSize(500,500);
}
public static void main(String[] args) {
new mainMenu();
}
}
As an example, to change the size of the "Start" button,
change :
start1 = new JButton("Start");
to
start1 = new JButton("Start") {
{
setSize(150, 75);
setMaximumSize(getSize());
}
};
The problem is that JFrames use BorderLayout by default, which means that your JPanel will naturally fill the space.
Before adding your JPanel, call the following code to change the JFrame's layout to null and use the JPanel's settings instead.
this.setLayout(null);
JPanel hoofdmenu = new JPanel();
hoofdmenu.setBounds(0,0, 400, 100);
Alternatively, you could set the maximum size of the JButtons
Dimension maxSize = new Dimension(100, 100);
start.setMaximumSize(maxSize);
highscore.setMaximumSize(maxSize);
help.setMaximumSize(maxSize);
stoppen.setMaximumSize(maxSize);
Here's another example following behind the previous two - I'm making a soundboard program, and this is actually a sample from it - The JPanel actually is needed, agreeing to the second post.
JFrame frame = new JFrame();
JPanel menuPanel = new JPanel();
JButton Button1 = new JButton("<BUTTON NAME 1>");
Button1.setSize(80, 30);
Button1.setLocation(4, 4);
JButton Button2 = new JButton("<BUTTON NAME 2>");
Button2.setSize(80, 30);
Button2.setLocation(90, 4);
Ah, and another thing - You created the buttons in a different block from the second piece of code. Doing that causes the other blocks to not see it. You need to declare them outside the block so all the blocks can see them.

ImageLoading in JPanel using JFileChooser

I am trying to load an image into a JPanel using JFileChooser. But when I try to run the program and load a selected image nothing happens in the JPanel. I am attaching the source code snippet here:
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
FileFilter filter = new FileNameExtensionFilter("Image files","jpeg","jpg");
fileChooser.setFileFilter(filter);
int result = fileChooser.showOpenDialog(null);
if(result == fileChooser.APPROVE_OPTION){
imgFile = fileChooser.getSelectedFile();//imgFile is File type
try{
myPicture = ImageIO.read(imgFile);//myPicture is BufferedImage
JLabel picLabel = new JLabel(new ImageIcon( myPicture )) ;
imagePanel.add( picLabel );
imagePanel.repaint();
System.out.println("You have selected "+imgFile);
}catch(Exception e){
e.printStackTrace();
}
}
}
Can anyone shed light on this?
The problem is that I have added two panels in my frame.
You might compare what you're doing with this complete example that uses two panels: a file chooser on the left and a display panel on the right.
I think this might help you...
Object selectedItem = jComboBox14.getSelectedItem();
ImageIcon picturetoInsert = new ImageIcon(selectedItem.toString());
JLabel label = new JLabel("", picturetoInsert, JLabel.CENTER);
JPanel panel = new JPanel(new GridLayout(1, 1));
panel.add(label, BorderLayout.CENTER);
jInternalFrame22.getContentPane();
jInternalFrame22.setContentPane(panel);
jInternalFrame22.setVisible(true);
Why don you try with the paint component?
class imagePanel extends JPanel
{
BufferedImage image;
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if(image != null)
{
g.drawImage(image, 0, 0, this);
}
}
}
There could be a few reasons for this. You could try
imagePanel.invalidate()
before the repaint call to force it to redraw.
Or possibly the label is to small and needs resizing since there may not have been an image before. You could try invoke the
frame.pack();
method to get the frame to recompute its component sizes.
Or you could try force the size of the label (setting its min size) to ensure it has enough space to show the image.

Categories