JTable在列标题中带有"关闭"按钮

Ale*_*sey 8 java swing jtable jbutton tablecellrenderer

我正在尝试使用自定义列标题创建一个表.我希望列标题包含一个用户可以单击的按钮.按钮的功能是从表中删除列.从本质上讲,我试图建立类似这样.

这是我的代码:

public class CustomColumnHeadersTable {

    private static String[] columnNames = {
        "Column 1", "Column 2", "Column 3"
    };
    private static String[][] data = {
        {"A", "B", "C"},
        {"D", "E", "F"},
        {"G", "H", "I"}
    };

    public CustomColumnHeadersTable() {
        DefaultTableModel model = new DefaultTableModel((Object[][]) data, columnNames);
        JTable table = new JTable(model);
        JScrollPane scrollPane = new JScrollPane(table);

        //set Header Renderer of each column to use the Custom renderer
        Enumeration enumeration = table.getColumnModel().getColumns();
        while (enumeration.hasMoreElements()) {
            TableColumn aColumn = (TableColumn) enumeration.nextElement();
            aColumn.setHeaderRenderer(new CustomColumnCellRenderer());
        }

        JFrame frame = new JFrame();
        frame.getContentPane().add(scrollPane, BorderLayout.CENTER);

        frame.setPreferredSize(new Dimension(300, 150));
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        CustomColumnHeadersTable ccht = new CustomColumnHeadersTable();
    }
}

class CustomColumnCellRenderer implements TableCellRenderer {

    private static String iconURL = "http://www.accessdubuque.com/images/close_icon.gif";
        //using a URL for the icon, so I don't have to upload the icon with the question
    private static Dimension buttonSize = new Dimension(16, 16);
    private static Dimension buttonBoxSize = new Dimension(16, 16);
    private static Border panelBorder = BorderFactory.createRaisedBevelBorder();

    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        JPanel panel = new JPanel();
        JLabel label = new JLabel();
        JButton button = new JButton();
        Box buttonBox = Box.createHorizontalBox();
        BorderLayout layout = new BorderLayout();

        label.setText(table.getColumnName(column));

        try { button.setIcon(new ImageIcon(new URL(iconURL))); }
        catch (MalformedURLException ex) {
            Logger.getLogger(CustomColumnCellRenderer.class.getName()).log(Level.SEVERE, null, ex);
        }

        //set size of the button and it's box
        button.setMaximumSize(buttonSize);
        button.setSize(buttonSize);
        button.setPreferredSize(buttonSize);
        buttonBox.setMaximumSize(buttonBoxSize);
        buttonBox.setSize(buttonBoxSize);
        buttonBox.setPreferredSize(buttonBoxSize);

        button.addMouseListener(new CustomMouseListener()); //doesn't work...

        buttonBox.add(button);
        panel.add(label, BorderLayout.CENTER);
        panel.add(buttonBox, BorderLayout.EAST);

        panel.setBorder(panelBorder);

        return panel;
    }
}

class CustomMouseListener implements MouseListener
{
    public void mouseClicked(MouseEvent e) { System.out.println("Mouse Clicked."); }
    public void mousePressed(MouseEvent e) { System.out.println("Mouse Pressed."); }
    public void mouseReleased(MouseEvent e) { System.out.println("Mouse Released."); }
    public void mouseEntered(MouseEvent e) { System.out.println("Mouse Entered."); }
    public void mouseExited(MouseEvent e) { System.out.println("Mouse Exited."); }
}
Run Code Online (Sandbox Code Playgroud)

默认情况下,如果我理解正确,JTable使用JLabel来呈现列标题.我的想法是使用自定义的TableCellRenderer实现,并从几个组件构建我自己的列标题,即包含JLabel和JButton的JPanel.我在getTableCellRendererComponent(...)函数中构建并返回它.

在视觉上,这是有效的.问题是我无法检测按钮上的鼠标点击(或者,就此而言,在持有它的面板上).只需将MouseListener添加到按钮不起作用.事件永远不会到达.

我在网上发现了几个类似的东西,但它们没有达到我需要的功能.

首先,有一个如何将JCheckBox放入标题的示例,这里:

http://java-swing-tips.blogspot.com/2009/02/jtableheader-checkbox.html
Run Code Online (Sandbox Code Playgroud)

这个问题是整个标题是复选框.单击复选框或关联的标签会产生相同的效果.因此,无法对列进行排序.我想这样做,以便点击标签对列进行排序,然后单击关闭按钮将从表中删除列.换句话说,标题需要有两个独立的区域和单独的鼠标事件处理程序.

我在这里找到另一个例子:

http://www.devx.com/getHelpOn/10MinuteSolution/20425/1954?pf=true
Run Code Online (Sandbox Code Playgroud)

这包括将JButton放入表格的单元格中,然后检测表格本身的鼠标点击,计算发生点击的列和行,并将事件分派给相应的按钮.

这也是几个问题.首先,按钮位于单元格中,而不是标题中.第二,这只是一个组件,而不是JPanel中的几个组件.虽然我从这个例子中得到了调度事件的想法,但我不能使它适用于复合组件.

我尝试了另一种方法.我推断如果我能得到关闭按钮的坐标,那么知道鼠标点击的坐标我可以计算出哪个按钮被点击,并适当地调度事件.我运行了几次测试,发现表头中的组件实际上并不位于屏幕上.

我在我的main(public)类中添加了一个静态JButton变量,并使实现TableCellRenderer的类成为主类的内部类.在getTableCellRendererComponent(...)中,在返回之前,我将刚刚创建的JButton分配给该静态变量.这样,我就能掌握它,可以这么说.然后,在main中,我尝试使用该静态变量获取X(),getY(),getWidth(),getHeight()和getLocationOnScreen().X,Y,Width和Height都返回0.GetLocationOnScreen()使程序崩溃,说明该组件必须出现在屏幕上才能使此功能正常工作.

这个代码看起来像这样:

    public class CustomColumnHeadersTable {

        private static JButton static_button;
        ///the rest as before....
Run Code Online (Sandbox Code Playgroud)

"CustomColumnCellRenderer类实现TableCellRenderer"成为CustomColumnHeadersTable的内部类.为此,我必须放弃CustomColumnCellRenderer中的静态变量,所以我没有打扰图标或网址或类似的东西.我没有使用带图标的按钮,只使用了一个简单的按钮,上面写着"BUTTON"......

接下来,在return语句之前的getTableCellRendererComponent(...)里面,我做了

static_button = button;
Run Code Online (Sandbox Code Playgroud)

最后,在main()中,我尝试这样做:

    System.out.println("X: " + static_button.getX());
    System.out.println("Y: " + static_button.getY());
    System.out.println("W: " + static_button.getWidth());
    System.out.println("H: " + static_button.getHeight());
    System.out.println("LOC: " + static_button.getLocation());
    System.out.println("LOC on screen: " + static_button.getLocationOnScreen());
Run Code Online (Sandbox Code Playgroud)

输出如下所示:

X: 0
Y: 0
W: 0
H: 0
LOC: java.awt.Point[x=0,y=0]
Exception in thread "main" java.awt.IllegalComponentStateException: component must be showing on the screen to determine its location
at java.awt.Component.getLocationOnScreen_NoTreeLock(Component.java:1943)
at java.awt.Component.getLocationOnScreen(Component.java:1917)
...
Run Code Online (Sandbox Code Playgroud)

换句话说,按钮的所有尺寸都是0,并且根据Java,它实际上并不位于屏幕上(即使我可以看到它......).调用getLocationOnScreen()会使程序崩溃.

所以,如果可以的话,请帮忙.也许有人知道如何做到这一点.也许你可以建议一些其他尝试方法.或者,也许你知道它根本不可能......

谢谢您的帮助.

Nat*_* W. 2

是的,当我第一次尝试做类似的事情时,我感到很惊讶,比如将JButtons 放入 a 中JList- 由于您所说的原因,它不太有效。执行我想要的操作的正确方法是使用类似列表的方式LayoutManager将 s 放入JButton列表中。

JLabel在你的情况下,我会尝试使用s 和的组合MouseListeners,我相信它会正确工作。使用 aJLabel作为标题将允许您提供图像和文本,并且您可以MouseListenerJLabel. 当然,您不会获得与单击 a 时相同的视觉效果JButton(即按下按钮),但它会提供相同的功能。

另一件需要注意的事情是使用 static JButton(或 any JComponent)。这样做的问题是 的坐标JButton存储在其JButton自身中,这意味着您不能JButton在不同的地方使用相同的坐标。换句话说,如果您尝试static JButton多次将相同的内容添加到列表中,您将不会看到多个s,您只会在上次添加它的位置JButton看到。JButton实现所需效果的正确方法是保留对内容即图像和文本)的静态引用JButton,而不是其JButton本身。然后,只需JButton使用图像和文本实例化一个新的并将其放置在您想要的任何位置。一般来说,最好不要保留对 Swing 组件的静态引用,因为这使得同一组件不可能有多个实例。

摇摆有时并不那么摇摆。希望我提供了一些有用的信息 - 继续打好仗!