rss
Rechercher : dans
Par : Pertinence Date Nom d'utilisateur
Statut : Non résolu

[Java]Afficher une colonne d'une JTable

Posté par Gwen, le vendredi 22 décembre 2006 à 23:16:12
Bonjour,

je voudrais savoir quelle classe il faut implémenter/hériter pour pouvoir choisir la colonne de la JTable que je veux voir.
Par exemple, admettons que ma JTable contient les colonnes :
colonne 1, colonne 2, colonne 3
J'ai un menu qui permet de choisir entre colonne 1, colonne 2, colonne 3, tous (tous permet de retrouver le tableau complet).
Comment faire pour que si je selectionne colonne 1, seule la colonne 1 de ma JTable s'affiche, si je selectionne colonne 2, seul la colonne 2 de la JTable s'affiche et si je selectionne tous, le tableau contient toutes les colonnes

Merci
Répondre à Gwen  Signaler ce message aux modérateurs Aller au dernier message

1


  • Ce message vous semble utile, votez !
  • Signaler ce message aux modérateurs
HackTrack, le lundi 22 janvier 2007 à 16:54:06
Salut Gwen!

Tu trouveras ci-dessous la solution à ton problème.

J'ai tout intégré dans une seule classe (exemple à ne pas suivre ;-) ) afin que tu aies plus facile de tester cette petite démo.

Je te laisse le soin de "refactorer" cette classe en la scindant en plusieurs classes. Bon exercice çà! ;-)

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.util.Enumeration;

import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

/**
 * Simple demo of JButtons used to hide/display JTable columns
 * 
 * @created on 22/01/2007
 * @author: HackTrack
 */

public class TableColumnTester extends JFrame {
	private Container c;

	private int width;

	private int height;

	public TableColumnTester() {
		super("Table column select");
		initialize();
		this.width = 400;
		this.height = 200;
	}

	private void initialize() {
		c = getContentPane();
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setLayout(new BorderLayout());

		// Generating JTable with data and column headers
		Object[] columnNames = { "Colonne 1", "Colonne 2", "Colonne 3" };
		Object[][] data = { { "a", "b", "c" }, { "a", "b", "c" }, { "a", "b", "c" }, { "a", "b", "c" }, { "a", "b", "c" },
				{ "a", "b", "c" }, { "a", "b", "c" }, { "a", "b", "c" }, { "a", "b", "c" }, { "a", "b", "c" }, { "a", "b", "c" },
				{ "a", "b", "c" }, { "a", "b", "c" }, { "a", "b", "c" }, { "a", "b", "c" }, { "a", "b", "c" }, { "a", "b", "c" },
				{ "a", "b", "c" }, { "a", "b", "c" }, { "a", "b", "c" }, { "a", "b", "c" } };
		JTable table = new JTable(data, columnNames) {
			public Component prepareRenderer(TableCellRenderer renderer, int row, int col) {
				Component c = super.prepareRenderer(renderer, row, col);
				Color color = getBackground();
				if (row % 2 == 0 && !isCellSelected(row, col)) {
					color = new Color(240, 240, 240);
				}
				c.setBackground(color);

				return c;
			}
		};

		/*
		 * MyCellRenderer cellRenderer = new MyCellRenderer(); Enumeration e =
		 * table.getColumnModel().getColumns(); while (e.hasMoreElements()) {
		 * TableColumn col = (TableColumn) e.nextElement();
		 * col.setCellRenderer(cellRenderer); }
		 */
		// Button panel
		JPanel jp_buttons = new JPanel();
		jp_buttons.setLayout(new GridLayout(1, 4));
		jp_buttons.setPreferredSize(new Dimension(width, 60));
		jp_buttons.setBorder(BorderFactory.createTitledBorder(&quo­t;Choose columns to display"));

		// Buutons and button group
		ButtonGroup bg_buttons = new ButtonGroup();
		JRadioButton jrb_col1 = new JRadioButton(new ShowColumnAction("Show column 1", new int[] { 0 }, table));
		bg_buttons.add(jrb_col1);
		jp_buttons.add(jrb_col1);

		JRadioButton jrb_col2 = new JRadioButton(new ShowColumnAction("Show column 2", new int[] { 1 }, table));
		bg_buttons.add(jrb_col2);
		jp_buttons.add(jrb_col2);

		JRadioButton jrb_col3 = new JRadioButton(new ShowColumnAction("Show column 3", new int[] { 2 }, table));
		bg_buttons.add(jrb_col3);
		jp_buttons.add(jrb_col3);

		JRadioButton jrb_colAll = new JRadioButton(new ShowColumnAction("Show all columns", new int[] { 0, 1, 2 }, table));
		bg_buttons.add(jrb_colAll);
		jp_buttons.add(jrb_colAll);

		c.add(jp_buttons, BorderLayout.NORTH);

		// Table panel
		JPanel jp_table = new JPanel();
		jp_table.setPreferredSize(new Dimension(640, 300));
		JScrollPane jsp = new JScrollPane(table);
		jsp.setPreferredSize(new Dimension(640, 300));
		jp_table.add(jsp);
		c.add(jsp, BorderLayout.CENTER);

		// Select all columns
		jrb_colAll.doClick();
	}

	class MyCellRenderer implements TableCellRenderer {
		Color bgColor;

		public MyCellRenderer() {
			super();
		}

		public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
			bgColor = Color.RED;
			if (row % 2 == 1)
				bgColor = Color.WHITE;

			Rectangle rect = table.getCellRect(row, column, true);

			JLabel label = new JLabel((String) value);
			label.setBackground(bgColor);
			return label;
		}
	}

	class ShowColumnAction extends AbstractAction {
		private int[] columnsToShow;

		private TableColumnModel tcm;

		private TableColumn[] columns;

		private JTable table;

		private String label;

		/**
		 * 
		 * @param label
		 *            The button description to display
		 * @param columnsToShow
		 *            An array of int with indexes of columns to dsiplay
		 *            (zero-based)
		 * @param table
		 *            The data table
		 */
		public ShowColumnAction(String label, int columnsToShow[], JTable table) {
			super(label);
			this.label = label;
			this.columnsToShow = columnsToShow;
			this.table = table;
			this.tcm = this.table.getColumnModel();

			this.columns = new TableColumn[table.getColumnCount()];

			for (int i = 0; i < columns.length; i++) {
				this.columns[i] = table.getColumnModel().getColumn(i);
			}
		}

		public void actionPerformed(ActionEvent e) {
			TableColumn tc;

			int colIndex;
			// Loop to remove all columns from table
			for (colIndex = 0; colIndex < columns.length; colIndex++) {
				tcm.removeColumn(columns[colIndex]);
			}

			// Loop on all columns
			for (colIndex = 0; colIndex < columns.length; colIndex++) {
				// For each column to show which index is stored in the
				// columnsToShow array
				for (int i = 0; i < columnsToShow.length; i++) {
					// If column index is the same as the index from the array
					// ...
					if (columnsToShow[i] == colIndex) {
						// ... get the column
						tc = columns[colIndex];
						// ... and add it to the table
						tcm.addColumn(tc);
					}

				}
			}
		}
	}

	public static void main(String[] args) {
		TableColumnTester tester = new TableColumnTester();
		tester.pack();
		tester.setVisible(true);
	}
}


;-)
Répondre à HackTrack

2


  • Ce message vous semble utile, votez !
  • Signaler ce message aux modérateurs
 pit, le lundi 29 janvier 2007 à 23:34:48
Répondre à pit
Logiciels pertinents trouvés dans les téléchargements
Télécharger Java Runtime Environment 6 Update 7Java Runtime Environment - Java Runtime Environment (JRE) installe la machine virtuelle Java, permettant de jouer en ligne, de discuter avec des...Catégorie: Java
Licence: Open Source
Télécharger Download Statusbar 0.9.4.5.1Download Statusbar - Cette extension remplace la fenêtre de téléchargement de Firefox par une discrète barre en bas de l'écran. En laissant le...Catégorie: Extensions Firefox
Licence: Freeware/gratuit
Télécharger FreeMind 0.8.1FreeMind - FreeMind est un logiciel de Mind mapping entièrement libre, permettant de créer des cartes heuristiques permettant de...Catégorie: Organisation
Licence: Open Source
Télécharger Web Developer Toolbar 1.1.6Web Developer Toolbar - WebDeveloper est une extension firefox représentant une formidable boîte à outils pour examiner et manipuler les pages...Catégorie: Extensions Firefox
Licence: Freeware/gratuit
Plus de logiciels gratuits sur « [Java]Afficher une colonne d'une JTable »