Ho adottato il tuo esempio:
codice:
package mensa;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.imageio.*;
import javax.swing.*;
public class TiledBackground {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new TiledBackgroundFrame().setVisible(true);
}
});
}
}
class TiledBackgroundFrame extends JFrame {
private TiledBackgroundPanel tiledBackPanel;
public TiledBackgroundFrame() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(400, 350);
tiledBackPanel = new TiledBackgroundPanel();
tiledBackPanel.setBackground(Color.ORANGE);
// The TiledBackgroundPanel is set as the "content pane"
// of the JFrame.
setContentPane(tiledBackPanel);
Container contentPane = getContentPane();
// The content pane is a TiledBackgroundPanel!!! (but not important here!)
contentPane.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));
}
private void loadImage(String resourceName) {
try {
URL url = getClass().getResource(resourceName);
if (url != null) {
Image img = ImageIO.read(url);
if (img != null) {
tiledBackPanel.setBackgroundImage(img);
} else {
JOptionPane.showMessageDialog(this, "impossibile caricare la risorsa");
}
} else {
JOptionPane.showMessageDialog(this, "risorsa non trovata");
}
} catch (IOException e) {
JOptionPane.showMessageDialog(this, "I/O Error reading resource " + resourceName);
}
}
private class LoadButtonListener implements ActionListener {
private String resourceName;
public LoadButtonListener(String resourceName) {
this.resourceName = resourceName;
}
public void actionPerformed(ActionEvent e) {
loadImage(resourceName);
}
}
}
class TiledBackgroundPanel extends JPanel {
private Image backImg;
public TiledBackgroundPanel() {
this(null);
}
public TiledBackgroundPanel(Image backImg) {
super(new BorderLayout());
this.backImg = backImg;
}
public void setBackgroundImage(Image backImg) {
this.backImg = backImg;
repaint();
}
protected void paintComponent(Graphics g) {
if (backImg == null) {
super.paintComponent(g);
} else {
int panelWidth = getWidth();
int panelHeight = getHeight();
int imageWidth = backImg.getWidth(null);
int imageHeight = backImg.getHeight(null);
// Repeats the draw of the image many times as necessary
// to fill the entire surface of the panel.
for (int y = 0; y < panelHeight; y += imageHeight) {
for (int x = 0; x < panelWidth; x += imageWidth) {
g.drawImage(backImg, x, y, null);
}
}
}
}
}
va bene o c'è qualche altra cosa che devo togliere???
Ancora non capisco come adattare questo codice al JPanel che voglio creare e come richiamare l'immagine.
Devo creare una cartella con le immagini nella stessa cartella del progetto?
Per esempio il mio package è "mensa", nella url da caricare metto come percorso: "mensa.foto" ?