JTable

Résolu
infodevinette Messages postés 8 Date d'inscription lundi 21 janvier 2008 Statut Membre Dernière intervention 19 août 2008 - 7 juil. 2008 à 11:40
infodevinette Messages postés 8 Date d'inscription lundi 21 janvier 2008 Statut Membre Dernière intervention 19 août 2008 - 16 juil. 2008 à 10:16
 Bonjour,
je travaille actuellement avec les jtable et  je voudrais ajouter une colonne entre deux colonnes déja existantes. si quelqu'un peut m'aider, je suis preneuse. merci d'avance

<!-- / message -->

9 réponses

uhrand Messages postés 491 Date d'inscription samedi 20 mai 2006 Statut Membre Dernière intervention 15 juillet 2012 9
9 juil. 2008 à 11:19
package demo;
/*
 * TableReportDemo_2.java
 * This demo shows you how to customize the JTable print function.
 * As an example, we print a report header with two rows and a border,
 * and we print 4 tables on one page.
 */

import java.awt.*;
import java.awt.event.*;
import java.awt.print.*;
import javax.print.attribute.*;
import javax.swing.*;
import javax.swing.JTable.*;
import javax.swing.table.*;

public class TableReportDemo_2 extends JFrame implements ActionListener {

    private JTable table1,  table2,  table3,  table4;
    private JButton btPrint;

    public TableReportDemo_2() {
        super("TableReportDemo_2");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        btPrint = new JButton("Print...");
        add(btPrint, BorderLayout.SOUTH);
        btPrint.addActionListener(this);
        JPanel mainpanel = new JPanel();
        add(mainpanel, BorderLayout.CENTER);
        table1 = createTable("A");
        table2 = createTable("B");
        table3 = createTable("C");
        table4 = createTable("D");
        mainpanel.add(new JScrollPane(table1));
        mainpanel.add(new JScrollPane(table2));
        mainpanel.add(new JScrollPane(table3));
        mainpanel.add(new JScrollPane(table4));
        setSize(500, 600);
        setLocationRelativeTo(null);
    }

    public JTable createTable(String name) {
        String[] title = new String[]{"Title A", "Title B", "Title C", "Title D", "Title E"};
        String[][] data = new String[][]{};
        DefaultTableModel model = new DefaultTableModel(data, title);
        JTable table = new JTable(model) {

            @Override
            public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
                Component c = super.prepareRenderer(renderer, row, column);
                c.setBackground(Color.WHITE);                if (row 1 && column 1) {
                    c.setBackground(Color.BLUE);                } else if (row 2 && column 3) {
                    c.setBackground(Color.RED);
                }
                return c;
            }
        };
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        for (int i = 0; i < 5; i++) {
            model.addRow(new String[]{"Table_" + name + " " + String.valueOf(i), "", "", "", ""});
        }
        table.setPreferredScrollableViewportSize(new Dimension(400, 100));
        return table;
    }

    public void actionPerformed(final ActionEvent e1) {
        try {
            printJTable();
        } catch (PrinterException ex) {
            ex.printStackTrace();
        }
    }

    private void printJTable() throws PrinterException {
        // possibly prepare the table for printing here first
        // wrap in a try/finally so table can be restored even if something fails
        try {
            // fetch the printable
            Printable printable = new TableReport(table1, table2, table3, table4);
            PrinterJob job = PrinterJob.getPrinterJob();// fetch a PrinterJob
            job.setPrintable(printable);// set the Printable on the PrinterJob
            // create an attribute set to store attributes from the print dialog
            PrintRequestAttributeSet attr = new HashPrintRequestAttributeSet();
            // display a print dialog and record whether or not the user cancels it
            boolean printAccepted = job.printDialog(attr);
            if (printAccepted) {// if the user didn't cancel the dialog
                job.print(attr);// do the printing
            }
        } finally {
            // possibly restore the original table state here
        }
    }

    public static void main(final String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                new TableReportDemo_2().setVisible(true);
            }
        });
    }
}

class TableReport implements Printable {

    private Printable tablePrintable1,  tablePrintable2,  tablePrintable3,  tablePrintable4;
    private PageFormat pageFormatJTable1,  pageFormatJTable2,  pageFormatJTable3,  pageFormatJTable4;
    private PageFormat pageFormat;
    private int x1,  y1,  w1,  h1;

    public TableReport(final JTable table1, final JTable table2, final JTable table3, final JTable table4) {
        tablePrintable1 = table1.getPrintable(JTable.PrintMode.FIT_WIDTH, null, null);
        tablePrintable2 = table2.getPrintable(JTable.PrintMode.FIT_WIDTH, null, null);
        tablePrintable3 = table3.getPrintable(JTable.PrintMode.FIT_WIDTH, null, null);
        tablePrintable4 = table4.getPrintable(JTable.PrintMode.FIT_WIDTH, null, null);
    }

    public int print(final Graphics graphics, final PageFormat pageFormat,
            final int pageIndex) throws PrinterException {
        Graphics2D g = (Graphics2D) graphics;
        this.pageFormat = pageFormat;
        x1 = (int) pageFormat.getImageableX();
        y1 = (int) pageFormat.getImageableY();
        w1 = (int) pageFormat.getImageableWidth();
        h1 = (int) pageFormat.getImageableHeight();
        //print header/footer:
        String title = "Title";
        String subtitle = "Subtitle";
        Font f = g.getFont();
        g.setFont(g.getFont().deriveFont(15f));
        FontMetrics fm = g.getFontMetrics();
        g.drawString(title, x1 + (w1 - fm.stringWidth(title)) / 2, y1 + 15);
        g.setFont(f);
        fm = g.getFontMetrics();
        g.drawString(subtitle, x1 + (w1 - fm.stringWidth(subtitle)) / 2, y1 + 30);
        g.drawRect(x1, y1, w1, 40);
        String footer = "Page " + (pageIndex + 1);
        g.drawString(footer, x1 + (w1 - fm.stringWidth(footer)) / 2, y1 + h1 - 10);
        //print the tables:
        pageFormatJTable1 = getPageFormatJTable(60, 150, pageFormatJTable1);
        pageFormatJTable2 = getPageFormatJTable(210, 150, pageFormatJTable2);
        pageFormatJTable3 = getPageFormatJTable(360, 150, pageFormatJTable3);
        pageFormatJTable4 = getPageFormatJTable(510, 150, pageFormatJTable4);
        Graphics gCopy = g.create();
        tablePrintable1.print(gCopy, pageFormatJTable1, pageIndex);
        gCopy.dispose();
        gCopy = g.create();
        tablePrintable2.print(gCopy, pageFormatJTable2, pageIndex);
        gCopy.dispose();
        gCopy = g.create();
        tablePrintable3.print(gCopy, pageFormatJTable3, pageIndex);
        gCopy.dispose();
        gCopy = g.create();
        int retVal = tablePrintable4.print(gCopy, pageFormatJTable4, pageIndex);
        gCopy.dispose();
        return retVal;
    }

    private PageFormat getPageFormatJTable(int position, int height, PageFormat pageFormatJTable) {
        if (pageFormatJTable == null) {
            pageFormatJTable = (PageFormat) pageFormat.clone();
            Paper paperJTable = pageFormatJTable.getPaper();
            if (pageFormatJTable.getOrientation() == PageFormat.PORTRAIT) {
                paperJTable.setImageableArea(x1, y1 + position, w1, height);
            } else {
                paperJTable.setImageableArea(y1 + position, x1, height, w1);
            }
            pageFormatJTable.setPaper(paperJTable);
        }
        return pageFormatJTable;
    }
}
3
indiana_jules Messages postés 750 Date d'inscription mardi 9 mars 2004 Statut Membre Dernière intervention 23 décembre 2008 22
7 juil. 2008 à 13:31
Bonjour,
le TableModel qu'utilise par défaut la Jtable est plutôt du genre statique. Pour ce faire, il te suffit juste de redéfinir un TableModel (en utilisant un AbstractTableModel), où tu pourras rajouter une méthode d'ajout / de suppression de colonne (vu que ce sera là que ta matrice de données sera présente).

Voili voilà

le monde a des idées : la preuve, c'est qu'il y en a de mauvaises
ne comprends pas tout, mais je parle de tout : c'est ce qui compte
0
infodevinette Messages postés 8 Date d'inscription lundi 21 janvier 2008 Statut Membre Dernière intervention 19 août 2008
7 juil. 2008 à 16:28
 tu peux mettre un petit bout de code pour voir comment on fait?
0
uhrand Messages postés 491 Date d'inscription samedi 20 mai 2006 Statut Membre Dernière intervention 15 juillet 2012 9
7 juil. 2008 à 17:14
Tu peus essayer ceci:

DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
tableModel.addColumn("Test");
table.getColumnModel().moveColumn(table.getColumnCount() - 1, 1);
0

Vous n’avez pas trouvé la réponse que vous recherchez ?

Posez votre question
infodevinette Messages postés 8 Date d'inscription lundi 21 janvier 2008 Statut Membre Dernière intervention 19 août 2008
8 juil. 2008 à 15:40
oui, Ca marche et j'évite l'AbstractTableModel  et pour la suppression y pas un truc simple aussi?
0
uhrand Messages postés 491 Date d'inscription samedi 20 mai 2006 Statut Membre Dernière intervention 15 juillet 2012 9
8 juil. 2008 à 17:00
table.getColumnModel().removeColumn(table.getColumn("Test"));
0
infodevinette Messages postés 8 Date d'inscription lundi 21 janvier 2008 Statut Membre Dernière intervention 19 août 2008
9 juil. 2008 à 09:14
merci beaucoup, j'ai deux autres petites questions la premiere , C'est que je veux imprimer 4 tables dans la meme page j'ai fait :
table.print()
table1.print()
....
et ca imprime chaque table dans une page.
et la seconde est que je voudrais colorer le fond de quelques cellules de differentes couleurs, merci d'avance.
0
infodevinette Messages postés 8 Date d'inscription lundi 21 janvier 2008 Statut Membre Dernière intervention 19 août 2008
9 juil. 2008 à 11:18
pour la coloration de la table:
j'ai crée la classe:
public class MyDefaultCellRenderer extends DefaultTableCellRenderer {


   
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
  
  
                if( value instanceof JLabel ) {
   return (JLabel) value;
  }
  return new JTextField(value.toString());
            
  }


puis dans mon autre classe, j'ai ajouter:


JLabel cellule = new JLabel();
   cellule.setText("Test");
  cellule.setBackground(Color.green);


et je sais pas comment ajouter le JLabel a la case par exemple 1,1??
0
infodevinette Messages postés 8 Date d'inscription lundi 21 janvier 2008 Statut Membre Dernière intervention 19 août 2008
16 juil. 2008 à 10:16
désolé pour le retard, merci beaucoup C exactement ce qui me fallait.
0
Rejoignez-nous