juliovieira Posted August 21, 2013 at 12:28 AM Report #522223 Posted August 21, 2013 at 12:28 AM Boa noite, como se adiciona imagens a uma grid bidimensional JPanel? Tenho a seguinte grelha 9x9 JPanel grelha[][] = new JPanel[nLinhas][nColunas]; JPanel painel = new JPanel(); e a cada elemento da grelha queria adicionar uma imagem .png à mesma tendo ainda um GridLayout GridLayout gl = new GridLayout(nLinhas, nColunas, 0, 0); Já testei com os seguintes código mas todos sem sucesso: JLabel icon = new JLabel(new ImageIcon("lena.png")); grelha[i][j].add(icon); grelha[i][j] = new JLabel(new ImageIcon("lena.png")); grelha[i][j].setOpaque(true); painel.getContentPane().add(grelha[i][j]); JLabel icon = new JLabel(new ImageIcon("lena.png")); grelha[i][j].add(icon); panelGrid.add(grelha[i][j]); Alguma ajuda? Cumprimentos
Ernest Posted August 21, 2013 at 01:20 AM Report #522227 Posted August 21, 2013 at 01:20 AM (edited) Bom dia, import java.awt.GridLayout; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; /** * Esta classe pode exibir uma grade de imagens em um layout de grade. * * Para colocar Diferentes fotos basta colocar um filtro (IF) no FOR * e as imagens com números. exemplo Img1.png , img2.png etc .. * * @author Ernest Duarte * */ public class MainSwingGridImg extends JFrame { int nLinhas = 9, nColunas = 9; public MainSwingGridImg() { JPanel[][] grelha = new JPanel[nLinhas][nColunas]; JPanel painel = new JPanel(); GridLayout gl = new GridLayout(nLinhas, nColunas, 0, 0); painel.setLayout(gl); for(int i = 0 ; i< grelha.length ; i++) { for(int j = 0 ; j< grelha.length ; j++) { ImageIcon icon = createImageIcon("a"+2+".png", "image"); JLabel label = new JLabel("", icon, JLabel.CENTER); grelha[i][j] = new JPanel(); grelha[i][j].add(label); painel.add(grelha[i][j]); } } getContentPane().add(painel); setBounds(100, 100, 400, 400); setVisible(true); } protected ImageIcon createImageIcon(String path, String description) { java.net.URL imgURL = getClass().getResource(path); if (imgURL != null) { return new ImageIcon(imgURL, description); } else { System.err.println("Couldn't find file: " + path); return null; } } public static void createGuiSWING() { //Schedule a job for the event-dispatching thread: //creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { new MainSwingGridImg(); } }); } public static void main(String[] args) { MainSwingGridImg.createGuiSWING(); } } Edited August 21, 2013 at 11:55 AM by brunoais geshi
Knitter Posted August 21, 2013 at 08:34 AM Report #522230 Posted August 21, 2013 at 08:34 AM Se não quiseres adicionar uma JLabel extra a cada JPanel como na solução que o Ernest te deu, podes desenhar a imagem directamente como fundo do JPanel. Procura aqui no fórum sobre JPanel com background ou vai directo à wiki do P@P, isso já foi perguntado centenas de vezes e existe um tutorial na wiki que explica como ter um JPanel com background personalizado.
juliovieira Posted August 21, 2013 at 02:04 PM Author Report #522268 Posted August 21, 2013 at 02:04 PM Obrigado pela resposta Ernest, mas no entanto deparo-me ainda com um problema no método createImageIcon(), ao correr o código diz que não consegue encontrar o ficheiro, já tentei mudar inúmeras vezes de path, folder, até no C:/ no entanto sem sucesso
Ernest Posted August 21, 2013 at 03:47 PM Report #522279 Posted August 21, 2013 at 03:47 PM (edited) Bom dia, Obrigado brunoais pela informação como meter o código com cor vou tentar. juliovieira o programa funciona a maravilha é só meter as imagens no mesmo repertório que a classe JAVA. Por exemplo a minha imagem é : MoiOpenStack.jpeg Existem varias técnicas para carregar as imagens na memoria do programa mas o mais simples é você meter as imagens no mesmo directory que as classes java. Também pode criar um directory no repertorio onde esta as classes chamado images/ e meter as suas imagens dentro dele e claro especificar o path adequado. Aproveito para adicionar o painel num : JScrollPane sp = new JScrollPane(painel); import java.awt.GridLayout; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; /** * Esta classe pode exibir uma grade de imagens em um layout de grade. * * Para colocar Diferentes fotos basta colocar um filtro (IF) no FOR * e as imagens com números. exemplo Img1.png , img2.png etc .. * * @author Ernest Duarte * */ public class MainSwingGridImg extends JFrame { int nLinhas = 9, nColunas = 9; public MainSwingGridImg() { JPanel[][] grelha = new JPanel[nLinhas][nColunas]; JPanel painel = new JPanel(); GridLayout gl = new GridLayout(nLinhas, nColunas, 0, 0); painel.setLayout(gl); for(int i = 0 ; i< grelha.length ; i++) { for(int j = 0 ; j< grelha.length ; j++) { ImageIcon icon = createImageIcon("MoiOpenStack.jpeg", "image"); JLabel label = new JLabel("", icon, JLabel.CENTER); grelha[i][j] = new JPanel(); grelha[i][j].add(label); painel.add(grelha[i][j]); } } JScrollPane sp = new JScrollPane(painel); getContentPane().add(sp); setBounds(10, 10, 800, 800); setVisible(true); } protected ImageIcon createImageIcon(String path, String description) { java.net.URL imgURL = getClass().getResource(path); if (imgURL != null) { return new ImageIcon(imgURL, description); } else { System.err.println("Couldn't find file: " + path); return null; } } public static void createGuiSWING() { //Schedule a job for the event-dispatching thread: //creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { new MainSwingGridImg(); } }); } public static void main(String[] args) { MainSwingGridImg.createGuiSWING(); } } Cordialmente Ernest Duarte Edited August 21, 2013 at 04:44 PM by Ernest Duarte
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now