java如何从数据库和JTable单元格Bg颜色摆动RGB颜色

问题描述 投票:-2回答:1

hi,我将Jbutton RGB背景色或前景色保存到数据库中之后,我想将背景色显示到JTable单元格中。当程序结果未显示出友善的指导并且我对JTable渲染不了解时,我遇到了问题。 JTable中的以下内容未根据数据库值绘制颜色

enter image description here

JavaCode

  /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication7;

import java.awt.Color;
import java.awt.Component;
import java.sql.Connection;
import java.sql.ResultSet;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author ultronhouse11
 */
public class demo extends javax.swing.JFrame {

    /**
     * Creates new form demo
     */
   public String var1;
   public String var2;

    public demo() {
        initComponents();
        showData();

       // table.getColumnModel().getColumn(0).setCellRenderer(new SimpleCellRenderer());

        getContentPane().setLayout(new java.awt.BorderLayout(5, 0));

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        //  a.setLayout(new MigLayout("fill,hidemode 5", "[80px][fill, grow]", ""));
    }


    public void showData() {


        try {

            Connection con = connectionDB.conDb();
            String sql = "select btn_color,text_color from menu_cat where visible='visible'";
            java.sql.PreparedStatement pst = con.prepareStatement(sql);
            DefaultTableModel dm = new DefaultTableModel();
            dm.setDataVector(
                    new Object[][]{},
                    new Object[]{"Button Color","Text Color"});

            ResultSet rs = pst.executeQuery();
            while (rs.next()) {

                String m1 = rs.getString("btn_color");
                String m2 = rs.getString("text_color");

                dm.addRow(new Object[]{m1, m2});



            }


          //    int cr = Integer.parseInt(rs.getString(4));
            table.setModel(dm);

            table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            table.getColumnModel().getColumn(0).setCellRenderer(new SimpleCellRenderer());





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

    }



    /**
     * 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() {

        b = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        table = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        b.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        table.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        table.setRowHeight(25);
        table.setRowMargin(5);
        jScrollPane1.setViewportView(table);

        javax.swing.GroupLayout bLayout = new javax.swing.GroupLayout(b);
        b.setLayout(bLayout);
        bLayout.setHorizontalGroup(
            bLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(bLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 1042, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        bLayout.setVerticalGroup(
            bLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(bLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 520, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(29, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(b, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(631, 631, 631))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(30, 30, 30)
                .addComponent(b, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>                        

    /**
     * @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(demo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(demo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(demo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(demo.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 demo().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JPanel b;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable table;
    // End of variables declaration                   

}

SimpleCellRenderer.java

class SimpleCellRenderer extends DefaultTableCellRenderer {

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        Component cell = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row,
                column);
     //   ((JLabel) cell).setIcon((Icon) value);
     //   ((JLabel) cell).setText("");
     //   ((JLabel) cell).setHorizontalAlignment(JLabel.CENTER);


            try {

                 //   int cr = Integer.parseInt();
                 //   int ct = Integer.parseInt();


                   cell.setBackground(Color.red); // database value here color
                 //   cell.setBackground(new Color(ct,true));


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


        return cell;
    }
    public void setColor(int cr){


    }

}
java swing jtable swingworker jtableheader
1个回答
0
投票

我已经在9到9个小时后解决了这个问题,当我们想要从数据库中获取RGB颜色时,我们需要渲染类并从Table模型中获取值enter image description here

class SimpleCellRenderer extends DefaultTableCellRenderer {

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        Component cell = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row,
                column);



            try {

               Object value1 = table.getModel().getValueAt(row, column);
                 int dbs=Integer.parseInt((String) value1);
                   JLabel ls=new JLabel();
                   cell.setBackground(new Color(dbs,true));
                   cell.setForeground(new Color(dbs,true));

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


        return cell;
    }
   }
© www.soinside.com 2019 - 2024. All rights reserved.