0
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.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 1
    Egad! You're adding the button in your paintComponent method, don't do that. Just paint. – matt Oct 22 '21 at 07:59
  • 1
    [Creating a GUI With Swing](https://docs.oracle.com/javase/tutorial/uiswing/) – Abra Oct 22 '21 at 08:06
  • 1
    Do you want your `JPanel` to have a [background image](https://stackoverflow.com/questions/19125707/simplest-way-to-set-image-as-jpanel-background) ? Or do you want your `JButton` to have an [icon](https://stackoverflow.com/questions/4801386/how-do-i-add-an-image-to-a-jbutton) ? – Abra Oct 22 '21 at 08:07

1 Answers1

1
  • First don't use setBounds unless you have a null type layout.
  • Second don't use a null layout unless you want to handle everything about the layout.
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.

matt
  • 10,892
  • 3
  • 22
  • 34