I want to add an image on the screen when an event occurs. In my case, this would be from a button being clicked. I attempted to solve this myself, but the image isn't appearing. I don't know what is wrong.
My code:
JButton button2 = new JButton("+");
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
System.out.println("button #2 working");
label2 = new JLabel(new ImageIcon(this.getClass().getResource("50.png")));
label2.setLocation(10, 60);
label2.setSize(300, 532);
add(label2);
//? Not working
}
});
button2.setSize(50, 40);
button2.setFont(new Font("Arial", 1, 20));
button2.setLocation(110, 592);
button2.setBackground(Color.ORANGE);
content.add(button2);
I actually have done something similar to what you are trying to achieve. However, I achieved this by using a different method instead. You could for example create a class MyPanel which extends JPanel and override the paintComponent() method. In the paintComponent() method you can call g.drawImage(yourImage, 0, 0,null); to add the image to your panel. Then it is a matter of creating an instance of MyPanel and adding it wherever you want on the GUI. Also, do not forget to call repaint() after you have clicked the button or you will not see the change.
Related
i'm trying to hide the current frame, when the user clicks the button
but it generates an error
i have tried to create a method and call it in the actionlistener but it still not ok
JButton btnAdd = new JButton("Add");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
AddBook add1=new AddBook();
add1.show();
frame.setVisible(false);
}});
btnAdd.setBounds(135, 113, 101, 49);
contentPane.add(btnAdd);
frame cannot be resolved
Because the frame variable is not accessible in the scope your ActionListener is being defined.
Either:
Make frame accessible using a field or simply defining the ActionListener after the frame (eg: JFrame frame = new JFrame(..); btn.addActionListener(...);), but before the setVisible(true).
Try to find the Window in which the button is, SwingUtilities::windowForComponent may help, or if you want the focused window, combine KeyboardFocusManager::getCurrentKeyboardFocusManager, KeyboardFocusManager::getFocusOwner and SwingUtilities::windowForComponent.
This question already has answers here:
How to find JLabel that was clicked and show ImageIcon from it?
(2 answers)
Closed 7 years ago.
I have a JFrame opening with 12 different pictures. I want to click on one and then in the new JFrame, show that same picture. In my code, shirts is my JFrame with the 12 pictures and I want the clicked picture to appear in the new JFrame called sizes. I made an ArrayList of type JLabel called select. Here is my code:
final JFrame shirts = new JFrame("T-shirts");
JPanel panel = new JPanel(new GridLayout(4, 4, 3, 3));
for (int i = 1; i < 13; i++) {
l = new JLabel(new ImageIcon("T-shirts/"+i+".jpg"), JLabel.CENTER);
l.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
l.setFont(l.getFont().deriveFont(20f));
panel.add(l);
select.add(l);
}//end of for loop
panel.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
sizes = new JFrame("Shopping");
sizes.setVisible(true);
sizes.setSize(500, 500);
sizes.setLocation(100,200);
shirts.dispose();
for(int i=0; i<12; i++){
if(e.getSource()==select.get(i)){
JLabel addition = newJLabel(newImageIcon(select.get(i).getText()));
//sizes.add(select.get(i));//Picture isn't added!!
}//end of if
}//end of for
}//end of method
});//end of listener
shirts.setContentPane(panel);
shirts.setSize(1000, 1000);
shirts.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
shirts.setVisible(true);
Start with How to Write a Mouse Listener.
Basically, you want to register a MouseListener with the JLabel which represents your picture and implement it's mouseClicked method.
You then want to get the Icon property of the JLabel that was clicked and pass that to your new frame, which you can simply use to set the Icon property of another JLabel
Something like...
addition.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
JLabel label = (JLabel) e.getComponent();
Icon icon = label.getIcon();
// Create new frame and pass it the icon value
}
});
as an example
You might also like to take a look at The Use of Multiple JFrames, Good/Bad Practice? and consider using either a CardLayout or JDialog instead of another JFrame ... which could become messy
You can use a JButton and make it look like a JLabel:
JButton button = new JButton( new ImageIcon("..." ));
button.setBorderPainted( false );
button.setContentFilled( false );
button.setFocusPainted( false );
button.addActionListener( new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
JButton button = (JButton)e.getSource();
Icon icon = button.getIcon();
// do something with the Icon.
}
});
Then you can add an ActionListener to the button.
An ActionListener is more reliable than using a MouseListener and handling the mouseClicked event. The mouseClicked event is only generated when a mousePressed and mouseReleased event is generated at the same mouse point. So if the mouse moves by even pixel between the two event you will not get a mouseClicked event which users think is a random problem.
Try making each picture a JButton, or at least placing an invisible button behind each picture. Then, when they are pressed in the ActionListener extended class, have the new JFrame be created, with the picture large.
I have the following Java method, which I am trying to use to add some buttons to a GUI:
private void addButtons(){
JButton addBtn = new JButton("Add");
JButton saveBtn = new JButton("Save");
addBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
/*Code to be added here */
}
});
addBtn.setBounds(1150, 135, 30, 15);
saveBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
/*Code to be added here */
}
});
saveBtn.setBounds(1190, 135, 30, 15);
System.out.println("'addButtons()' method is being called");
}
I am calling this method from a private void initialize() method in the same class. I know that initialize() is being called because all of the other method calls that it performs are happening, and displaying in the GUI.
However, for some reason, the buttons that I am trying to create and add to my GUI with this method are not being displayed...
Can anyone point out to me why this is, and what I'm doing wrong?
Edit
Apologies- I'm calling the method in a private void initialize() method in the same class:
private void initialize(){
...
(other code that is successfully adding stuff to the GUI)
...
addButtons();
}
I am seeing the System.out.println() message from the end of the addButtons() method in the console when I click the button that calls the initialize() method... and all of the other code from the `initialize()' method is being called (for example, it's opening a new window, and adding some text, textboxes and tables to the window)...
Edit 26/06/2014 # 09:15
The class where I have written this code extends JPanel:
public class JConfigurationPane extends JPanel implements UndoableEditListener, ChangeListener
I am now no longer using the addButtons() method that I had previously mentioned, and am trying to use my initialize() method to add the buttons to the JPanel:
public void initialize(){
// Code that initialises other elements in the GUI, such as Jlabels, layout, etc
JButton addBtn = new JButton("Add");
JButton saveBtn = new JButton("Save");
this.add(addBtn);
this.add(saveBtn);
}
But the buttons still don't appear when I run the application, even though all of the other graphical elements in the initialize() method do... Any ideas why this is? I've added some debug before and after where I create the buttons, and where I add them to the GUI- the debug is displayed in the console, so the code to create and add the buttons must be called...
Where are you adding these buttons to the form?
You are creating buttons in the method yes, and attaching listeners to these but the buttons themselves aren't being added to the form which is why you cant see them.
e.g you should be doing something like:
yourForm.add(addBtn);
yourForm.add(saveBtn);
or add these to a JPanel or something - finally making sure you add this JPanel
I managed to solve this by moving the code from my addButtons() method to my initialize() method, and setting the bounds of each button immediately after creating it:
JButton addBtn = new JButton("Add");
addBtn.setBounds(1000, 135, 75, 25);
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 have a JButton which I want to create a new JButton with when it is pressed I have added an ActionListener that looks like this, but it doesn't add another JButton.
public void actionPerformed(ActionEvent e){
Object command = e.getSource();
if(command.equals(play)){
ImageIcon i1 = new ImageIcon("NewGame.png");
width = i1.getIconWidth();
height = i1.getIconWidth();
newGame = new JButton(i1);
newGame.setBorderPainted(false);
newGame.setContentAreaFilled(false);
newGame.setSize(width, height);
newGame.setLocation(600,100);
add(newGame);
System.out.println("It Works");
}
}
How would I make it so that when I press the already existing JButton this one will be added?
Make sure to revalidate and repaint after adding the button
revalidate();
repaint();
From the use of setSize and setLocation, it appears you are using a absolute positioning or null layout. Use a layout manager.
You must call repaint() after adding it.
if you are not getting exception, then you will need to refresh or repaint the container which will old the new button.