0

I've made a Jpanel with a background image and a Jbutton also with its background. The problem is that background sometimes is loaded sometimes no.

public class Window extends JFrame {

    public static JFrame createwindow() {//fare singleton
        JFrame frame = new JFrame("Battaglia navale");

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(740, 740);
        frame.setVisible(true);
        frame.setResizable( false );

        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();

        frame.setLocation(((int)dim.getWidth()-(int)frame.getWidth())/2, ((int)dim.getHeight()-(int)frame.getHeight())/2);

        return frame;
    }
}

public class StartWindow {

    JFrame frame;
    private JButton button;
    private JButton button2;
    final String button_start = "img/start.png";
    ImageIcon start = new ImageIcon(button_start);

    public void CreateStartWindow() {
        frame = Window.createwindow();
        Container container = frame.getContentPane();
        JpanelStart panel = new JpanelStart();
        container.add(panel);

        this.button = new JButton(start);
        button.setActionCommand("start");
        button.setHideActionText(true);
        button.setOpaque(false);
        button.setFocusPainted(false);
        button.setBorderPainted(false);
        button.setContentAreaFilled(false);

        this.button2 = new JButton("Classifica");

        panel.add(button);
        panel.add(button2);
        frame.setVisible(true);
    }

    public void addActionListener(ActionListener al) {
        this.button.addActionListener(al);
        this.button2.addActionListener(al);
    }

    public void chiudi() {
        frame.dispose();
    }
}

class JpanelStart extends JPanel {

    private Image img;
    private String path_img = "img/sfondo.jpg";

    public JpanelStart() {
        img = Toolkit.getDefaultToolkit().createImage(path_img);
        loadImage(img);
    }

    private void loadImage(Image img) {
        try {
            MediaTracker track = new MediaTracker(this);
            track.addImage(img, 0);
            track.waitForID(0);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        setOpaque(false);
        g.drawImage(img, 0, 0, this);
        super.paintComponent(g);

    }
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Stefano Maglione
  • 3,946
  • 11
  • 49
  • 96

2 Answers2

2
  • draw the image after super.paintComponent(g) (which draws the component that you want to draw on top of)
  • call repaint() in loadImage() after the image is set (so that it redraws it)
  • loadImage() doesn't seem to be setting the img variable does it need to?
  • (not essential but recommended) you should also move UI changes into the EDT (Event Dispatch Thread).

Example of running a UI task on EDT

This puts UI operations on a queue so that all UI changes are made from the same thread and avoid interference.

java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
        //UI Operations
    }
} );
Community
  • 1
  • 1
Ross Drew
  • 8,163
  • 2
  • 41
  • 53
  • I've added an example and another point to my list regarding `img` never being set after creation of `JpanelStart` – Ross Drew Jan 29 '14 at 14:28
2
  1. super.paintComponet should go right after the method signature.
  2. you set the button opacity to false, so it won't be seen.
  3. Run your program from the Event Dispatch Thread.

    public static void main(String[] args){
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                new StartWindow().CreateStartWindow();  
            }
        });
    }
    
  4. In your method, you're making the frame visible before adding anything. Leave that out in the method

  5. Don't set the size of the frame. Instead override the getPrefereedSize() of the JPanel and call pack() on the frame.
  6. IMO, I see no use at all for this so-called helper method. I would toss it out the window
  7. You should load your image as an embedded resource, and not from the file system.

    img = ImageIO.read(StartWindow.class.getResource(path_img));
    

import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class StartWindow {

    JFrame frame;
    private JButton button;
    private JButton button2;
    final String button_start = "img/start.png";
    ImageIcon start = new ImageIcon(button_start);

    public void CreateStartWindow() throws IOException  {
        frame = Window.createwindow();
        Container container = frame.getContentPane();
        JpanelStart panel = new JpanelStart();
        container.add(panel);

        this.button = new JButton(start);
        button.setActionCommand("start");
        button.setHideActionText(true);
        button.setOpaque(false);
        button.setFocusPainted(false);
        button.setBorderPainted(false);
        button.setContentAreaFilled(false);

        this.button2 = new JButton("Classifica");

        panel.add(button);
        panel.add(button2);

        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);


    }

    public static void main(String[] args){
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                try {
                    new StartWindow().CreateStartWindow();
                } catch (IOException ex) {
                    Logger.getLogger(StartWindow.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });

    }

    public void addActionListener(ActionListener al) {
        this.button.addActionListener(al);
        this.button2.addActionListener(al);
    }

    public void chiudi() {
        frame.dispose();
    }
}

class Window {

    public static JFrame createwindow() {//fare singleton

        JFrame frame = new JFrame("Battaglia navale");

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.setResizable(false);
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();

        return frame;

    }

}



class JpanelStart extends JPanel {
    private static final int D_W = 700;
    private static final int D_H = 700;

    private Image img;
    private String path_img = "/images/logo.gif";

    public JpanelStart() throws IOException {

        img = ImageIO.read(StartWindow.class.getResource(path_img));
        loadImage(img);

    }

    private void loadImage(Image img) {
        try {
            MediaTracker track = new MediaTracker(this);
            track.addImage(img, 0);
            track.waitForID(0);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        g.drawImage(img, 0, 0, D_W, D_W, this);
    }

    @Override 
    public Dimension getPreferredSize() {
        return new Dimension(D_W, D_H);
    }
}

**Shows Up Every time **

enter image description here

Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720