I tried to change the picture in this code. I tried to call the public function, and able to load when I want to call them out. I wanted to know how to do this, so that way I can put them in the if statement, while loop, or case statement.
In this code, I called a public function:
test chill = new chill();
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
public class test extends Component {
BufferedImage img;
BufferedImage img1;
public void paint(Graphics g) {
g.drawImage(img, 0, 0, null);
g.drawImage(img1,0,0,null);
}
public test() {
try {
img = ImageIO.read(new File("smile.png"));
} catch (IOException e) {
}
}
public chill() {
try {
img1 = ImageIO.read(new File("chill.png"));
} catch (IOException e) {
}
}
//img1= ImageIO.read(new File("chill.png"));
public Dimension getPreferredSize() {
if (img == null) {
return new Dimension(100,100);
} else {
return new Dimension(img.getWidth(null), img.getHeight(null));
}
}
public static void main(String[] args) {
JFrame f = new JFrame("Load Image Sample");
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
test chill = new chill();
f.add(new test());
f.pack();
f.setVisible(true);
}
}
What did I do wrong in this? If you have a website that explains about it, please post it on here! Thanks a tons!
This program is something that I do for fun.
First, the class should start with a capital letter (by convention). Second
test chill = new chill();
should be
test chill = new test();
Because chill
is the variable name, and test
is the class. Also, that's a constructor (not a method). And, you can't have a chill
constructor in test
class.
// public chill() {
// try {
// img1 = ImageIO.read(new File("chill.png"));
// } catch (IOException e) {
// }
// }
You could have a chill
method
public void chill() {
try {
img1 = ImageIO.read(new File("chill.png"));
} catch (IOException e) {
}
}
And then
new test().chill();
would work.