如何为JTable中的行创建翻转或悬停效果?

时间:2018-05-02 08:38:07

标签: java swing jtable jinternalframe rollover-effect

在我的应用程序中,我想用JTable的行创建一个翻转效果。例如,当鼠标进入行时,该行的背景颜色将改变;相反,当鼠标退出该行时,该行的颜色将恢复正常。 我已经提到了很多文章。

I got one answer but the class extending JTable and my table is in JInternalFrame so my class extends JInternalFrame.

这是我的代码

public class UpdateAdmin extends JInternalFrame {
public static JTable table;
private JScrollPane scrollPane;
public static String rowUserId;
private static String photoUrl;
 private int rollOverRowIndex = -1;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            try {
                UpdateAdmin frame = new UpdateAdmin();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}
    public UpdateAdmin() {
        addInternalFrameListener(new InternalFrameAdapter() {
            @Override
            public void internalFrameOpened(InternalFrameEvent arg0) {
                updateTable();
            }
        });
        getContentPane().setBackground(new Color(144, 202, 249));
        setClosable(true);
        setResizable(true);
        setMaximizable(true);
        setIconifiable(true);
        setTitle("View Admin");
        setBounds(100, 100, 1200, 571);
        getContentPane().setLayout(null);

        JLabel lblviewUsers = new JLabel("<html><ul><li>View Users</li></ul></html>");
        lblviewUsers.setBounds(10, 25, 188, 23);
        lblviewUsers.setFont(new Font("Tahoma", Font.PLAIN, 18));
        getContentPane().add(lblviewUsers);




        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        this.setLocation(dim.width/2-this.getSize().width/2, dim.height/2-this.getSize().height/2);
    }

    protected void updateTable() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/librarymanagement", "root", "santosh123");
            PreparedStatement ps = con.prepareStatement("select uid, photo, username, firstName, lastName, email, Mob_no, DOB, address, Gender, Usertype from users where Usertype='Admin'");
            ResultSet rs = ps.executeQuery();   


            table = new JTable(buildTableModel(rs));
            //table.getColumn("DP").setCellRenderer(new RightTableCellRenderer());
            table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
            //table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            table.setRowSelectionAllowed(false);
            table.setFocusable(false);
            table.setFillsViewportHeight(true);
            table.setRowHeight(35);
            TableColumn tc = table.getColumn("DP");
            tc.setMinWidth(40);
            tc.setMaxWidth(40);
            TableColumn tc1 = table.getColumn("Update");
            tc1.setMinWidth(70);
            tc1.setMaxWidth(70);
            TableColumn tc2 = table.getColumn("Delete");
            tc2.setMinWidth(70);
            tc2.setMaxWidth(70);
            TableColumn tc3 = table.getColumn("UID");
            tc3.setMinWidth(65);
            tc3.setMaxWidth(65);
/*          Dimension dm = new Dimension(5,1);
            table.setIntercellSpacing(new Dimension(dm));*/
            table.addMouseListener(new JTableButtonMouseListener(table));

            //table.getColumn("UID").setCellRenderer(new MyCellRenderer());

            table.addMouseMotionListener(new MouseAdapter() {
                public void mouseMoved(MouseEvent e) {
                    Point p = e.getPoint();
                    hoveredRow = table.rowAtPoint(p);
                    hoveredColumn = table.columnAtPoint(p);
                    table.repaint();
                }
                public void mouseExited(MouseEvent e) {
                    hoveredRow = hoveredColumn = -1;
                    table.repaint();
                }
            });

            JTableHeader header = table.getTableHeader();
            header.setFont(new Font("Tahoma", Font.BOLD, 14));

            addComponentListener(new ComponentAdapter() {
                @Override
                public void componentResized(ComponentEvent arg0) { 
                    scrollPane.setBounds(10, 80, getContentPane().getWidth()-20, 400);

                }
            });

            TableCellRenderer buttonRenderer = new JTableButtonRenderer();
            table.getColumn("Update").setCellRenderer(buttonRenderer);
            table.getColumn("Delete").setCellRenderer(buttonRenderer);

            final TableColumnModel columnModel = table.getColumnModel();
            for (int column = 0; column < table.getColumnCount(); column++) {
                int width = 15; // Min width
                for (int row = 0; row < table.getRowCount(); row++) {
                    TableCellRenderer renderer = table.getCellRenderer(row, column);
                    Component comp = table.prepareRenderer(renderer, row, column);
                    width = Math.max(comp.getPreferredSize().width +1 , width);

                }
                if(width > 300)
                    width=300;
                columnModel.getColumn(column).setPreferredWidth(width);
            }


            DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
            centerRenderer.setHorizontalAlignment( JLabel.CENTER );
            table.setDefaultRenderer(String.class, centerRenderer);
            //centerRenderer.setHorizontalTextPosition(DefaultTableCellRenderer.CENTER);

            /*DefaultTableCellRenderer renderer = new DefaultTableCellRenderer(){
                @Override
                public Component getTableCellRendererComponent(JTable arg0,Object arg1, boolean arg2, boolean arg3, int arg4, int arg5) {
                     Component tableCellRendererComponent = super.getTableCellRendererComponent(arg0, arg1, arg2, arg3, arg4, arg5);
                     int align = DefaultTableCellRenderer.LEFT;
                     if(align == DefaultTableCellRenderer.LEFT){
                         align = DefaultTableCellRenderer.CENTER;
                     }
                    ((DefaultTableCellRenderer)tableCellRendererComponent).setHorizontalAlignment(align);
                     return tableCellRendererComponent;
                }
            };          

            for(int i = 0; i < rs.getMetaData().getColumnCount(); i++)
            {
                table.getColumnModel().getColumn(+i).setCellRenderer(renderer);
            }*/


            scrollPane = new JScrollPane(table);
            //scrollPane.setBounds(10, 80, getContentPane().getWidth()-20, table.getRowHeight()*(table.getRowCount() + 1));
            scrollPane.setBounds(10, 80, 1570, 400);
            Dimension maxScrollPaneSize = new Dimension(getContentPane().getWidth()-20, 400);
            scrollPane.setMaximumSize(maxScrollPaneSize);
            scrollPane.setBackground(new Color(144, 202, 249));
            scrollPane.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1, true));
            scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
            scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); 
            getContentPane().add(scrollPane);   

            // Closes the Connection        
            rs.close();
            ps.close();
            con.close();

        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

如何将上述链接解决方案应用于我的桌面?

2 个答案:

答案 0 :(得分:0)

我只是做了一些改变而且它为我工作。

<img src="/assets/img1.jpg" />

答案 1 :(得分:0)

试试这个:

        table.addMouseMotionListener(new MouseMotionListener() {
        @Override
        public void mouseDragged(MouseEvent e) {

        }

        @Override
        public void mouseMoved(MouseEvent e) {
            Point p = e.getPoint();
            int y = p.y / table.getRowHeight();
            if(y < table.getModel().getRowCount())
                table.setRowSelectionInterval(0, y);
        }
    });