/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package picturechanger;
import java.awt.Dimension;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.util.Random;
/**
*
* @author
*/
public class PictureChangerGui extends JFrame{
private JPanel mainPanel;
private JButton mainButton;
private JLabel mainLabel;
public PictureChangerGui() {
// Define the characteristics of the window
this.setSize(200, 200);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setTitle("Picture Changer");
// Create the components
mainPanel = new JPanel(new GridLayout(2,1));
mainButton = new JButton("Change Pictures");
mainLabel = new JLabel();
// Add listeners
ButtonListener bl = new ButtonListener();
mainButton.addActionListener(bl);
// Add the components
mainPanel.add(mainButton);
mainPanel.add(mainLabel);
this.getContentPane().add(mainPanel);
}
private class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
ImageIcon icon1 = createImageIcon("face1.png", "");
ImageIcon icon2 = createImageIcon("face2.png", "");
ImageIcon icon3 = createImageIcon("face3.png", "");
Random generator = new Random();
for (int idx = 0; idx <= 1; ++idx){
int randomInt = generator.nextInt(4);
if (randomInt <= 1) {
mainLabel.setIcon(icon1);
}
else if (randomInt <= 2 && randomInt > 1) {
mainLabel.setIcon(icon2);
}
else {
mainLabel.setIcon(icon3);
}
}
}
}
/** Returns an ImageIcon, or null if the path was invalid. */
protected ImageIcon createImageIcon(String path,
String description) {
java.net.URL imgURL = getClass().getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL, description);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
}
This is suppossed to let the user click on a button and then, whenever they click it the image in the label is updated randomly with one of three images stored in files "face1.png" ... "face3.png".
This is code that started out as partial code by a lecturer which we had to complete in a Lab which is why it may seem slightly unreadable, he doesn't comment much.
The problem I have is, when I run the program (I have a main class that constructs a new GUI and runs it) the window appears but none of the components appear. Can anyone see something wrong with the code?
I'm working on a Mac with netbeans by the way, in case there are any known problems with that...


Sign In
Create Account


Back to top









