JTable,由MousClick在混凝土单元中添加动态标签

时间:2016-05-20 17:40:53

标签: java swing jtable

我有任务,在混凝土栏中添加图像,在jTable中添加原始图像。我试图使用setCellRendered,但它无法正常工作。也许有人有同样的任务。 我试图通过DefaultTableCellRenderer创建,但现在无法理解我如何将此Renderer称为具体单元格,而不是列,例如[3] [4]     public Frame1(){         初始化();     }

#lang racket/gui

(define *our-frame*
  (new frame%
       [width 600]
       [height 800]
       [x 1000]
       [y 100]
       [label "Label"]
       [style '(no-resize-border)]
       ))

(define *row*
  (new horizontal-panel%
       [parent *our-frame*]
       [style '(border)]))

(define *left-column*
  (new horizontal-panel%
       [parent *row*]
       [style '(border)]))

(define *right-column*
  (new horizontal-panel%
       [parent *row*]
       [style '(border)]))

(define *game-panel*
  (new vertical-panel%
       [parent *left-column*]
       [style '(border)]
       [alignment '(left center)]
       ))

(define *button-panel*
  (new vertical-panel%
       [parent *right-column*]
       [style '(border)]
       [alignment '(right bottom)]
       ))

(define *game-button*
  (new button%
       [parent *button-panel*]
       [label "Pause"]
       [min-width 200]
       [min-height 100]
       ))

(define *new-game-button*
  (new button%
       [parent *button-panel*]
       [label "New Game"]
       [min-width 200]
       [min-height 100]
       ))

(send *our-frame* show #T)

}

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 364, 385);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    table = new JTable();
    table.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent event) {
            Point point = event.getPoint();
            JTable target = (JTable)event.getSource();
            int column = table.columnAtPoint(point); 
            int row = target.getSelectedRow();
           table.getColumnModel().getColumn(column).setCellRenderer(new ImageRenderer());
            //JOptionPane.showMessageDialog(table, "Column header #" + column + " is clicked");
        }
    });
    table.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, Color.DARK_GRAY, Color.LIGHT_GRAY, SystemColor.menu, null));
    table.setModel(new DefaultTableModel(
        new Object[][] {
            {null, "", null, null, null, null},
            {null, null, null, null, null, null},
            {null, null, null, null, null, null},
            {null, null, null, null, null, null},
            {null, null, null, null, null, null},
            {null, null, null, null, null, null},
            {null, null, null, null, null, null},
        },
        new String[] {
            "New column", "New column", "New column", "New column", "New column", "New column"
        }
    ));
    table.getColumnModel().getColumn(0).setMinWidth(50);
    table.setBounds(0, 0, 350, 350);
    table.setRowHeight(50);
    frame.getContentPane().add(table);
}

}

2 个答案:

答案 0 :(得分:2)

无需自定义渲染。

您需要做的是:

  1. Icon添加到TableModel
  2. 覆盖getColumnClass(...)的{​​{1}}方法以返回TableModel,该表格将使用默认的图标渲染器。
  3. 如果您确实需要自定义渲染器,请查看Using Custom Renderers上Swing教程中的部分,以获取更多信息和工作示例。

    Class.Icon

    不要使用空布局!不要使用setBounds()。 Swing旨在与布局管理器一起使用。您还需要将表添加到JScrollPane,以便显示列标题。同样,本教程中的示例将向您展示如何执行此操作。因此,请阅读教程并下载演示代码。

答案 1 :(得分:0)

来自oracle.com的修改示例。它显示所选单元格上的图标。请看看:

/*
 * SimpleTableDemo.java requires no other files.
 */
import java.awt.Component;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.io.IOException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.table.DefaultTableCellRenderer;

public class SimpleTableDemo extends JPanel {

    private static final String ICON_IMAGE
            = "http://icons.iconarchive.com/icons/scafer31000/bubble-circle-3/16/GameCenter-icon.png";

    public SimpleTableDemo() {
        super(new GridLayout(1, 0));

        String[] columnNames = {"First Name",
            "Last Name",
            "Sport",
            "# of Years",
            "Vegetarian"};

        Object[][] data = {
            {"Kathy", "Smith",
                "Snowboarding", new Integer(5), new Boolean(false)},
            {"John", "Doe",
                "Rowing", new Integer(3), new Boolean(true)},
            {"Sue", "Black",
                "Knitting", new Integer(2), new Boolean(false)},
            {"Jane", "White",
                "Speed reading", new Integer(20), new Boolean(true)},
            {"Joe", "Brown",
                "Pool", new Integer(10), new Boolean(false)}
        };

        final JTable table = new JTable(data, columnNames);
        table.setPreferredScrollableViewportSize(new Dimension(500, 70));
        table.setFillsViewportHeight(true);
        java.awt.Image image = null;
        try {
            URL imageLoc = new URL(ICON_IMAGE);
            image = ImageIO.read(imageLoc);
        } catch (IOException ex) {
            Logger.getLogger(SimpleTableDemo.class.getName()).log(Level.SEVERE, null, ex);
        }
        final ImageIcon icon = new ImageIcon(image);
        table.setDefaultRenderer(Object.class, new ImageRenderer(icon));
        //Create the scroll pane and add the table to it.
        JScrollPane scrollPane = new JScrollPane(table);
        //Add the scroll pane to this panel.
        add(scrollPane);
    }

    /**
     * Create the GUI and show it. For thread safety, this method should be
     * invoked from the event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("SimpleTableDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane.
        SimpleTableDemo newContentPane = new SimpleTableDemo();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

    private class ImageRenderer extends DefaultTableCellRenderer {

        private final JLabel lbl = new JLabel();
        private final ImageIcon imageIcon;

        public ImageRenderer(ImageIcon imageIcon) {
            this.imageIcon = imageIcon;
            lbl.setIcon(imageIcon);
        }

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            Component result = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            if (hasFocus && isSelected) {
                result = lbl;
            }
            return result;
        }
    }
}