JList e JLabel [RESOLVIDO]

bom dia!
Sou iniciante em java e a cada hora descubro novas melhoras para meu codigo.

Agora encontrei um problema que nao consigo sanar:

Como pegar a descriçao de um Item do JList (contem endereço de uma imagem essa descricao) e fazer a imagem aparecer no JLabel.?
Fiz o codigo dentro de um MouseClicked, mas não fui feliz.

Segue abaixo o codigo:

private void jList1MouseClicked(java.awt.event.MouseEvent evt) {
      
        
            if(evt.getClickCount() == 1) {  
        String path= (jList1.getSelectedValue().toString());
       // System.out.println("aquiii= " + path);
        
ImageIcon img = new ImageIcon(path);
JLabel jLabel3 = new JLabel(img);
jLabel3.setVisible(true);
         
            }
    }

Obrigada pela ajuda!

Ola, veja bem voce tem que usar os GET E SET do encapsulamento, ou seja, se o valor de uma variavel for do tipo texto.

label.setText() = list.getText();

obs: “label” e “list” é a sua variavel.

espero ter ajudado!

Usualmente métodos de tratamento de mouse não funcionam bem com os componentes do Swing.
Evite-os porque normalmente não dão o resultado esperado.
No seu caso, por exemplo, o método correto a ser usado é um List Selection Listener, método valueChanged. Um exemplo:

package guj;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.KeyEvent;

import javax.swing.Action;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class ExemploJList2 extends JFrame {

    private static final long serialVersionUID = 1L;

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                ExemploJList2 thisClass = new ExemploJList2();
                thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                thisClass.setVisible(true);
            }
        });
    }

    private JButton btnOK = null;
    private JPanel jContentPane = null;
    private DefaultListModel listModel;
    private JList lstList = null;

    private JPanel pnlBotoes = null;

    private JScrollPane scpList = null;
    private JLabel lblTextoSelecionado;

    public ExemploJList2() {
        super();
        initialize();
    }

    private JButton getBtnOK() {
        if (btnOK == null) {
            btnOK = new JButton();
            btnOK.setText("OK");
        }
        return btnOK;
    }

    private JPanel getJContentPane() {
        if (jContentPane == null) {
            jContentPane = new JPanel();
            jContentPane.setLayout(new BorderLayout());
            jContentPane.add(getScpList(), BorderLayout.CENTER);
            jContentPane.add(getPnlBotoes(), BorderLayout.SOUTH);
            jContentPane.add(getLblTextoSelecionado(), BorderLayout.NORTH);
        }
        return jContentPane;
    }

    private DefaultListModel getListModel() {
        if (listModel == null) {
            listModel = new DefaultListModel();
            for (int i = 0; i < 100; ++i) {
                listModel.addElement(String.format("Elemento %02d", i));
            }
        }
        return listModel;
    }

    private JList getLstList() {
        if (lstList == null) {
            lstList = new JList();
            // É em um ListSelectionListener (não em um MouseListener)
            // que você pega eventos de escolha de itens do JList
            lstList.addListSelectionListener(new ListSelectionListener() {
                public void valueChanged(ListSelectionEvent e) {
                    // Note que "e.getValueIsAdjusting" e "lstList.getSelectedValue() != null" abaixo
                    // não são enfeite: se você não tratar essa condição, você vai tomar um NullPointerException
                    if (!e.getValueIsAdjusting() && lstList.getSelectedValue() != null) {
                        String text = lstList.getSelectedValue().toString();
                        getLblTextoSelecionado().setText("Elemento selecionado: " + text);
                    }
                }
            });
            lstList.setModel(getListModel());
            lstList.setFocusCycleRoot(true);
            lstList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            lstList.setSelectedIndex(0);

            // Como exemplo, fiz com que as teclas q e w funcionem como Up e
            // Down, respectivamente.
            lstList.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_Q, 0), "up");
            lstList.getActionMap().put("up", (Action) lstList.getActionForKeyStroke(KeyStroke.getKeyStroke(KeyEvent.VK_KP_UP, 0)));
            lstList.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0), "down");
            lstList.getActionMap().put("down",
                (Action) lstList.getActionForKeyStroke(KeyStroke.getKeyStroke(KeyEvent.VK_KP_DOWN, 0)));
        }
        return lstList;
    }

    private JPanel getPnlBotoes() {
        if (pnlBotoes == null) {
            pnlBotoes = new JPanel();
            pnlBotoes.setLayout(new FlowLayout());
            pnlBotoes.add(getBtnOK(), null);
        }
        return pnlBotoes;
    }

    private JScrollPane getScpList() {
        if (scpList == null) {
            scpList = new JScrollPane();
            scpList.setViewportView(getLstList());
        }
        return scpList;
    }

    private void initialize() {
        this.setSize(320, 234);
        this.setContentPane(getJContentPane());
        this.setTitle("Exemplo de JList");
    }

    private JLabel getLblTextoSelecionado() {
        if (lblTextoSelecionado == null) {
            lblTextoSelecionado = new JLabel("Clique em um item do JLabel");
        }
        return lblTextoSelecionado;
    }
}

Boa tarde e obrigada pelas dicas pessoal.

Seguinte tentei usar a dica anterior, mas nao apareceu a imagem no JLabel mesmo assim. Alguém pode me informar o que eu fiz de errado?

Segue o codigo:

    private void imagMostrar(){
         jList1.addListSelectionListener(new ListSelectionListener() {  
                public void valueChanged(ListSelectionEvent e) {  
                       if (!e.getValueIsAdjusting() && jList1.getSelectedValue() != null) {  
                       String path= (jList1.getSelectedValue().toString());
                       // jLabel3.setText(jList1.getSelectedValue().toString());
                       System.out.println("aquiii= " + path);
        
                     //String aux = file.getPath();
                     ImageIcon img = new ImageIcon(path);
                     JLabel jLabel3 = new JLabel(img);
                     //jLabel3.setText(path);
                      jLabel3.setVisible(true);
}
}
});
}

OBRIGADA meus AMIGOS!

                     JLabel jLabel3 = new JLabel(img);  
                     //jLabel3.setText(path);  
                      jLabel3.setVisible(true);  

Vossa Excelência criou um JLabel e o associou a algum container? Senão ele não será visualizado. Não adianta dar um setVisible (true) nesse caso - isso se chama “magia”, ou seja, fazer algo sem saber para que serve.

Além disso, o lugar onde você adicionou o “listener” aparentemente está errado, já que o nome do método que você usou é “imagMostrar”.

Brigada pela dica, mas a excelência aqui criou sim o Label direitinho (acho…) tô usando NetBeans e apenas arrastei e comecei a usar o JLabel.

Não entendi porque estaria errado meu método de Mostrar Imagem no Label =s

Tô quase la…
Obrigada pela ajuda,
veronica!

Faltou posicionar seu label para aparecer algum lugar da tela, talvez também precise setar o tamanho do label para que ele apareça…

Hum… maldito NetBeans :slight_smile:

De qualquer maneira, voce ja deve ter um JLabel criado e posicionado no local adequado, nao?

Para mudar a imagem dele, voce tem de fazer algo parecido com:

jlabel.setIcon (img);

onde jlabel é o jlabel que o NetBeans criou e você posicionou na tela.

Se você ficar instanciando um novo JLabel, como você fez, ele não vai ficar associado a nenhum local na tela, portanto ele ficará invisível :frowning:

Eu realmente não gosto de usar o NetBeans para desenhar telas.

Um dos principais motivos é que fica o tal do “código preso” que ele gera, e que não é fácil de customizar (é possível fazer isso, mas é preciso conhecer bem o que o NetBeans faz, além de conhecer o Swing).

O outro é que o layout padrão (javax.swing.GroupLayout) é terrível para desenhar telas que precisem de ser bem organizadas. Talvez seja bom para uma prova de conceito :frowning:

Prefiro usar o WindowBuilder do Eclipse (que aliás foi o que usei para montar o exemplo que postei) e o layout MigLayout (não o uso muito para dar exemplos aqui no GUJ porque aí você tem o problema de rodar seu programa, já que é um JAR separado que não vem com o JDK e como eu sei muito bem, o pessoal aqui no GUJ tem muitos problemas de rodar um programa que exija um JAR separado :frowning:

[quote=entanglement]Eu realmente não gosto de usar o NetBeans para desenhar telas.

Um dos principais motivos é que fica o tal do “código preso” que ele gera, e que não é fácil de customizar (é possível fazer isso, mas é preciso conhecer bem o que o NetBeans faz, além de conhecer o Swing).

O outro é que o layout padrão (javax.swing.GroupLayout) é terrível para desenhar telas que precisem de ser bem organizadas. Talvez seja bom para uma prova de conceito :frowning:

Prefiro usar o WindowBuilder do Eclipse (que aliás foi o que usei para montar o exemplo que postei) e o layout MigLayout (não o uso muito para dar exemplos aqui no GUJ porque aí você tem o problema de rodar seu programa, já que é um JAR separado que não vem com o JDK e como eu sei muito bem, o pessoal aqui no GUJ tem muitos problemas de rodar um programa que exija um JAR separado :frowning:
[/quote]

Já passei muita raiva também, mas foi com elas que aprendi e percebi que provavelmente o erro da colega é esse

Bom dia amigos…

Ainda nao consegui um bom resultado.
É tao complicado pegar um Item do JList (que é o endereço de uma imagem) e apresentar a imagem no JLabel?
Alguém me sugere outra coisa mais facil???

OBRIGADA,
veronica!

CONSEGUI GALERA!!! =D

No NetBeans adicionei o evento jList1ValueChanged e dentro dele coloquei meu método para aparecer a imagem de figura no Label.
Retirei a linha para construir um novo objeto: JLabel jLabel3 = new JLabel(img); e funcionou!
Alguém me explica porque quando tirei ela o método funcionou.

Segue o codigo abaixo:

    private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {
        jList1.addListSelectionListener(new ListSelectionListener() {  
                public void valueChanged(ListSelectionEvent e) {  
                    if (!e.getValueIsAdjusting() && jList1.getSelectedValue() != null) {                      
        String path= (jList1.getSelectedValue().toString());
        System.out.println("aquiii= " + path);
ImageIcon img = new ImageIcon(path);
jLabel3.setIcon (img);
jLabel3.setVisible(true);
}
}
});
    }

OBRIGADA A TODOS PELA GRANDE AJUDA,
veronica

Voce estava criando um novo objeto, sendo que não era isso sua real intenção.
criando um novo objeto voce nao herdou a “imagem” do objeto já criado , voce criava um objeto vazio e voce mandava mostrar no label um label VAZIO.

[quote=entanglement]Usualmente métodos de tratamento de mouse não funcionam bem com os componentes do Swing.
Evite-os porque normalmente não dão o resultado esperado.
No seu caso, por exemplo, o método correto a ser usado é um List Selection Listener, método valueChanged. Um exemplo:

[code]
package guj;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.KeyEvent;

import javax.swing.Action;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class ExemploJList2 extends JFrame {

private static final long serialVersionUID = 1L;

public static void main(String[] args) {
    // TODO Auto-generated method stub
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            ExemploJList2 thisClass = new ExemploJList2();
            thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            thisClass.setVisible(true);
        }
    });
}

private JButton btnOK = null;
private JPanel jContentPane = null;
private DefaultListModel listModel;
private JList lstList = null;

private JPanel pnlBotoes = null;

private JScrollPane scpList = null;
private JLabel lblTextoSelecionado;

public ExemploJList2() {
    super();
    initialize();
}

private JButton getBtnOK() {
    if (btnOK == null) {
        btnOK = new JButton();
        btnOK.setText("OK");
    }
    return btnOK;
}

private JPanel getJContentPane() {
    if (jContentPane == null) {
        jContentPane = new JPanel();
        jContentPane.setLayout(new BorderLayout());
        jContentPane.add(getScpList(), BorderLayout.CENTER);
        jContentPane.add(getPnlBotoes(), BorderLayout.SOUTH);
        jContentPane.add(getLblTextoSelecionado(), BorderLayout.NORTH);
    }
    return jContentPane;
}

private DefaultListModel getListModel() {
    if (listModel == null) {
        listModel = new DefaultListModel();
        for (int i = 0; i < 100; ++i) {
            listModel.addElement(String.format("Elemento %02d", i));
        }
    }
    return listModel;
}

private JList getLstList() {
    if (lstList == null) {
        lstList = new JList();
        // É em um ListSelectionListener (não em um MouseListener)
        // que você pega eventos de escolha de itens do JList
        lstList.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                // Note que "e.getValueIsAdjusting" e "lstList.getSelectedValue() != null" abaixo
                // não são enfeite: se você não tratar essa condição, você vai tomar um NullPointerException
                if (!e.getValueIsAdjusting() && lstList.getSelectedValue() != null) {
                    String text = lstList.getSelectedValue().toString();
                    getLblTextoSelecionado().setText("Elemento selecionado: " + text);
                }
            }
        });
        lstList.setModel(getListModel());
        lstList.setFocusCycleRoot(true);
        lstList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        lstList.setSelectedIndex(0);

        // Como exemplo, fiz com que as teclas q e w funcionem como Up e
        // Down, respectivamente.
        lstList.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_Q, 0), "up");
        lstList.getActionMap().put("up", (Action) lstList.getActionForKeyStroke(KeyStroke.getKeyStroke(KeyEvent.VK_KP_UP, 0)));
        lstList.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0), "down");
        lstList.getActionMap().put("down",
            (Action) lstList.getActionForKeyStroke(KeyStroke.getKeyStroke(KeyEvent.VK_KP_DOWN, 0)));
    }
    return lstList;
}

private JPanel getPnlBotoes() {
    if (pnlBotoes == null) {
        pnlBotoes = new JPanel();
        pnlBotoes.setLayout(new FlowLayout());
        pnlBotoes.add(getBtnOK(), null);
    }
    return pnlBotoes;
}

private JScrollPane getScpList() {
    if (scpList == null) {
        scpList = new JScrollPane();
        scpList.setViewportView(getLstList());
    }
    return scpList;
}

private void initialize() {
    this.setSize(320, 234);
    this.setContentPane(getJContentPane());
    this.setTitle("Exemplo de JList");
}

private JLabel getLblTextoSelecionado() {
    if (lblTextoSelecionado == null) {
        lblTextoSelecionado = new JLabel("Clique em um item do JLabel");
    }
    return lblTextoSelecionado;
}

}
[/code][/quote]

Boa Man, salvou minha vida! kkk Thanks!