Reputation: 3
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TowerDefence extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
ImageIcon EasyImage = new ImageIcon("WelcomeImage.png");
Image Image = EasyImage.getImage();
Image newimg = Image.getScaledInstance(1000, 700, java.awt.Image.SCALE_SMOOTH);
EasyImage = new ImageIcon(newimg);
EasyImage.paintIcon(this, g, 0, 0);
JButton button = new JButton("Click Button");
button.setBounds(100, 100, 100, 100);
super.add(button);
}
public static void main(String[] args) throws Exception {
TowerDefence T = new TowerDefence();
JFrame frame = new JFrame("Sam");
frame.setVisible(true);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setBounds(150, 20, 1000, 700);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(T);
}
}
Why is this printing out 2 JButtons? I literally don't know how this works and it would be nice to know. The idea is to literally print out a picture and a button and I can't even get that to work lol. The main issue is I don't know how to use the paint component as I am quite new to java.
Upvotes: 0
Views: 46
Reputation: 12347
ImageIcon easyImage;
public TowerDefense(){
EasyImage = new ImageIcon("WelcomeImage.png");
Image Image = EasyImage.getImage();
Image newimg = Image.getScaledInstance(1000, 700, java.awt.Image.SCALE_SMOOTH);
JButton button = new JButton("Click Button");
add(button);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
EasyImage.paintIcon(this, g, 0, 0);
}
I've re-arranged the code to try to separate the painting and the initialization. I strongly recommend checking out the link provided by Abra because you'll save quite a few headaches.
Upvotes: 1