简体   繁体   English

如何使JTable单元(链接)可单击

[英]How to make a JTable cell (link) clickable

I am making a hospital project in Java, I have made a JTable which is fetching Hospital Name and a Hospital image link ie "Click to see more" from SQL database. 我正在用Java创建一个医院项目,我已经创建了一个JTable ,它从SQL数据库获取医院名称和医院图像链接,即"Click to see more" My problem is that the data is successfully fetched from database to the table, but I can't click the link which is in the table cell. 我的问题是数据已成功从数据库提取到表中,但我无法单击表格单元格中的链接。

How to make the link active? 如何激活链接?

Consider using JXTable (a class of SwingX ): it supports a hyperlink renderer which can be configured to do any action, based on the cell value 考虑使用JXTable(一类SwingX ):它支持超链接渲染器,可根据单元格值配置为执行任何操作

JXTable table = new JXTable(myModel);
AbstractHyperlinkAction<Object> simpleAction = new AbstractHyperlinkAction<Object>(null) {

    public void actionPerformed(ActionEvent e) {
        // here goes what you want to do on activating the hyperlink
        //LOG.info("hit: " + getTarget());
    }

};
TableCellRenderer renderer = new DefaultTableRenderer(
    new HyperlinkProvider(simpleAction));
table.getColumnExt(0).setEditable(false);
table.getColumnExt(0).setCellRenderer(renderer);

You can either make a TableCellEditor whose isCellEditable method could be used to activate on a single mouse click. 您可以创建一个TableCellEditorisCellEditable方法可用于在单击鼠标时激活。 Frankly, this just get messy. 坦率地说,这只是变得混乱。

Or, you could attach a MouseListener to the table directly and monitor for the mouseClicked event. 或者,您可以直接将MouseListener附加到表中并监视mouseClicked事件。

On the clicked event, you could need to getSelectedColumn and getSelectedRow to determine if they've clicked on the column you want and get the link value from the selected cell, using getValueAt 在单击的事件上,您可能需要getSelectedColumngetSelectedRow来确定他们是否已单击所需的列并使用getValueAt从所选单元格中获取链接值

You'll need to take into consideration that the table may be sorted or the columns are no longer in the order you started them in (the user may have moved them). 您需要考虑到表可能已排序或列不再按您启动它们的顺序(用户可能已移动它们)。

Then you'll need convertColumnIndexToView and convertRowIndexToModel 然后你需要convertColumnIndexToViewconvertRowIndexToModel

Simple :D 简单:D

I think that avoiding an external library is a better way to go as MadProgrammer suggests, but I guess swingx is still pure java. 我认为避免使用外部库是MadProgrammer建议的更好的方法,但我认为swingx仍然是​​纯粹的java。 Anyway, I would use the mouseClicked listener and then open uri in the way described in this question How to add hyperlink in JLabel . 无论如何,我会使用mouseClicked监听器,然后按照此问题中描述的方式打开uri 如何在JLabel中添加超链接

JTable table = new JTable();

table.addMouseListener(new MouseAdapter() {
  public void mouseClicked(MouseEvent e) {

        int row = table.getSelectedRow();
        int col = table.getSelectedColumn();

        //build your address / link

        URI uri = new URI("http: your link here");

        //see below
        open(uri);
      }
    });

//Then elsewhere as from the McDowell answer
private static void open(URI uri) {
  if (Desktop.isDesktopSupported()) {
    try {
       Desktop.getDesktop().browse(uri);
      } catch (IOException e) { /* TODO: error handling */ }
   } else { /* TODO: error handling */ }
 }

I solved adding a button inside the cells clickable, I followed this tutorial Table Button Column from Rob Camick: 我解决了在单元格中添加一个按钮,我按照Rob Camick的教程表按钮列

String[] columnNames = {"First Name", "Last Name", ""};
Object[][] data =
{
    {"Homer", "Simpson", "delete Homer"},
    {"Madge", "Simpson", "delete Madge"},
    {"Bart",  "Simpson", "delete Bart"},
    {"Lisa",  "Simpson", "delete Lisa"},
};

DefaultTableModel model = new DefaultTableModel(data, columnNames);
JTable table = new JTable( model );

Then: 然后:

Action delete = new AbstractAction()
{
    public void actionPerformed(ActionEvent e)
    {
        JTable table = (JTable)e.getSource();
        int modelRow = Integer.valueOf( e.getActionCommand() );
        ((DefaultTableModel)table.getModel()).removeRow(modelRow);
    }
};

ButtonColumn buttonColumn = new ButtonColumn(table, delete, 2);
buttonColumn.setMnemonic(KeyEvent.VK_D);

Where ButtonColumn class is: ButtonColumn类的位置是:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;

/**
 *  The ButtonColumn class provides a renderer and an editor that looks like a
 *  JButton. The renderer and editor will then be used for a specified column
 *  in the table. The TableModel will contain the String to be displayed on
 *  the button.
 *
 *  The button can be invoked by a mouse click or by pressing the space bar
 *  when the cell has focus. Optionally a mnemonic can be set to invoke the
 *  button. When the button is invoked the provided Action is invoked. The
 *  source of the Action will be the table. The action command will contain
 *  the model row number of the button that was clicked.
 *
 */
public class ButtonColumn extends AbstractCellEditor
    implements TableCellRenderer, TableCellEditor, ActionListener, MouseListener
{
    private JTable table;
    private Action action;
    private int mnemonic;
    private Border originalBorder;
    private Border focusBorder;

    private JButton renderButton;
    private JButton editButton;
    private Object editorValue;
    private boolean isButtonColumnEditor;

    /**
     *  Create the ButtonColumn to be used as a renderer and editor. The
     *  renderer and editor will automatically be installed on the TableColumn
     *  of the specified column.
     *
     *  @param table the table containing the button renderer/editor
     *  @param action the Action to be invoked when the button is invoked
     *  @param column the column to which the button renderer/editor is added
     */
    public ButtonColumn(JTable table, Action action, int column)
    {
        this.table = table;
        this.action = action;

        renderButton = new JButton();
        editButton = new JButton();
        editButton.setFocusPainted( false );
        editButton.addActionListener( this );
        originalBorder = editButton.getBorder();
        setFocusBorder( new LineBorder(Color.BLUE) );

        TableColumnModel columnModel = table.getColumnModel();
        columnModel.getColumn(column).setCellRenderer( this );
        columnModel.getColumn(column).setCellEditor( this );
        table.addMouseListener( this );
    }


    /**
     *  Get foreground color of the button when the cell has focus
     *
     *  @return the foreground color
     */
    public Border getFocusBorder()
    {
        return focusBorder;
    }

    /**
     *  The foreground color of the button when the cell has focus
     *
     *  @param focusBorder the foreground color
     */
    public void setFocusBorder(Border focusBorder)
    {
        this.focusBorder = focusBorder;
        editButton.setBorder( focusBorder );
    }

    public int getMnemonic()
    {
        return mnemonic;
    }

    /**
     *  The mnemonic to activate the button when the cell has focus
     *
     *  @param mnemonic the mnemonic
     */
    public void setMnemonic(int mnemonic)
    {
        this.mnemonic = mnemonic;
        renderButton.setMnemonic(mnemonic);
        editButton.setMnemonic(mnemonic);
    }

    @Override
    public Component getTableCellEditorComponent(
        JTable table, Object value, boolean isSelected, int row, int column)
    {
        if (value == null)
        {
            editButton.setText( "" );
            editButton.setIcon( null );
        }
        else if (value instanceof Icon)
        {
            editButton.setText( "" );
            editButton.setIcon( (Icon)value );
        }
        else
        {
            editButton.setText( value.toString() );
            editButton.setIcon( null );
        }

        this.editorValue = value;
        return editButton;
    }

    @Override
    public Object getCellEditorValue()
    {
        return editorValue;
    }

//
//  Implement TableCellRenderer interface
//
    public Component getTableCellRendererComponent(
        JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
    {
        if (isSelected)
        {
            renderButton.setForeground(table.getSelectionForeground());
            renderButton.setBackground(table.getSelectionBackground());
        }
        else
        {
            renderButton.setForeground(table.getForeground());
            renderButton.setBackground(UIManager.getColor("Button.background"));
        }

        if (hasFocus)
        {
            renderButton.setBorder( focusBorder );
        }
        else
        {
            renderButton.setBorder( originalBorder );
        }

//      renderButton.setText( (value == null) ? "" : value.toString() );
        if (value == null)
        {
            renderButton.setText( "" );
            renderButton.setIcon( null );
        }
        else if (value instanceof Icon)
        {
            renderButton.setText( "" );
            renderButton.setIcon( (Icon)value );
        }
        else
        {
            renderButton.setText( value.toString() );
            renderButton.setIcon( null );
        }

        return renderButton;
    }

//
//  Implement ActionListener interface
//
    /*
     *  The button has been pressed. Stop editing and invoke the custom Action
     */
    public void actionPerformed(ActionEvent e)
    {
        int row = table.convertRowIndexToModel( table.getEditingRow() );
        fireEditingStopped();

        //  Invoke the Action

        ActionEvent event = new ActionEvent(
            table,
            ActionEvent.ACTION_PERFORMED,
            "" + row);
        action.actionPerformed(event);
    }

//
//  Implement MouseListener interface
//
    /*
     *  When the mouse is pressed the editor is invoked. If you then then drag
     *  the mouse to another cell before releasing it, the editor is still
     *  active. Make sure editing is stopped when the mouse is released.
     */
    public void mousePressed(MouseEvent e)
    {
        if (table.isEditing()
        &&  table.getCellEditor() == this)
            isButtonColumnEditor = true;
    }

    public void mouseReleased(MouseEvent e)
    {
        if (isButtonColumnEditor
        &&  table.isEditing())
            table.getCellEditor().stopCellEditing();

        isButtonColumnEditor = false;
    }

    public void mouseClicked(MouseEvent e) {}
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM