Visualizzazione dei risultati da 1 a 5 su 5
  1. #1
    Utente di HTML.it
    Registrato dal
    Jun 2008
    Messaggi
    396

    override JPanel, definisci percorso immagine

    Ciao, ho effettuato l'override del mio JPanel nel seguente modo:
    codice:
    import java.awt.Graphics;
    import java.awt.Image;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    
    /**
     *
     * @author Daniele
     */
    public class backgroundedPanel extends javax.swing.JPanel
    {
        protected Image img;
    
        public backgroundedPanel(String localURL)
        {super();
            try
            {this.img = ImageIO.read(getClass().getResource(localURL));}
            catch (IOException ex)
            {System.out.print("Impossibile leggere l'immagine per creare il pane \n");}
        }
    
        @Override
    
        public void paintComponent(Graphics g)
        {
            g.drawImage(img, 0, 0,img.getWidth(null), img.getHeight(null),null);
        }
    
        public void setBounds(int x, int y)
        {
            super.setBounds(x,y,img.getWidth(this),img.getHeight(this));
        }
    }
    Adesso se io volessi utilizzare tale metodo in un'altra classe dello stesso package cosa devo fare?
    Per inserire un'immagine devo inserire l'indirizzo locale dell'immagina da caricare, ma tale immagine può essere in qualsiasi posto del mio computer? mi potete fare un esempio?

    Mettiamo che voglio utilizzare questo motodo in una classe JFrame disegnata con netBeans in automatico con il metodo grafico, come faccio a far disegnare il mio JPanel con lo sfondo definito da me?

    Ecco un sempio di JPanel disegnato con netBeans dove imposto con il mouse le finestre e poi il codice viene generato in automatico:
    codice:
    public class mensa extends javax.swing.JFrame {
    
        /** Creates new form mensa */
        public mensa() {
            initComponents();
        }
    
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
         */
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
    
            jPanel1 = new javax.swing.JPanel();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    
            jPanel1.setBackground(new java.awt.Color(255, 0, 0));
            jPanel1.setNextFocusableComponent(jPanel1);
    
            org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(0, 100, Short.MAX_VALUE)
            );
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(0, 100, Short.MAX_VALUE)
            );
    
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(280, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(180, Short.MAX_VALUE))
            );
    
            pack();
        }// </editor-fold>
    
        /**
        * @param args the command line arguments
        */
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new mensa().setVisible(true);
                }
            });
        }
    
        // Variables declaration - do not modify
        private javax.swing.JPanel jPanel1;
        // End of variables declaration
    
    }

  2. #2
    Utente di HTML.it L'avatar di andbin
    Registrato dal
    Jan 2006
    residenza
    Italy
    Messaggi
    18,284

    Re: override JPanel, definisci percorso immagine

    Originariamente inviato da Salinas
    Ciao, ho effettuato l'override del mio JPanel nel seguente modo:
    1) IOException sarebbe meglio e preferibile farlo "uscire" dal costruttore. Così come hai fatto, se lancia un IOException tu stampi il messaggio ma nessun altro codice se ne accorge, 'img' rimane a null e visto che su img invochi poi dei metodi .... ottieni un'altra eccezione in un secondo momento.

    2) paintComponent tienilo 'protected' ... non 'public'. Fa parte di un "contratto" privato tra JComponent e la tal sottoclasse, quindi non deve essere invocabile dall'esterno.

    3) Se volevi disegnare sempre comunque tutta la immagine, basterebbe il
    drawImage(Image img, int x, int y, ImageObserver observer)
    e non necessariamente quello che ha anche width/height.

    4) L'override di setBounds è molto discutibile. E qui centra dove poi dovrai mettere questo pannello relativamente anche all'uso o no di un layout manager.
    La cosa minima/sensata sarebbe impostare il "preferred size" del pannello ma poi bisogna vedere se lo metti in un layout manager che rispetta il preferred size o no.
    Su questa questione ci sarebbe molto di più da dire .....

    Originariamente inviato da Salinas
    ma tale immagine può essere in qualsiasi posto del mio computer?
    Come l'hai caricata no. Hai usato getResource(), quindi la immagine viene trattata come "risorsa" e trovata con lo stesso criterio che viene usato dalla JVM per trovare le classi .... ovvero il "classpath".
    E quello che passi a getResource() non è un URL .... ma una specifica particolare della risorsa (vedi documentazione).
    Andrea, andbin.devSenior Java developerSCJP 5 (91%) • SCWCD 5 (94%)
    java.util.function Interfaces Cheat SheetJava Versions Cheat Sheet

  3. #3
    Utente di HTML.it
    Registrato dal
    Jun 2008
    Messaggi
    396
    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" ?

  4. #4
    Utente di HTML.it
    Registrato dal
    Jun 2008
    Messaggi
    396
    Forse così è meglio

    codice:
    package mensa;
    
    import java.awt.*;
    import java.io.*;
    import java.net.*;
    import javax.imageio.*;
    import javax.swing.*;
    
    
    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);
                    }
                }
            }
        }
        
        private void loadImage(String resourceName) {
            try {
                URL url = getClass().getResource(resourceName);
    
                if (url != null) {
                    Image img = ImageIO.read(url);
    
                    if (img != null) {
                        
                        this.setBackgroundImage(img); // qui ho inserito this al posto del backPanel
                        
                    } 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);
            }
        }
    }
    va bene???

  5. #5
    Utente di HTML.it
    Registrato dal
    Jun 2008
    Messaggi
    396

    nessuna risposta?
    Avete un esempio da poter vedere dove si carica un immagine nel JPanel e magari viene anche richiamata tale funzione ?

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.