I want to load an image to a JButton in a java application so when I click the button to show the image and when I click it again to hide the image.I don't want the image to be loaded to a label but on the button.
I'm thinking in SWT, but I guess this works for Swing too.
final JButton button = new JButton();
final ImageIcon icon = new ImageIcon(image);
button.setIcon(icon);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button.setIcon( button.getIcon() == null ? icon : null );
}
});
You can try this:
ImageIcon iconStart = new ImageIcon("start.jpg");
JButton bttnStart = new JButton(iconStart);
Related
I want to set the icon on a label when button pressed once if pressed twice it will remove i have used label.setIcon(null); but it is not working fine for me.
public void actionPerformed(ActionEvent e) {
if (!"submit".equals(e.getActionCommand()))
{
JButton button = (JButton) e.getSource();
int X = button.getLocation().x;
int Y = button.getLocation().y;
JLabel tick=new JLabel();add(tick);
tick.setBounds(X+400,Y+15,50,50);
if(arr.contains(e.getActionCommand()))
{
tick.setIcon(null);
arr.remove(e.getActionCommand());
}
else
{
image=new ImageIcon(imageList[0]);
tick.setIcon(image);
arr.add(e.getActionCommand());
}
Don't recreate JLabel and don't add it on each click
JLabel tick=new JLabel();
add(tick);
Create class' field instead and create the label once. If it's initialized just tick.setIcon(null).
Code in Question
There isn't an actionListener for the image thumbnails, yet when clicked they update the image.
From this webpage.
Edit: I am currently importing images using JFileChooser and then creating a thumbnail and displaying the full image in a similar way to this, although not using ImageIcons. But would like to use this method so when I add an image it adds to the list and allows me to click the thumbnail to show that image.
However mine using actionListeners to change when something is pressed but this doesn't and can't understand the code where it does.
Thanks
Edit2:
Regarding the repaint option:
I have a class which extends component which then calls a repaint function.
public class Image extends Component {
private BufferedImage img;
//Print Image
public void paint(Graphics g) {
g.drawImage(img, 0, 0, null);
}
}
I then have a class with all my Swing components which call methods from other classes.
Image importedImage = new Image(loadimageone.openFile());
Image scaledImage = new Image();
// Save image in Buffered Image array
images.add(importedImage.getImg());
// Display image
imagePanel.removeAll();
imagePanel.add(importedImage);
imagePanel.revalidate();
imagePanel.repaint();
previewPanel.add(scaledImage);
previewPanel.revalidate();
previewPanel.repaint();
If I remove the revalidate or repaint it wont' update the image on the screen.
Edit 3:
This is the code on how I implemented the dynamic buttons:
//Create thumbnail
private void createThumbnail(ImpImage image){
Algorithms a = new Algorithms();
ImpImage thumb = new ImpImage();
//Create Thumbnail
thumb.setImg(a.shrinkImage(image.getImg(), 75, 75));
//Create ImageIcon
ImageIcon icon = new ImageIcon(thumb.getImg());
//Create JButton
JButton iconButton = new JButton(icon);
//Create ActionListener
iconButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
bottomBarLabel.setText("Clicked");
imagePanel.removeAll();
imagePanel.add(images.get(position)); //Needs Fixing
imagePanel.revalidate();
}
});
//Add to previewPanel
previewPanel.add(iconButton);
previewPanel.revalidate();
previewPanel.repaint();
}
It looks like it uses ThumbnailAction instead which extends AbstractAction (at the very bottom of the code). Swing components can use Actions instead of ActionListeners. The advantage of Actions is that buttons can share an Action and they will automatically use the same key-bindings etc.
http://docs.oracle.com/javase/tutorial/uiswing/misc/action.html
EDIT: I have added some code demonstrating that you do not need to explicitly repaint(). Give it a try.
public static void main(String args[]) {
JFrame frame = new JFrame();
frame.setSize(200, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(2, 1));
final JLabel iconLabel = new JLabel();
JButton button = new JButton("Put Image");
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
try {
iconLabel.setIcon(new ImageIcon(ImageIO.read(fc.getSelectedFile())));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
panel.add(iconLabel);
panel.add(button);
frame.add(panel);
frame.setVisible(true);
}
EDIT 2 (There is no Edit 2)
EDIT 3: Try this
public class MyActionListener implements ActionListener {
private JPanel imagePanel;
private Image image;
public MyActionListener(JPanel imagePanel, Image image) {
this.imagePanel = imagePanel;
this.image = image;
}
#Override
public void actionPerformed(ActionEvent arg0) {
System.out.println("Clicked");
imagePanel.removeAll();
imagePanel.add(image); //Needs Fixing
imagePanel.revalidate();
}
}
I'm getting the error message null pointer exception on the line img.setIcon(bg); in the controller class in my action listener and I'm not sure why. I've commented where the error is highlighted. Any ideas on why?
public class Display {
public ImageIcon bg;
public JLabel img;
public void UI() {
Controller listener = new Controller();
bg = new ImageIcon("prophase.png");
img = new JLabel(bg, JLabel.CENTER);
JFrame gameFrame = new JFrame();
JPanel top = new JPanel();
JPanel bottom = new JPanel();
JPanel imgPane = new JPanel();
JPanel panel1 = new JPanel();
imgPane.setLayout(new BorderLayout());
panel1.setLayout(new BorderLayout());
panel1.setOpaque(false);// !!
top.setBorder(BorderFactory.createTitledBorder(""));
bottom.setBorder(BorderFactory.createTitledBorder(""));
JLabel jl = new JLabel("What stage of mitosis is this?", JLabel.CENTER);
imgPane.add(img);// center
top.add(jl);// top center
top.add(listener.wordListener());// top center
bottom.add(listener.answer);// bottom
panel1.add(imgPane, BorderLayout.CENTER);// background image (center)
panel1.add(top, BorderLayout.NORTH);// text field and jlabel (top)
panel1.add(bottom, BorderLayout.SOUTH);// blank spaces and letters used
gameFrame.setJMenuBar(menuBar());
gameFrame.setTitle("Mitosis");
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameFrame.setIconImage(new ImageIcon("logo.png").getImage());
gameFrame.setResizable(false);
gameFrame.add(panel1);
gameFrame.setSize(400, 300);
gameFrame.setLocationRelativeTo(null);
gameFrame.setVisible(true);
}
}
another class:
public class Controller {
Display display = new Display();
private JFrame dialogFrame = new JFrame();
private ImageIcon logo = new ImageIcon("logo.png");
public String word;
public JLabel answer = new JLabel(" ", JLabel.CENTER);
public JTextField wordListener() {
JTextField tf = new JTextField(10);
tf.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {// right click key
JTextField tf = (JTextField) e.getSource();
word = tf.getText();
if (word.equalsIgnoreCase("Prophase")) {
answer.setText("Correct!");
ImageIcon bg = display.bg;
JLabel img = display.img;
bg = new ImageIcon("interphase.png");
img.setIcon(bg);//error
answer.setText(" ");
} else {
answer.setText("Incorrect, try again.");
}
tf.setText("");
}// end actionPerformed method
});
return tf;
}
}
The default constructor of Display doesn't initialize the attribute img, which is then initialized to null by default. The exception is clearly due to the fact that you are trying to use img without initializing it anywhere. You should define a default constructor for Display that does something like this:
public Display(){
UI();
}
Because in UI() you are initializing img.
Also you have to initialize your display before using img, like this:
Display display = new Display();
Please check if the path for your image is correct
bg = new ImageIcon("interphase.png");
If a resource is not found you will get a NullPointerException when you try to use that imageicon somewhere else.
Try something along the lines
getClass().getResource("interphase.png");
prepend the directory name if needed, in order to get to your image in your resources.
Also, make sure you are initialising the variable in the Display class before using it.
I'm trying to make a buttom from an image on the JFrame using the ImageIcon and the addMouseListener that will replace the current image with another image by clicking it.
static JPanel jp = new JPanel();
final JLabel jl = new JLabel();
final JFrame jf = new JFrame();
ImageIcon image = new ImageIcon("image1.jpg");
jl.setIcon(image);
jp.add(jl);
jf.add(jp);
jf.validate();
JLabel button = new JLabel(image);
button.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
jl.setIcon( null );
ImageIcon image = new ImageIcon("image2.jpg");
jl.setIcon(image);
}
});
The GUI is displayed with image1.jpg, but the button does not work at all and I can't even test whether the replacement from image1 to image2 works. GUI will not do anything even if I attempt to click the image1.jpg displayed on the window.
Edit: Adjusted JLabel varaible to be final for now. Other similar questions intimate that this method should be working but I can't figure out what is wrong with the code.
Not really sure ActionListener works with JLabel either.
No you can't add an ActionListener to a JLabel. An easier approach is to make a JButton look like a JLabel, then you can add the ActionListener to the button:
JButton button = new JButton(...);
button.setBorderPainted(false);
button.setContentAreaFilled(false);
button.addActionListener(...);
but the button does not work at all
A mouse click is generated when a mousePressed and mouseReleased is received for the same mouse point. So if you move the mouse slightly the event will not get generated. Instead listen for the mousePressed() event.
I am using following class for adding background image to JPanel.
http://www.java2s.com/Code/Java/Swing-JFC/Panelwithbackgroundimage.htm
But when the application is executing and image is changed the new updated image is not shown on screen.
Image image = new ImageIcon(path + item.getItemID() + ".png").getImage();
panel = new ImagePanel(image);
variable path is static path outside workspace.
If you "update JPanel with new JPanel" you are not "updating", you are creating a new JPanel.
Example, we have a green JPanel called "panelTest":
panelTest = new JPanel();
panelTest.setBackground(Color.green);
add(panelTest);
And now we have a button that will change the JPanel background color from green to red, but in a wrong way:
JButton btnTest = new JButton("Test");
btnTest.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
panelTest = new JPanel(); //woops, now we have 2 panels...
panelTest.setBackground(Color.red);
}
});
Note that panelTest was a pointer to a green panel, and now it is pointing to a new JPanel with a red background. This new JPanel has not been added to any container, thus it will not be shown. And the old green panel will stay visible.
The best way to update the image is creating a method inside ImagePanel like:
public void setImage( Image image ) {
this.img = image;
this.repaint();
}
This way you don't have to create a new ImagePanel just for changing the background.