0

This is my first question here, I'll try to make it clear, if I don't succeed, please be patient :)

Ok, I'm developing a karaoke application with javax swing and mySQL for data (assignment) and I have a TabbedPane with one tab for the song list and a play button, when I hit play it sends us to the next tab, picks up all details necessary for song, amongst them the cover image of the record which the song belongs to, and then activates the second tab.

On the second tab I load a small JPanel for the image and put it in the main one above the JTextField where I'll be showing the lyrics

The problem comes when I go back to the song list, select a different song and hit play, everything works fine, except for the image, it always reloads the previous one, plus I set a println in the paint method of the panel containing the image and it seems to call the method as many times as I have gone back during the application being on.

I have thousands of lines of code, so I'll try to leave the most relevant (or what I think could be it)

Declaration of the main components of the GUI:

JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
        tabbedPane.setBounds(0, 0, 650, 740);
        getContentPane().add(tabbedPane);

        JPanel seleccion = new JPanel();
        seleccion.setBounds(0, 0, 650, 740);
        tabbedPane.addTab("Selecciona canción", null, seleccion, null);
        seleccion.setLayout(null);


        JPanel reproduccion = new JPanel();
        tabbedPane.addTab("Reproducción", null, reproduccion, null);
        reproduccion.setBounds(0, 0, 650, 740);
        reproduccion.setLayout(null);
        reproduccion.setBackground(Color.black);
        tabbedPane.setEnabledAt(1, false);

        JMenuBar menuBar = new JMenuBar();
        menuBar.setBounds(400, 5, 250, 45);
        seleccion.add(menuBar);

        JMenu menuFavoritos = new JMenu("Favoritas");
        menuBar.add(menuFavoritos);

Code for the play button:

 JButton btnPlayIcono = new JButton("");
        btnPlayIcono.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (interrupcion==true){
                    interrupcion=false;
                }
                int selected=list.getSelectedIndex();
//I get the song and collect it's details from the database
                seleccionada = listCanciones.get(selected);
                String path = seleccionada.getPath();
                letras = seleccionada.getLetras();
                tiempos=castTiempos(seleccionada);
                repr=new Reproduccion(Registro.usuarioActivo.getId(), seleccionada.getId());
                ReproduccionDAO.controlTabla(repr);

                ruta_imagen=seleccionada.getImagen();


            System.out.println("Ruta imagen: "+ruta_imagen);

This is where I initialize the panel for the image and provide it with the path (still inside the play button)

            fondo = new panel(ruta_imagen);//"/imagenes/port_la_polla.jpeg");
            System.out.println("Ruta imagen: "+ruta_imagen);
            fondo.setBounds(32, 62, 582, 220);
            reproduccion.add(fondo);
            tabbedPane.setEnabledAt(1, true);
            tabbedPane.setSelectedIndex(1);

            //reproduccion.repaint();
            try {//here I just call methods for playing song and printing lyrics
                  mi_reproductor.AbrirFichero(path);
                  mi_reproductor.Play();
                  imp=new ImprimeLetras(letras, tiempos, null);
                  imp.start();

            } 
            catch (Exception ex) {
                   System.out.println("Error: " + ex.getMessage());
            }
        }
    });
    btnPlayIcono.setIcon(new ImageIcon(SeleccionaCancion.class.getResource("/imagenes/windows-media-player-play-button-updated_f.png")));
    btnPlayIcono.setBounds(371, 289, 139, 128);
    seleccion.add(btnPlayIcono);

This is the class for the image panel which lays in the tab:

public class panel extends JPanel{

        ImageIcon imagen;
        String nombre;

        public panel(String nombre){
            this.nombre=nombre;
        }

        public void paint(Graphics g){
            Dimension tamanyo=getSize();
            //this is the print that shows itself as many times as I have reloaded the panel
            System.out.println("Path en metodo"+nombre);
            imagen = new ImageIcon(getClass().getResource(nombre));
            g.drawImage(imagen.getImage(), 0, 0, tamanyo.width, tamanyo.height, null);
            setOpaque(false);
            super.paint(g);

        }

    }

This is the code of the button that goes back to the list song tab (where the play button is)

JButton btnAtras1 = new JButton("Atras");
        btnAtras1.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                if(imp.isAlive()){
                    interrupcion=true;
                }
                //here I clear variable for the path to the image
                ruta_imagen="";
                //here I select the previous tab
                tabbedPane.setSelectedIndex(0);
                //I've left this here, but I also tried with remove all and repaint, no success
                reproduccion.revalidate();
            }
        });
        toolBar1.add(btnAtras1);

As it happens, it's turned out to be quite a long post, I hope I've explained myself properly though.

Cheers for now!

Editing to add runnable example:

(I have provided names for images, I'm not to sure how this works, but I guess anyone trying my code will just create a folder and put any images in there matching names? If not, please let me know)

import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Toolkit;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.awt.event.ActionEvent;
import javax.swing.JToolBar;
import javax.swing.JMenuBar;
import javax.swing.JPopupMenu;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JMenu;
import javax.swing.JList;
import javax.swing.event.ListSelectionListener;

import javax.swing.event.ListSelectionEvent;
import javax.swing.ImageIcon;

public class SeleccionaCancion extends JFrame {

    private JTextField txtAhoraQueremosSaber;
    private JTextField txtMusicalesPinchaSobre;
    private static JTextArea txtArRepro;
    public String visa;
    public static String letras ="";
    private JPanel contentPane;
    private ArrayList <String> listCanciones;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    SeleccionaCancion frame2 = new SeleccionaCancion();
                    frame2.setLocationRelativeTo(null);
                    frame2.setVisible(true);
                    frame2.setResizable(false);
                    frame2.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                    frame2.setTitle("Karaoke Center");
                } 
                catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public SeleccionaCancion() {
        setUndecorated(true);
        setBounds(0, 0, 650, 740);
        getContentPane().setLayout(null);
        contentPane = new JPanel();
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
        tabbedPane.setBounds(0, 0, 650, 740);
        getContentPane().add(tabbedPane);

        JPanel seleccion = new JPanel();
        seleccion.setBounds(0, 0, 650, 740);
        tabbedPane.addTab("Selecciona canción", null, seleccion, null);
        seleccion.setLayout(null);


        JPanel reproduccion = new JPanel();
        tabbedPane.addTab("Reproducción", null, reproduccion, null);
        reproduccion.setBounds(0, 0, 650, 740);
        reproduccion.setLayout(null);
        reproduccion.setBackground(Color.black);
        tabbedPane.setEnabledAt(1, false);

        JMenuBar menuBar = new JMenuBar();
        menuBar.setBounds(400, 5, 250, 45);
        seleccion.add(menuBar);

        JMenu menuFavoritos = new JMenu("Favoritas");
        menuBar.add(menuFavoritos);

        JMenuItem itemFav = new JMenuItem("Ver canciones favoritas");
        itemFav.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {

                try {
                    close();

                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        });
        menuFavoritos.add(itemFav);

        JMenu menuReproduccion = new JMenu("Reproduccion");
        menuBar.add(menuReproduccion);

        JMenuItem itemPlay = new JMenuItem("Play");
        itemPlay.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(null, "Tienes que seleccionar un tema y darle al botón grande de Play");
            }
        });
        menuReproduccion.add(itemPlay);

        JMenuItem itemPause = new JMenuItem("Pause");
        itemPause.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    System.out.println("h");
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        });
        menuReproduccion.add(itemPause);

        JMenuItem itemResume = new JMenuItem("Resume");
        itemResume.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    System.out.println("h");
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        });

        menuReproduccion.add(itemResume);

        JMenuItem itemStop = new JMenuItem("Stop");
        itemStop.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    System.out.println("h");
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        });
        menuReproduccion.add(itemStop);

        JToolBar toolBar = new JToolBar();
        toolBar.setBounds(0, 5, 460, 45);
        seleccion.add(toolBar);

        /*
         * botón para volver a la pantalla de login
         */
        JButton btnAtras = new JButton("Atras");
        btnAtras.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                try {
                    close();
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                System.out.println("h");

            }
        });
        toolBar.add(btnAtras);

        /*
         * en caso de estar habilitada la siguiente pestaña, pasara a ella
         */
        JButton btnAdelante = new JButton("Adelante");
        btnAdelante.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                if(tabbedPane.isEnabledAt(1)==true){
                    tabbedPane.setSelectedIndex(1);
                }
            }
        });
        toolBar.add(btnAdelante);

        JButton btnEdPerfil = new JButton("Editar Perfil");
        btnEdPerfil.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                System.out.println("h");
                try {
                    close();

                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        });
        toolBar.add(btnEdPerfil);

        JButton btnGoPremium = new JButton("Go Premium");
        btnGoPremium.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                  visa = JOptionPane.showInputDialog("Introduce tu número de tarjeta VISA y te cobraremos la suscripción"); 
            }
        });
        toolBar.add(btnGoPremium);

        JLabel lblEscoge = new JLabel("Bienvenido al menú de reproducción, escoge entre una de tus 10 canciones:");
        lblEscoge.setBounds(12, 117, 626, 45);
        seleccion.add(lblEscoge);

        JLabel lblPlay = new JLabel("");
        lblPlay.setBounds(278, 174, 323, 32);
        seleccion.add(lblPlay);

        /*
         * para cargar las canciones al JList llamo al método  
         * generarCanciones, el cual, tras hacer una operación CRUD 
         * sobre la BBDD nos devolverá el listado de canciones
         * del usuario
         */

        JList list = new JList(generatePaths());
        list.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                if (list.getSelectedIndex()==0){
                    lblPlay.setText("Ahora dale al Play!!!");
                }
                else if (list.getSelectedIndex()==1){
                    lblPlay.setText("Ahora dale al Play!!!");
                }
                else if (list.getSelectedIndex()==2){
                    lblPlay.setText("Ahora dale al Play!!!");
                }
                //y asi para todos los temas
            }
        });
        list.setBounds(41, 191, 200, 226);
        seleccion.add(list);

        /*
         * 
         */
        JButton btnPlayIcono = new JButton("");
        btnPlayIcono.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int selected=list.getSelectedIndex();
                String[]listPaths=generatePaths();
                System.out.println(selected + "el path "+listPaths[selected]);
                panel fondo = new panel(listPaths[selected]);
                fondo.setBounds(32, 62, 582, 220);
                reproduccion.add(fondo);
                tabbedPane.setEnabledAt(1, true);
                tabbedPane.setSelectedIndex(1);
                try {
                     System.out.println("h");
                } 
                catch (Exception ex) {
                       System.out.println("Error: " + ex.getMessage());
                }
            }
        });
        btnPlayIcono.setIcon(new ImageIcon(SeleccionaCancion.class.getResource("/imagenes/windows-media-player-play-button-updated_f.png")));
        btnPlayIcono.setBounds(371, 289, 139, 128);
        seleccion.add(btnPlayIcono);

        JLabel lblSpoon = new JLabel("Karaoke Center es una aplicación desarrollada por industrias Spoon");
        lblSpoon.setBounds(12, 650, 624, 22);
        seleccion.add(lblSpoon);

        JMenuBar menuBar1 = new JMenuBar();
        menuBar1.setBounds(400, 5, 250, 45);
        reproduccion.add(menuBar1);

        JMenu menuFavoritos1 = new JMenu("Favoritas");
        menuBar1.add(menuFavoritos1);

        /*
         * boton que llama al frame de Canciones Favoritas
         */
        JMenuItem itemFav1 = new JMenuItem("Ver canciones favoritas");
        itemFav1.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {

                try {
                    close();
                    System.out.println("h");
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        });
        menuFavoritos1.add(itemFav1);

        JMenu menuReproduccion1 = new JMenu("Reproduccion");
        menuBar1.add(menuReproduccion1);

        JMenuItem itemPlay1 = new JMenuItem("Play");
        itemPlay1.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    System.out.println("h");
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        });
        menuReproduccion1.add(itemPlay1);

        JMenuItem itemPause1 = new JMenuItem("Pause");
        itemPause1.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    System.out.println("h");
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        });
        menuReproduccion1.add(itemPause1);

        JMenuItem itemResume1 = new JMenuItem("Resume");
        itemResume1.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    System.out.println("h");
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        });
        menuReproduccion1.add(itemResume1);


        JMenuItem itemStop1 = new JMenuItem("Stop");
        itemStop1.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("El evento stop item");
                    try {
                        System.out.println("h");
                    } catch (Exception e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
            }
        });
        menuReproduccion1.add(itemStop1);

        JToolBar toolBar1 = new JToolBar();
        toolBar1.setBounds(0, 5, 460, 45);
        reproduccion.add(toolBar1);

        /*
         * This button takes us back to the previous tab
         */
        JButton btnAtras1 = new JButton("Atras");
        btnAtras1.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                tabbedPane.setSelectedIndex(0);
            }
        });
        toolBar1.add(btnAtras1);

        JButton btnAdelante1 = new JButton("Adelante");
        toolBar1.add(btnAdelante1);

        JButton btnGoPremium1 = new JButton("Go Premium");
        btnGoPremium1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                  visa = JOptionPane.showInputDialog("Introduce tu número de tarjeta VISA y te cobraremos la suscripción"); 
            }
        });
        toolBar1.add(btnGoPremium1);

        txtArRepro=new JTextArea();
        txtArRepro.setFont(new Font("Dialog", Font.BOLD, 20));
        txtArRepro.setForeground(Color.WHITE);

        JScrollPane scrollPane = new JScrollPane(txtArRepro);
        scrollPane.setBounds(32, 290, 582, 235);
        txtArRepro.setBackground(Color.BLUE);
        reproduccion.add(scrollPane);

        txtArRepro.setText("London Calling...");

        JLabel lblSpoon2 = new JLabel("Karaoke Center es una aplicación desarrollada por industrias Spoon");
        lblSpoon2.setBounds(12, 650, 624, 22);
        lblSpoon2.setForeground(Color.white);
        reproduccion.add(lblSpoon2);


        JButton btnFavoritos = new JButton("Añadir canción a Favoritas");
        btnFavoritos.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                boolean control=false;
                if (!control){
                    JOptionPane.showMessageDialog(getRootPane(), "A nosotros también nos encanta este tema, pero solo lo puedes marcar una vez como favorito ;)");
                }
            }
        });
        btnFavoritos.setBounds(199, 585, 229, 25);
        reproduccion.add(btnFavoritos);
    }

    /*
     * métodos de la clase
     */
    public void close() throws Exception{
        WindowEvent winClosingEvent = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
        Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(winClosingEvent);

    }

    /*
     * I method to generate Strings with path to images
     */
    public String[] generatePaths(){
        String path1="/imagenes/play.png";
        String path2="/imagenes/port_1999.jpg";
        String path3="/imagenes/port_loncall.jpg";
        String [] selecciones ={path1, path2, path3};
        return selecciones;
    }

    /*
     * panel to set Image
     */
    public class panel extends JPanel{

        ImageIcon imagen;
        String nombre;

        public panel(String nombre){
            this.nombre=nombre;

    }
        public void paint(Graphics g){
            super.paint(g);
            Dimension tamanyo=getSize();
            imagen = new ImageIcon(getClass().getResource(nombre));
            g.drawImage(imagen.getImage(), 0, 0, tamanyo.width, tamanyo.height, null);
        }

    }
}
user1803551
  • 12,965
  • 5
  • 47
  • 74
Steven
  • 1,236
  • 1
  • 13
  • 37
  • 3
    Avoid using `null` layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify. You might find [How to Use CardLayout](http://docs.oracle.com/javase/tutorial/uiswing/layout/card.html) a better choice then using a `JTabbedPane` – MadProgrammer Feb 18 '16 at 09:03
  • 3
    The likely problem is to do with your `panel`, which override's paint. One of the things that `paint` does is calls `paintComponent`, which clears the background. Don't load resources in paint methods and don't change the state of the component in paint methods (like calling `setOpaque(false)`). You should be overriding `paintComponent` (calling `super.paintComponent` first) and the drawing your image. You might also find that `JLabel` can do this for you with less paiin – MadProgrammer Feb 18 '16 at 09:05
  • 2
    Consider providing a [runnable example](https://stackoverflow.com/help/mcve) which demonstrates your problem. This is not a code dump, but an example of what you are doing which highlights the problem you are having. This will result in less confusion and better responses – MadProgrammer Feb 18 '16 at 09:06
  • 2
    And on making a runnable example as suggested by @MadProgrammer.. One way to get image(s) for an example is to hot link to images seen in [this Q&A](http://stackoverflow.com/q/19209650/418556). – Andrew Thompson Feb 18 '16 at 09:07
  • Hi there, you guys are awesome, so quick to answer. Thank you very much, I've read about null layouts, but it's how they want us to work this one... About the paintComponent, I've tried putting it as the first order, still not working. I'll take a quick look at the runnable example, see if I can do that now, if not later on. Thank you again – Steven Feb 18 '16 at 09:31
  • Just added runnable example to original message ;) – Steven Feb 18 '16 at 10:12
  • Don't add "[SOLVED]" to your title, just [accept an answer](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235). – user1803551 Feb 25 '16 at 15:46
  • It wasn't solved through an answer, as a matter of fact I did not receive an answer, only comments. However I won't do it in future solved yet unanswered topics – Steven Feb 26 '16 at 19:08

1 Answers1

0

Ok, with the help of a friend, I've managed to solve the issue, this has been done declaring a variable of the class panel (I know, terrible mistake class name with lowcase), anyway, the code:

I declare variable and getters / setters:

panel currentPanel;

    public panel getCurrentPanel() {
        return currentPanel;
    }

    public void setCurrrentPanel(panel fondo) {
        this.currentPanel = fondo;
    }

And on the play button:

if(currentPanel != null)
    reproduccion.remove(currentPanel);

panel fondo = new panel(listPaths[selected]);
    fondo.setBounds(32, 62, 582, 220);
    setCurrrentPanel(fondo);
    reproduccion.add(fondo);
Steven
  • 1,236
  • 1
  • 13
  • 37