I wrote a class that uses buttons to play radio stations broadcast to the internet.
When the buttons are pressed, I also wanted to have a series of images in the Frame selectively hidden and shown.
I am trying to do this by adding Images, setting "setVisible(false);" and then overriding the setVisible method when the button is clicked.
It isn't viable in it's current state. Is there a way to do this?
I'm pretty new to writing code.
public void actionPerformed(ActionEvent e)
{
JButton button = (JButton)e.getSource();
String text = button.getText();
JLabel img = new JLabel(new ImageIcon("resources/1920.png"));
img.setBounds(642, 230, 100, 100); // x, y, width, height
add(img);
img.setVisible(false);
if (text.equals("1920a"))
{
try
{
getMediaPlayer().setURI(mediaPaths[0]);
img.setVisible(true);
}
catch (URISyntaxException e1)
{
e1.printStackTrace();
}
Each time you press the button, you are creating a new instance of a JLabel and adding it to the screen, but you're not keeping track of them...
// Yet ANOTHER label...which one it is, nobody knows...
JLabel img = new JLabel(new ImageIcon("resources/1920.png"));
img.setBounds(642, 230, 100, 100); // x, y, width, height
add(img);
img.setVisible(false);
If you only want a single image on the screen at a time, then simply change the icon label of a single label...
Start by declaring an instance field for the pictures...
public class ... {
//...
private JLabel pictureLabel;
Add the label to the screen...
public ... { // Public constructor
//...
pictureLabel = new JLabel();
add(pictureLabel);
Now, when you want to change the picture, simply change the icon property of the label...
pictureLabel.setIcon(new ImageIcon("resources/1920.png"));
Related
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 want to make a Swing version TimeBomber, which means when time is counted down to 1 the Bomb will blow up! I have two images, images.png for a bomb in normal state, bomber.jpg for a bomb that has blown up. Apparently I need to change the images.png(which is already in an JLabel) to bomber.jpg when i==1; But I have no idea of how to change the pic location content in ImageIcon and as the change happens in anonymous inner class, so change value became difficult as final type var is not modifiable unless you call function.
public class TimeBomber {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
//create Jframe
JFrame app = new JFrame("Time Bomber");
//create JPanel
final JPanel panel = new JPanel();
//JLabel with first Picture
JLabel pic = new JLabel(new ImageIcon("images.png"));
pic.setSize(100, 100);
//Label for displaying time digit
final JLabel label = new JLabel("");
label.setLocation(200, 250);
//create another thread
Thread time = new Thread(){
public void run(){
for(int i=10; i>0; i--){
if(i==1){
JLabel picSecond = new JLabel(new ImageIcon("Bomber.jpg"));
//<--Fact is I dont want to create another JLabel, I want to modify the pic location content in JLabel pic.
picSecond.setSize(100, 100);
panel.add(picSecond);
}
label.setText("Time: "+i);
try {
sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
//add every component to where it belongs
panel.add(pic);
panel.add(label);
app.add(panel);
app.setSize(300, 400);
app.setVisible(true);
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
time.start();
}
}
Wrap the code in SwingUtilities.invokeAndWait() (or SwingUtilities.invokeLater())
if(i==1){
JLabel picSecond = new JLabel(new ImageIcon("Bomber.jpg"));//<--Fact is I dont want to create another JLabel, I want to modify the pic location content in JLabel pic.
picSecond.setSize(100, 100);
panel.add(picSecond);
}
label.setText("Time: "+i);
TO avoid recreation of the JLabel make it the class' field and add to panel just once. Then use picSecond.setIcon() to update the image.
BTW it's better to have kind of images cache to avoid image recreation on each step.
Okay I want my background image to change when helpButton is pressed. I can make the button image change when the mouse hovers over it with a Mouse Listener. I did the same steps except with the Action Listener but with no success. Any help would be great!
public class test extends JFrame{
private JLabel label;
private JButton button;
private ImageIcon bgi;
private JLabel bgl;
public static Rectangle gameSquare;
private JButton startButton;
private JButton helpButton;
private final Action action = new SwingAction();
public static void main(String[] args) throws MalformedURLException, IOException {
test gui = new test ();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // when click x close program
gui.setSize(902, 305);
gui.setVisible(true);
gui.setTitle("Solid Cloud Inc - Twitter Unfolower");
}
public test() throws MalformedURLException, IOException{
bgi = new ImageIcon(getClass().getResource("tu.png"));
getContentPane().setLayout(null);
BufferedImage img = ImageIO.read(new URL("http://i1344.photobucket.com/albums/p656/SolidCloudInc/start_zpsf3781681.png"));
//ImageIcon start = new ImageIcon(getClass().getResource("start.png"));
startButton = new JButton("");
startButton.setIcon(new ImageIcon(img));
startButton.setBounds(22, 186, 114, 50);
getContentPane().add(startButton);
BufferedImage img2 = ImageIO.read(new URL("http://i1344.photobucket.com/albums/p656/SolidCloudInc/help_zpsc4fad867.png"));
final JButton helpButton = new JButton("");
helpButton.setIcon(new ImageIcon(img2));
helpButton.setBounds(192, 186, 114, 50);
getContentPane().add(helpButton);
bgl = new JLabel (bgi);
bgl.setBounds(0, 0, 886, 272);
getContentPane().add(bgl);
Events e = new Events();
startButton.addActionListener(e);
helpButton.addActionListener(e);
}
public class Events implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == startButton) {
label.setText("Searching");
try {
Unfollow();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
else if (e.getSource() == helpButton){
System.out.println("gottem");
bgi = new ImageIcon(getClass().getResource("tu2.png"));
bgl = new JLabel (bgi);
}
}
}
bgl = new JLabel (bgi);
Here you're creating a new JLabel, and putting it into the bgl variable but are doing anything with it and make no change to the JLabel object that continues to be shown in the GUI. It's a common newbie trap to think that by changing the reference of a variable you change the state of the original object that the variable previously referred to. That's not how it works. In other words, the original JLabel that was held by the bgl variable still exists and still displays its original content in the GUI despite this code above. What you should do instead is to change the icon shown by the original JLabel, or in other words, change the state of the current JLabel object, not change references held by the bgl variable. i.e.,
bgl.setIcon(bgi);
Also, you'll want to get rid of any and all use of null layout and calls to setBounds(...) as this will lead to buggy hard to maintain and upgrade code. Let the layout managers do the heavy lifting with regards to laying out the GUI.
I'm looking to add interactivity to an image but cannot see a way off adding a mouselistener to it. I would like to get the X & Y of where whas clicked on the image.
The Flow if the image is:
tileset = new ImageIcon("xx.png"); //ImageIcon Image that wants to be clicked
label.setIcon(tileset); // assigned to a label
panel.add(label); //assigned to a panel
tileScrollPane = new JScrollPane(panel); // Assigned to a scrollable pane
frame.add(tileScrollPane, BorderLayout.CENTER); // then onto a JFrame
You should be able to add a MouseListener to the label:
label.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent event) {
// Handle click - coordinates in event.
}
});
In the overridden function for my JFrame:
#Override
protected void paintComponent(Graphics g) {
BufferedImage imagePerson;
try {
imagePerson = ImageIO.read(new File("errol.gif"));
} catch (IOException e) {
imagePerson = null;
}
g.drawImage(imagePerson, i * increment, j * increment - 1, null);
}
How can I change this so the animation on the gif is shown (without using threading). I have spent many hours trying to get this to work but to no avail.
You could use an ImageIcon for this purpose. Have a look here and here. If you need the animation on a JPanel, simply add a JLabel (with the ImageIcon) to the panel.
Check this example for displaying an animated gif in Swing. you dont have to use any threads:
Icon imgIcon = new ImageIcon(this.getClass().getResource("ajax-loader.gif"));
JLabel label = new JLabel(imgIcon);
label.setBounds(668, 43, 46, 14); // for example, you can use your own values
frame.getContentPane().add(label);
Source