从数据库中获取数据和图像路径并将它们放入Jtable中

时间:2014-01-21 12:40:07

标签: java oracle swing

我试图在jtable中获取一些数据(点击按钮),在数据库中我有存储图像的路径。所以我想把它们放在JTable的单元格中。我的代码非常大,因为它包含一些其他信息,比如当我们在文本字段中提供正确的信息时,它只会从数据库中获取数据。

这个程序运行正常,没有错误,我只是想在表格的一列中插入照片。

  import java.awt.BorderLayout;
  import java.awt.FlowLayout;
  import java.awt.Font;
  import java.awt.event.ActionEvent;
  import java.awt.event.ActionListener;
  import java.sql.Connection;
  import java.sql.DriverManager;
  import java.sql.PreparedStatement;
  import java.sql.ResultSet;
  import java.sql.SQLException;

  import javax.swing.DefaultCellEditor;
  import javax.swing.JButton;
  import javax.swing.JCheckBox;
  import javax.swing.JFrame;
  import javax.swing.JLabel;
  import javax.swing.JOptionPane;
  import javax.swing.JPanel;
  import javax.swing.JScrollPane;
  import javax.swing.JTable;
  import javax.swing.JTextField;
  import javax.swing.UIManager;
  import javax.swing.UnsupportedLookAndFeelException;
  import javax.swing.table.DefaultTableModel;

  @SuppressWarnings("serial")
  public class VCstVote extends JFrame implements ActionListener{

   JFrame frame;
   JTextField tauid, tphone;
   JLabel label, auid, aphone;
   JButton cls, ok, vote;
   JCheckBox chkbx;
   JPanel panel,panel1,panel2, panel3;
   static JTable table,table2;
   DefaultTableModel model1 = new DefaultTableModel();

   VCstVote() throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException{
final UIManager.LookAndFeelInfo[] plafInfos =UIManager.getInstalledLookAndFeels();
UIManager.setLookAndFeel(plafInfos[1].getClassName() );

frame = new JFrame();
frame.setSize(930, 400);
frame.setTitle("VOTE YOUR CANDIDATE");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
vote = new JButton("VOTE YOUR CANDIDATE");

label = new JLabel("CASTE YOUR VOTE");
label.setFont(new Font("Verdana", Font.BOLD, 18));
panel.add(label);

panel1  = new JPanel();

cls= new JButton("CLOSE");

panel1.add(vote);
panel1.add(cls);

panel2 = new JPanel();

auid = new JLabel("UNIQUE ID",11);
tauid = new JTextField(10);
auid.setFont(new Font("Verdana", Font.BOLD, 10));
aphone = new JLabel("PHONE", 11);
aphone.setFont(new Font("Verdana", Font.BOLD, 10));
tphone = new JTextField(10);


ok = new JButton("SUBMIT");

panel2.add(auid);
panel2.add(tauid);
panel2.add(aphone);
panel2.add(tphone);

panel3 = new JPanel( new FlowLayout(FlowLayout.LEFT, 3,3));
panel3.add(ok);
panel2.add(panel3);

String[] columnNames = {"Candidate Name", "Department Name","Year","Photo","CASTE VOTE"};

model1.setColumnIdentifiers(columnNames);
table = new JTable();
table.setModel(model1); 
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setFillsViewportHeight(true);
JScrollPane scroll = new JScrollPane(table);

cls.addActionListener(this);
ok.addActionListener(this);
vote.addActionListener(this);

frame.add(scroll, BorderLayout.WEST);
frame.add(panel2,BorderLayout.EAST);
frame.add(panel,BorderLayout.NORTH);
frame.add(panel1,BorderLayout.SOUTH);

frame.validate();

frame.setVisible(true);
}
 public void actionPerformed(ActionEvent ae) {
  String action=ae.getActionCommand();
   Connection conn = null ;
    String cfn= null;
     String cln=null;
  if(action=="SUBMIT")
  {
    try {
         Class.forName("oracle.jdbc.driver.OracleDriver");
        conn = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:orcl", "scott","tiger");
        String query1="insert into vote (vuid,uphno) values(?,?)";
        String query2 = "select uphno from accounts where vuid='"+tauid.getText()+"'";
        String query3 = "select p.cfname, p.clname, p.deptname, l.dyear from potential p, leads l where p.cfname=l.cfname and p.clname=l.clname and p.deptname =l.deptname";
        String query4 = "Select a.ufname, a.ulname from vote v, accounts a where a.uphno=v.uphno and v.vuid='"+tauid.getText()+"'";
        chkbx = new JCheckBox();
        PreparedStatement ps1 = conn.prepareStatement(query1);
        PreparedStatement ps2 = conn.prepareStatement(query2);
        PreparedStatement ps3 = conn.prepareStatement(query3);
        PreparedStatement ps4 = conn.prepareStatement(query4);

        ResultSet rs2= null;
        ResultSet rs3= null;
        ResultSet rs4= null;

        rs2=ps2.executeQuery(); 
        while(rs2.next())
        {
            ps1.setString(1, tauid.getText());
            ps1.setString(2, rs2.getString(1));

            ps1.executeUpdate();
            conn.commit();
        }
        rs4= ps4.executeQuery();
        while(rs4.next())
        {
            cfn = rs4.getString(1);
            cln = rs4.getString(2);
        }

        JOptionPane.showMessageDialog(null, "Hii.. "+cfn+" "+cln+" Please Select Only one Candidate for voting, otherwise you vote will not be counted..");

        rs3= ps3.executeQuery();

        while(rs3.next())
        {
            String fname= rs3.getString(1);
            String lname= rs3.getString(2);
            String dept= rs3.getString(3);
            String year= rs3.getString(4);


            model1.addRow(new Object[]{fname+" "+lname,dept,year});
            table.getColumn("CASTE VOTE").setCellEditor(new DefaultCellEditor(chkbx));

        } 
        for (int i=0;i<model1.getRowCount();i++)
        {
         model1.setValueAt("false", i, 3);
        }
    }
    catch(SQLException e)
    {
        JOptionPane.showMessageDialog(null,"Please Enter correct information");
        e.printStackTrace();
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}

if(action=="VOTE YOUR CANDIDATE")
{
    try {
        Class.forName("oracle.jdbc.driver.OracleDriver");
        conn = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:orcl", "scott","tiger");

        String query1 ="select cfname,clname,deptname,luid from potential";
        String test = tphone.getText();
        String query2="update vote set cfname=?, clname=?, deptname=?, luid=?, votcount=1 where uphno="+test;
        ResultSet rs1 = null;

        PreparedStatement ps1= conn.prepareStatement(query1);
        PreparedStatement ps2 = conn.prepareStatement(query2);

           rs1 =ps1.executeQuery();

           for(int i=0;i<model1.getRowCount();i++)
           {    
              Object st = model1.getValueAt(i,3);
              String ss= st.toString();

              if(ss.equals("true"))
              {
                rs1.next();
                String fname = rs1.getString(1);
                String lname = rs1.getString(2);
                String dept = rs1.getString(3);
                String uid = rs1.getString(4);

                    ps2.setString(1, fname);
                    ps2.setString(2, lname);
                    ps2.setString(3, dept);
                    ps2.setString(4, uid);

                    ps2.executeUpdate();
                    conn.commit();
                    JOptionPane.showMessageDialog(null,"Successfully registred Your Vote");

              }
              else{
                  rs1.next();
              }

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

}

if(action=="CLOSE")
    {
      frame.setVisible(false);

    }
 }

 public static void main(String args[]) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException
  {
     try {
          UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
   }
   catch (UnsupportedLookAndFeelException ex) {
        ex.printStackTrace();
   } catch (IllegalAccessException ex) {
        ex.printStackTrace();
   } catch (InstantiationException ex) {
        ex.printStackTrace();
   } catch (ClassNotFoundException ex) {
    ex.printStackTrace();
   }
    new VCstVote();
 }

 }

请帮助我,我尝试了很多网站和代码,但似乎它们只适用于一组已定义的数据和图像,它们都没有代码表明jtable从数据库中获取数据并渲染图像。

1 个答案:

答案 0 :(得分:2)

  

我有存储图像的路径。所以我想把它们放进去   JTable的细胞。

修改

  

我尝试过这种类型的编码,但它却向我展示了这条路径   仅

  • 需要覆盖getColumnClassIcon / ImageIcon

        public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }
    
        //or 
    
        @Override
        public Class<?> getColumnClass(int colNum) {
            switch (colNum) {
                case 0:
                    return Integer.class;
                case 1:
                    return Double.class;
                case 2:
                    return Long.class;
                case 3:
                    return Boolean.class;
                case 4:
                    return String.class;
                case 5:
                    return Icon.class;
                /*case 6:
                return Double.class;
                case 7:
                return Double.class;
                case 8:
                return Double.class;*/
                default:
                    return String.class;
            }
        } 
    

e.g。在代码中使用

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.*;
import javax.swing.table.*;

public class TableIcon extends JFrame implements Runnable {

    private static final long serialVersionUID = 1L;
    private JTable table;
    private JLabel myLabel = new JLabel("waiting");
    private int pHeight = 40;
    private boolean runProcess = true;
    private int count = 0;

    public TableIcon() {
        ImageIcon errorIcon = (ImageIcon) UIManager.getIcon("OptionPane.errorIcon");
        ImageIcon infoIcon = (ImageIcon) UIManager.getIcon("OptionPane.informationIcon");
        ImageIcon warnIcon = (ImageIcon) UIManager.getIcon("OptionPane.warningIcon");
        String[] columnNames = {"Picture", "Description"};
        Object[][] data = {{errorIcon, "About"}, {infoIcon, "Add"}, {warnIcon, "Copy"},};
        DefaultTableModel model = new DefaultTableModel(data, columnNames) {

            private static final long serialVersionUID = 1L;
            //  Returning the Class of each column will allow different
            //  renderers to be used based on Class

            @Override
            public Class getColumnClass(int column) {
                return getValueAt(0, column).getClass();
            }
        };
        table = new JTable(model);
        table.setRowHeight(pHeight);
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane, BorderLayout.CENTER);
        myLabel.setPreferredSize(new Dimension(200, pHeight));
        myLabel.setHorizontalAlignment(SwingConstants.CENTER);
        add(myLabel, BorderLayout.SOUTH);
        new Thread(this).start();
    }

    public void run() {
        while (runProcess) {
            try {
                Thread.sleep(1250);
            } catch (Exception e) {
                e.printStackTrace();
            }
            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {
                    ImageIcon myIcon = (ImageIcon) table.getModel().getValueAt(count, 0);
                    String lbl = "JTable Row at :  " + count;
                    myLabel.setIcon(myIcon);
                    myLabel.setText(lbl);
                    count++;
                    if (count > 2) {
                        count = 0;
                    }
                }
            });
        }
    }

    public static void main(String[] args) {
        TableIcon frame = new TableIcon();
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.setLocation(150, 150);
        frame.pack();
        frame.setVisible(true);
    }
}