gpt4 book ai didi

java - 防止 TableCellEditor 显示类的描述符

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:05:59 24 4
gpt4 key购买 nike

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

当我点击一次(正确)

enter image description here

当我点击两次时(bug)

enter image description here

这是我的代码

PanelItem

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

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

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
}

最佳答案

您在评论中表示:

On the double click,the song that is represented by that specific table cell will be played,also on right click there will be some menu shown(remove,...).

我认为您混淆了 TableCellRenderer 的概念和 TableCellEditor (参见 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:这个接口(interface)建立一个契约来创建一个自播放的歌曲对象。这些方法的实现方式取决于实现方式(例如:使用的库、需要时的多线程等)。

  • Song:它是以前接口(interface)的默认实现。如您所见,它实际上并没有实现任何功能(抛出 UnsupportedOperationException),因为我没有任何库来播放 MP3 文件。但希望你明白这一点。

  • SwingWorker 的使用:您会看到我使用了 SwingWorker创建歌曲并将它们添加到表的模型中。这是因为你想得到一些 ID3 tags来自 MP3 文件,这意味着很多 IO 操作。这种操作可能非常耗时,并且可能会阻塞 Event Dispatch Thread。 (又名 EDT)导致 GUI 变得无响应(卡住)。所以 swing worker 在后台线程中执行这些操作,并在 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();
}
});
}

}

关于java - 防止 TableCellEditor 显示类的描述符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21501343/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com