如何将jbutton放入数组以在jtable中逐行上传图像?

时间:2018-08-03 06:49:51

标签: java swing jtable jbutton

我的图像上传功能完全可以使用。但是我不能逐行上传图像。目前,当我上传图片时,它将添加到整个第5列中。如何将按钮放入数组并逐行上传图像?

**注意:按钮用作文件上传器。

这是图片

enter image description here

这是代码:

NewFrame.java

package test4;

import java.awt.Color;
import java.awt.Component;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.swing.DefaultCellEditor;
import javax.swing.DefaultListCellRenderer;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.ListCellRenderer;
import javax.swing.UIManager;
import javax.swing.filechooser.FileSystemView;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;


public class NewJFrame extends javax.swing.JFrame {

   static String fileoriginal="C:/Users/Praneeth Thisal/Documents/NetBeansProjects/Copyfile/src/copyfile/";

    public NewJFrame() {
        initComponents();
        tablemodel();
    }
void tablemodel(){
    Color choices[] = { Color.red, Color.yellow, Color.green, Color.white, Color.orange };
    ComboTableCellRenderer renderer = new ComboTableCellRenderer();
    JComboBox comboBox = new JComboBox(choices);
    comboBox.setRenderer(renderer);

    TableCellEditor editor = new DefaultCellEditor(comboBox);

    TableModel model = new ColorTableModel();
    jTable1.setModel(model);
    TableColumn column = jTable1.getColumnModel().getColumn(5);
    column.setCellRenderer(renderer);
    column.setCellEditor(editor);
    TableColumn column1 = jTable1.getColumnModel().getColumn(3);
    column1.setCellRenderer(new ButtonRenderer());
    TableColumn column2 = jTable1.getColumnModel().getColumn(4);
    column2.setCellRenderer(new ImageRenderer());

     column1.setCellEditor(
        new ButtonEditor(new JCheckBox()));
jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
jTable1.getColumnModel().getColumn(0).setPreferredWidth(27);
jTable1.getColumnModel().getColumn(1).setPreferredWidth(120);
jTable1.getColumnModel().getColumn(2).setPreferredWidth(100);
jTable1.getColumnModel().getColumn(3).setPreferredWidth(90);
jTable1.getColumnModel().getColumn(4).setPreferredWidth(90);

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

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jTable1.setModel(new javax.swing.table.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}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4", "Title 5", "Title 6"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(25, 160, 730, 275));

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-795)/2, (screenSize.height-651)/2, 795, 651);
    }// </editor-fold>                        

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }

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

}

class ImageRenderer extends DefaultTableCellRenderer  {
  JLabel lbl = new JLabel();

  ImageIcon icon = new ImageIcon(new ImageIcon(NewJFrame.fileoriginal+"test.jpg").getImage().getScaledInstance(40, 40, Image.SCALE_DEFAULT));

  public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
      boolean hasFocus, int row, int column) {
    lbl.setText((String) value);
    lbl.setIcon(icon);
    return lbl;
  }
}

class ButtonRenderer extends JButton implements TableCellRenderer {

  public ButtonRenderer() {
    setOpaque(true);

  }

  public Component getTableCellRendererComponent(JTable table, Object value,
      boolean isSelected, boolean hasFocus, int row, int column) {
      value="Upload";

      if (isSelected) {
      setForeground(table.getSelectionForeground());
      setBackground(table.getSelectionBackground());
    } else {
      setForeground(table.getForeground());
      setBackground(UIManager.getColor("Button.background"));
     // setText("dsda1");
    }
    setText((value == null) ? "" : value.toString());
    return this;
  }
}

/**
 * @version 1.0 11/09/98
 */

class ButtonEditor extends DefaultCellEditor {
  protected JButton button;

  private String label;

  private boolean isPushed;

  public ButtonEditor(JCheckBox checkBox) {
    super(checkBox);
    button = new JButton();
    button.setOpaque(true);
    button.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        fireEditingStopped();
      }
    });
  }

  public Component getTableCellEditorComponent(JTable table, Object value,
      boolean isSelected, int row, int column) {

    if (isSelected) {
      button.setForeground(table.getSelectionForeground());
      button.setBackground(table.getSelectionBackground());


    } else {
      button.setForeground(table.getForeground());
      button.setBackground(table.getBackground());

    }
   label = (value == null) ? "" : value.toString();
    //label="DDD";
    button.setText("Upload");

    isPushed = true;
    return button;
  }

  public Object getCellEditorValue() {
    if (isPushed) {
      //
      JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());

        int returnValue = jfc.showOpenDialog(null);
        // int returnValue = jfc.showSaveDialog(null);

        if (returnValue == JFileChooser.APPROVE_OPTION) {
            File selectedFile = jfc.getSelectedFile();
            System.out.println(selectedFile.getAbsolutePath());
                        File source = new File(selectedFile.getAbsolutePath());

           try{
               NewJFrame.fileoriginal="C:/Users/Praneeth Thisal/Documents/NetBeansProjects/Copyfile/src/copyfile/";
            copyFileUsingStream(source, new File(NewJFrame.fileoriginal+"test"+".jpg"));
            System.out.println("Done");
           NewJFrame nf = new NewJFrame();
           nf.setVisible(true);
        }
        catch(IOException e){
            e.printStackTrace();
        }

        }

    //  JOptionPane.showMessageDialog(button, label + ": Ouch!");
       System.out.println(label + "Uploaded Successfully!!");


    }
    isPushed = false;
    return new String(label);
  }

  private static void copyFileUsingStream(File source, File dest) throws IOException {
    InputStream is = null;
    OutputStream os = null;
    try {
        is = new FileInputStream(source);
        os = new FileOutputStream(dest);
        byte[] buffer = new byte[1024];
        int length;
        while ((length = is.read(buffer)) > 0) {
            os.write(buffer, 0, length);
        }
    } finally {
        is.close();
        os.close();
    }
}


  public boolean stopCellEditing() {
    isPushed = false;
    return super.stopCellEditing();
  }

  protected void fireEditingStopped() {
    super.fireEditingStopped();
  }
}

ComboTableCellRenderer.java

package test4;


import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;

import javax.swing.DefaultCellEditor;
import javax.swing.DefaultListCellRenderer;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListCellRenderer;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;

class ComboTableCellRenderer implements ListCellRenderer, TableCellRenderer {
  DefaultListCellRenderer listRenderer = new DefaultListCellRenderer();

  DefaultTableCellRenderer tableRenderer = new DefaultTableCellRenderer();

  private void configureRenderer(JLabel renderer, Object value) {
    if ((value != null) && (value instanceof Color)) {
      if (value.equals(Color.red)) {
            renderer.setText("0");
        } else if(value.equals(Color.orange)) {
            renderer.setText("10");
        }
      else if(value.equals(Color.yellow)) {
            renderer.setText("20");
        }
      else if(value.equals(Color.green)) {
            renderer.setText("30");
        }
      else if(value.equals(Color.white)) {
            renderer.setText("N/A");
        }
      renderer.setBackground((Color)value);
    } else {
      renderer.setText((String) value);
    }
  }

  public Component getListCellRendererComponent(JList list, Object value, int index,
      boolean isSelected, boolean cellHasFocus) {
    listRenderer = (DefaultListCellRenderer) listRenderer.getListCellRendererComponent(list, value,
        index, isSelected, cellHasFocus);
    configureRenderer(listRenderer, value);
    return listRenderer;
  }

  public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
      boolean hasFocus, int row, int column) {
    tableRenderer = (DefaultTableCellRenderer) tableRenderer.getTableCellRendererComponent(table,
        value, isSelected, hasFocus, row, column);
    configureRenderer(tableRenderer, value);
    return tableRenderer;
  }
}

class ColorTableModel extends AbstractTableModel {

  Object rowData[][] = {
      { "1","","","","", Color.red, "30" },
      { "2","","","","", Color.red, "30" },
      { "3","","","","", Color.red, "30" },
      { "4","","","","", Color.red, "30" },
      { "5","","","","", Color.red, "30" }, };

  String columnNames[] = { "Index","Item","Reason","Image","Image 1","Marks","Allocated Marks" };

  public int getColumnCount() {
    return columnNames.length;
  }

  public String getColumnName(int column) {
    return columnNames[column];
  }

  public int getRowCount() {
    return rowData.length;
  }

  public Object getValueAt(int row, int column) {
    return rowData[row][column];
  }

  public Class getColumnClass(int column) {
    return (getValueAt(0, column).getClass());
  }

  public void setValueAt(Object value, int row, int column) {
    rowData[row][column] = value;
  }

  public boolean isCellEditable(int row, int column) {
    return (column != 0);
  }
}

0 个答案:

没有答案