在JTabbed Panel

时间:2016-02-18 08:50:03

标签: java image swing jtabbedpane

这是我的第一个问题,我会尽力说清楚,如果我没有成功,请耐心等待:)

好的,我正在开发一个带有javax swing和mySQL for data(赋值)的卡拉OK应用程序,我有一个TabbedPane,其中有一个用于歌曲列表的选项卡和一个播放按钮,当我点击播放时它将我们发送到下一个标签,选取歌曲所需的所有细节,其中包括歌曲所属唱片的封面图像,然后激活第二个标签。

在第二个标签上,我为图​​片加载了一个小JPanel,并将其放在JTextField上方的主要版本中,我将会显示歌词

当我回到歌曲列表,选择不同的歌曲并点击播放时,问题就出现了,一切正常,除了图像,它总是重新加载前一个,加上我在paint方法中设置了println包含图像的面板,它似乎在应用程序启动期间多次调用该方法。

我有数千行代码,所以我会尝试留下最相关的(或者我认为可能是它)

宣告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);

播放按钮的代码:

 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);

这是我初始化图像面板并为其提供路径(仍在播放按钮内)的地方

            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);

这是放置在标签中的图像面板的类:

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);

        }

    }

这是返回列表歌曲标签(播放按钮所在的位置)按钮的代码

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);

事实上,它已经发布了相当长的帖子,我希望我能够正确地解释自己。

现在欢呼!

编辑以添加可运行的示例:

(我提供了图片的名称,我不确定这是如何工作的,但我想任何尝试我的代码的人都会创建一个文件夹,并将任何图片放在那里匹配名称?如果没有,请让我知道)

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);
        }

    }
}

1 个答案:

答案 0 :(得分:0)

好的,在朋友的帮助下,我已经设法解决了这个问题,这已经完成了声明类面板的变量(我知道,可怕的错误类名称为低位),无论如何,代码:< / p>

我宣布变量和getters / setters:

panel currentPanel;

    public panel getCurrentPanel() {
        return currentPanel;
    }

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

在播放按钮上:

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

panel fondo = new panel(listPaths[selected]);
    fondo.setBounds(32, 62, 582, 220);
    setCurrrentPanel(fondo);
    reproduccion.add(fondo);