阻止TableCellEditor显示Class'描述符

时间:2014-02-01 17:42:27

标签: java swing jtable tablecelleditor defaulttablemodel

我遇到了一个奇怪的错误。我的歌曲列表位于JFrame的右侧。当我在任何项目上单击一次时,它会执行我想要的操作:将颜色设置为灰色。但是双击它会显示我的自定义表格单元格的类'描述符。

当我点击一次(正确)

enter image description here

当我点击两次(错误)

enter image description here

继承我的代码

PanelItem class

package dierplayer;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;

/**
 * @author srnec
 */
public class PanelItem extends javax.swing.JPanel implements TableCellRenderer {

    private Thread focusThread;
    private int startPosX, startPosY;

    public PanelItem() {
        initComponents();
        this.setPreferredSize(new Dimension(20, 30));
        startPosX = songLabel.getX();
        startPosY = songLabel.getY();
    }

    /**
     * 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() {

        songLabel = new javax.swing.JLabel();

        songLabel.setText("Song");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(songLabel)
                .addGap(0, 88, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(songLabel)
                .addGap(0, 45, Short.MAX_VALUE))
        );
    }// </editor-fold>                        


    // Variables declaration - do not modify                     
    private javax.swing.JLabel songLabel;
    // End of variables declaration                   

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {

        this.setSelected(isSelected);

        return this;

    }

    public void setSelected(boolean isSelected) {
        if (isSelected) {
            this.setBackground(Color.GRAY);
        } else {
            this.setBackground(Color.WHITE);
        }
    }
}   

PanelItemEditor class

package dierplayer;

import java.awt.Component;
import java.util.EventObject;
import javax.swing.JTable;
import javax.swing.event.CellEditorListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;

/**
 * @author srnec
 */
public class PanelItemEditor extends DefaultTableModel implements  TableCellEditor{


    @Override
    public boolean isCellEditable(int row,int column)
    {
        return false;
    }

    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public Object getCellEditorValue() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public boolean isCellEditable(EventObject anEvent) {
     return false;
    }

    @Override
    public boolean shouldSelectCell(EventObject anEvent) {
       return true;
    }

    @Override
    public boolean stopCellEditing() {
        return true;
    }

    @Override
    public void cancelCellEditing() {

    }

    @Override
    public void addCellEditorListener(CellEditorListener l) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void removeCellEditorListener(CellEditorListener l) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

}

MainContext class

package dierplayer;

import java.io.File;
import java.util.Vector;
import javax.swing.JFileChooser;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;

/**
 * @author srnec
 */
public class MainContext extends javax.swing.JFrame 
{

    private DierPlayer mainPlayer;
    public MainContext() 
    {
        initComponents();
        mainPlayer=new DierPlayer();

        songList.setCellEditor(new PanelItemEditor());
        songList.getColumnModel().getColumn(0).setCellRenderer(new PanelItem());

        DefaultTableModel dtm = (DefaultTableModel) songList.getModel();

        Vector v = new Vector();
        v.add(new PanelItem());
        dtm.addRow(v);  
        v.clear();
        v.add(new PanelItem());
        dtm.addRow(v);
        v.clear();
        v.add(new PanelItem());
        dtm.addRow(v);

    }


    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        progressPanel = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        songList = new javax.swing.JTable();
        MainMenuBar = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        OpenMenuItem = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        progressPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        javax.swing.GroupLayout progressPanelLayout = new javax.swing.GroupLayout(progressPanel);
        progressPanel.setLayout(progressPanelLayout);
        progressPanelLayout.setHorizontalGroup(
            progressPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 582, Short.MAX_VALUE)
        );
        progressPanelLayout.setVerticalGroup(
            progressPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 55, Short.MAX_VALUE)
        );

        songList.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Title 1"
            }
        ));
        jScrollPane2.setViewportView(songList);

        jMenu1.setText("File");

        OpenMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
        OpenMenuItem.setText("Open");
        OpenMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                OpenMenuItemActionPerformed(evt);
            }
        });
        jMenu1.add(OpenMenuItem);

        MainMenuBar.add(jMenu1);

        jMenu2.setText("Edit");
        MainMenuBar.add(jMenu2);

        setJMenuBar(MainMenuBar);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(progressPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 488, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(progressPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>                        

    private void OpenMenuItemActionPerformed(java.awt.event.ActionEvent evt) {                                             
        JFileChooser chooser = new JFileChooser();
        chooser.setMultiSelectionEnabled(true);
        chooser.showOpenDialog(this);
        File[] files = chooser.getSelectedFiles();

    }                                            

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainContext.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainContext.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainContext.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainContext.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainContext().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JMenuBar MainMenuBar;
    private javax.swing.JMenuItem OpenMenuItem;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JPanel progressPanel;
    private javax.swing.JTable songList;
    // End of variables declaration                   
}

2 个答案:

答案 0 :(得分:1)

您已在评论中说明:

  

双击,由该特定表示的歌曲   表格单元格将被播放,右键单击也会有一些菜单   示出(移除,...)。

我认为你混淆了TableCellRendererTableCellEditor的概念(参见Concepts: Editors and Renderers)。单元格渲染器应显示一些文本,比如歌曲的标题,而单元格编辑器应允许用户修改此值。由于用户在单元格上双击(或按F2键)时会自动调用单元格编辑器,因此提供单元格编辑器并不是您想要的。要实现您的目标,您必须遵循以下提示:

防止编辑单元格

由于您想要在用户双击单元格时播放歌曲,因此必须阻止单元格可编辑(因此不会调用单元格编辑器):

    DefaultTableModel model = new DefaultTableModel(new Object[]{"Songs list"}, 0) {
        @Override
        public boolean isCellEditable(int row, int column) {
            return false;
        }
    };

提供单元格渲染器以显示歌曲的名称

您已经完成了这一步。请注意,如果它唯一要做的就是更改背景/选择颜色,那么你可以摆脱它,只需按照以下步骤操作:

    table.setBackground(Color.WHITE);
    table.setSelectionBackground(Color.GRAY);

将MouseListener附加到表

要听取用户的双击和右键点击,您需要在表格中附加MouseListener

    table.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            if(e.isPopupTrigger()) {
                // show JPopupMenu here
            } else if(e.getClickCount() >= 2){
                // play the song here
            }
        }
    });

您可能需要查看:


实施例

这是一个可以用作起点的小例子。一些说明:

  • IPlayableSong:此界面建立合约以创建可自行播放的歌曲对象。这取决于如何实现这些方法(f.i:使用库,如果需要多线程等)。

  • Song:它是以前界面的默认实现。你可以看到它没有真正实现任何东西(抛出UnsupportedOperationException),因为我没有任何库来播放MP3文件。但希望你明白这一点。

  • 使用SwingWorker:您会看到我使用SwingWorker创建歌曲并将其添加到桌面模型中。这是因为你想从MP3文件中获得一些ID3 tags,这意味着需要进行大量的IO操作。这种操作可能非常耗时,并且可能会阻止Event Dispatch Thread(也就是说EDT)导致GUI变得无响应(冻结)。所以swing工作者在后台线程中执行这些操作并更新EDT中的表模型。请参阅Concurrency in Swing trial

  • 中的详情

代码

import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

public class Demo {

    private JTable table;
    private IPlayableSong currentPlayingSong;

    private void createAndShowGUI() {

        DefaultTableModel model = new DefaultTableModel(new Object[]{"Songs list"}, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        table = new JTable(model);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                Color background = isSelected ? Color.GRAY : Color.WHITE;
                setBackground(background);

                if(value instanceof Song) {
                    Song song = (Song)value;
                    setText(song.getTitle());
                }
                return this;
            }
        });

        table.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if(e.isPopupTrigger()) {
                    // show JPopupMenu here
                } else if(e.getClickCount() >= 2){
                    int row = table.rowAtPoint(e.getPoint());
                    int column = table.columnAtPoint(e.getPoint());

                    if(currentPlayingSong != null) {
                        currentPlayingSong.stop();
                    }

                    IPlayableSong song = (IPlayableSong)table.getValueAt(row, column);
                    song.play();
                    currentPlayingSong = song;
                }
            }

        });

        JMenuItem addDir = new JMenuItem("Add dir...");
        addDir.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                addSongs();
            }
        });

        JMenu fileMenu = new JMenu("File");
        fileMenu.add(addDir);

        JMenuBar menuBar = new JMenuBar();
        menuBar.add(fileMenu);

        JFrame frame = new JFrame("Demo");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.setJMenuBar(menuBar);
        frame.getContentPane().add(new JScrollPane(table));
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private void addSongs() {
        final List<File> fileList = new ArrayList<>();

        File file = new File(System.getProperty("user.dir"));
        JFileChooser fileChooser = new JFileChooser(file);
        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);        
        fileChooser.setMultiSelectionEnabled(true);
        fileChooser.setAcceptAllFileFilterUsed(false);
        fileChooser.setDialogTitle("Please select a directory");

        if(fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION && fileChooser.getSelectedFile().isDirectory()){
            File selectedDirectory = fileChooser.getSelectedFile();
            FilenameFilter filenameFilter = new FilenameFilter() {
                @Override
                public boolean accept(File dir, String name) {
                    return name.toUpperCase().endsWith("MP3");
                }
            };
            fileList.addAll(Arrays.asList(selectedDirectory.listFiles(filenameFilter)));

            DefaultTableModel model = (DefaultTableModel)table.getModel();
            model.setRowCount(0);

            SwingWorker<Void, Song> worker = new SwingWorker<Void, Song>() {
                @Override
                protected Void doInBackground() throws Exception {

                    for(File aFile : fileList) {
                        Song song = new Song(aFile, aFile.getName());
                        publish(song);
                    }
                    return null;
                }

                @Override
                protected void process(List<Song> chunks) {
                    DefaultTableModel model = (DefaultTableModel)table.getModel();
                    for(Song song: chunks) {
                        model.addRow(new Object[]{song});
                    }
                }
            };
            worker.execute();
        }

    }

    public interface IPlayableSong {

        public void play();

        public void stop();
    }

    public class Song implements IPlayableSong {

        private final String title;
        private final File file;

        public Song(File file, String title){
            this.file = file;
            this.title = title;
        }

        public String getTitle() {
            return title;
        }

        @Override
        public void play() {
            String message = String.format("Not supported yet! Trying to play %s", title);
            throw new UnsupportedOperationException(message);
        }

        @Override
        public void stop() {
            String message = String.format("Not supported yet! Trying to stop %s", title);
            throw new UnsupportedOperationException(message);
        }
    }

    public static void main(String[] args) {   
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {                
                new Demo().createAndShowGUI();
            }
        });
    }

}

答案 1 :(得分:0)

我不确切知道你的情况,但这是我的建议......在songList中使用该模型

songList.setModel(new model());

TableModel类“模型”

  

类模型扩展了DefaultTableModel {

     

模型(){

     

超级(               new Object [] [] {

     },
        new String [] {
            "Title 1"
        }
    );
}
    public boolean isCellEditable(int row,int column){
        return false;
    }
}