IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Composants Java Discussion :

Comment faire pour modifier une JTable


Sujet :

Composants Java

  1. #1
    Membre à l'essai
    Homme Profil pro
    Inscrit en
    Janvier 2007
    Messages
    13
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Janvier 2007
    Messages : 13
    Points : 11
    Points
    11
    Par défaut Comment faire pour modifier une JTable
    Bonjour à tous,

    J'ai commencé à développer un petit projet :
    Nom : MonAppli.jpg
Affichages : 97
Taille : 9,6 Ko
    -> StartBleed contient la méthode main
    -> MainApplicationWindow est une JFrame contenant une table héritée de DataFileTableModel ainsi qu'une JToolBar héritée de MainToolBar
    -> MainToolBar gère les événements (clics sur les boutons)

    A partir des événements, je souhaiterais ajouter ou modifier des lignes dans ma table.
    En revanche, cette dernière ne me semble pas visible depuis la class MainToolBar.

    Quelqu'un pourrait-il m'expliquer ce que je dois faire pour rendre cette dernière visible et modifiable ?

    Merci d'avance

    Jerome

  2. #2
    Expert éminent sénior
    Avatar de Baptiste Wicht
    Homme Profil pro
    Étudiant
    Inscrit en
    Octobre 2005
    Messages
    7 431
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 36
    Localisation : Suisse

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Octobre 2005
    Messages : 7 431
    Points : 21 324
    Points
    21 324
    Par défaut
    Il faut juste que dans MainApplicationWindow, tu fasses une méthode qui permette de récupérer la JTable, un getTable() par exemple. Et ensuite, dans ton MainToolBar, il te suffira d'appeller cette méthode pour récupérer l'objet.

  3. #3
    Membre à l'essai
    Homme Profil pro
    Inscrit en
    Janvier 2007
    Messages
    13
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Janvier 2007
    Messages : 13
    Points : 11
    Points
    11
    Par défaut
    Salut,

    J'avoue mon ignorance, je ne vois pas comment faire...

    Je comprends bien la méthode d'ajouter un :
    public JTable getTable() dans mon code de MainApplicationWindow

    En revanche, je ne vois pas comment je dois faire pour l'appeler depuis MainToolBar...
    En général, je fais un "Objet".getTable() mais quel objet dois-je utiliser ?

    Je suis désolé de poser une question qui dois vous paraitre si basique...

    Ci-dessous, le code des 2 classes concernées.

    Un grand merci

    Jerome

    MainApplicationWindow:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    public class MainApplicationWindow extends JPanel {
    	private static final long serialVersionUID = 1L;
    	public JTable table; // le tableau
     
    	public MainApplicationWindow(String dataFilePath) {
    		DataFileTableModel model; // le modèle
    		// fonte
    		Font f = new Font("SanSerif", Font.PLAIN, 24);
    		setFont(f);
    		// gestionnaire de positionnement
    		setLayout(new BorderLayout());
    		// construction du modèle de remplissage à partir du fichier
    		model = new DataFileTableModel(dataFilePath);
    		// création du tableau
    		table = new JTable();
    		table.setModel(model);
    		table.createDefaultColumnsFromModel();
    		// scroller
    		JScrollPane scrollpane = new JScrollPane(table);
    		add(scrollpane, BorderLayout.CENTER);
    		// Barre d'outil
    		MainToolBar myBar = new MainToolBar("Main ToolBar", table);
    		add(myBar, BorderLayout.PAGE_START);
    	}
     
    	public Dimension getPreferredSize() {
    		return new Dimension(500, 400);
    	}
    }
    et MainToolBar:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
     
    public class MainToolBar extends JToolBar implements ActionListener {
    	private static final long serialVersionUID = 1L;
    	private final String ADD_ACTION = "Add";
    	private final String DEL_ACTION = "Del";
    	private final String MOD_ACTION = "Mod";
    	private final String SAV_ACTION = "Sav";
    	private final String CAL_ACTION = "Cal";
    	private final String OPT_ACTION = "Opt";
    	private final Calendar calendar = new GregorianCalendar();
    	private final Date todayDate = new Date();
     
     
    	public MainToolBar(String MTBTitle, JTable maTable) {
    		calendar.setTime(todayDate);
    		this.setName(MTBTitle);
    		this.setFloatable(false);
    		addButtons(this);	
    	}
     
    	protected JButton makeNavigationButton(Icon icon,
    				String actionCommand, String toolTipText, String altText, String modeIcon) {
    		// Create and initialize the button.
    		JButton button = new JButton();
    		button.setToolTipText(toolTipText);
    		button.setActionCommand(actionCommand);
    		button.addActionListener(this);
     
    		if (modeIcon.equals("Icon")) { // ImageIcon found
    			button.setIcon(icon);
    		} else { // no ImageIcon found
    			button.setText(altText);
    			System.err.println("Button image not found for:" + altText);
    		}
    		return button;
    	}
     
    	protected void addButtons(MainToolBar myBar) {
    		final String path = "U:/Java Workspaces/Icons/";
    		String modeIcon = "Icon";
    		File fichier1 = new File(path + "New.gif");
    	    if (!fichier1.exists()) {  modeIcon = "Text";}
    	    File fichier2 = new File(path + "Delete.gif");
    	    if (!fichier2.exists()) {  modeIcon = "Text";}
    	    File fichier3 = new File(path + "Modify.gif");
    	    if (!fichier3.exists()) {  modeIcon = "Text";}
    	    File fichier4 = new File(path + "Save.gif");
    	    if (!fichier4.exists()) {  modeIcon = "Text";}
    	    File fichier5 = new File(path + "Calculate.gif");
    	    if (!fichier5.exists()) {  modeIcon = "Text";}
    	    File fichier6 = new File(path + "Option.gif");
    	    if (!fichier6.exists()) {  modeIcon = "Text";}
     
    		final Icon[] faces = { new ImageIcon(path + "New.gif"),
    				new ImageIcon(path + "Delete.gif"),
    				new ImageIcon(path + "Modify.gif"),
    				new ImageIcon(path + "Save.gif"),
    				new ImageIcon(path + "Calculate.gif"),
    				new ImageIcon(path + "Option.gif") };
     
    		JButton button = null;
     
    		// "ADD" Button
    		button = makeNavigationButton(faces[0], ADD_ACTION, "Add a new task",
    				"Add",modeIcon);
    		myBar.add(button);
     
    		// "MOD" Button
    		button = makeNavigationButton(faces[2], MOD_ACTION,
    				"Modify the selected task", "Modify",modeIcon);
    		myBar.add(button);
     
    		// "DEL" Button
    		button = makeNavigationButton(faces[1], DEL_ACTION,
    				"Delete the selected task", "Delete",modeIcon);
    		myBar.add(button);
     
    		// "Save" Button
    		button = makeNavigationButton(faces[3], SAV_ACTION,
    				"Save the task list", "Save",modeIcon);
    		myBar.add(button);
     
    		// "DEL" Button
    		button = makeNavigationButton(faces[4], CAL_ACTION,
    				"Calculate priority", "Calculate",modeIcon);
    		myBar.add(button);
     
    		// Ajout d'un séparateur
    		myBar.addSeparator();
     
    		// "OPT" Button
    		button = makeNavigationButton(faces[5], OPT_ACTION, "Manage options",
    				"Option",modeIcon);
    		myBar.add(button);
    	}
     
    	public void actionPerformed(ActionEvent actionRequested) {
    		// On a cliqué sur ADD
    		if (actionRequested.getActionCommand().equals(this.ADD_ACTION) )
    		{
    			TaskWindow panneau = new TaskWindow();
    			panneau.setCreda(calendar.get(Calendar.DATE) + "/" +
    					(calendar.get(Calendar.MONTH) + 1) + "/" +
    					calendar.get(Calendar.YEAR));
     
    			int reponse = JOptionPane.showConfirmDialog(null, panneau,
    		                       "Contact", JOptionPane.OK_CANCEL_OPTION,
    		                       JOptionPane.PLAIN_MESSAGE);
    		    if (reponse == JOptionPane.OK_OPTION)
    		    	System.out.println("Mettre à jour la table en créant une nouvelle ligne");
    		}
    		// On a cliqué sur MOD
    		else if (actionRequested.getActionCommand().equals(this.MOD_ACTION) )
    		{
    			System.out.println("Modifiation d'une ligne");
    		}
    		// On a cliqué sur DEL
    		else if (actionRequested.getActionCommand().equals(this.DEL_ACTION) )
    		{
    			System.out.println("suppression d'une ligne");
    		}
    		// On a cliqué sur CAL
    		else if (actionRequested.getActionCommand().equals(this.CAL_ACTION) )
    		{
    			System.out.println("Calcul de la liste");
    		}
    		//		 On a cliqué sur SAV
    		else if (actionRequested.getActionCommand().equals(this.SAV_ACTION) )
    		{
    			System.out.println("Sauvegarde de la liste");
    		}
    		// On a cliqué sur OPT
    		else if (actionRequested.getActionCommand().equals(this.OPT_ACTION) )
    		{
    			System.out.println("Gestion des options");
    		}
    	}
    }

  4. #4
    Expert éminent sénior
    Avatar de Baptiste Wicht
    Homme Profil pro
    Étudiant
    Inscrit en
    Octobre 2005
    Messages
    7 431
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 36
    Localisation : Suisse

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Octobre 2005
    Messages : 7 431
    Points : 21 324
    Points
    21 324
    Par défaut
    En fait, c'est beaucoup plus simple, puisque tu passes déja ta JTable au constructeur de MainToolBar...

    Il faut que tu modifies ton constructeur de la manière suivante :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     
    private JTable table = null;
     
    public MainToolBar(String MTBTitle, JTable maTable) {
    	calendar.setTime(todayDate);
    	this.setName(MTBTitle);
    	this.setFloatable(false);
    	addButtons(this);	
    	this.table = maTable;
    }
    Comme ça, tu peux utiliser table dans ta classe MainToolBar

  5. #5
    Membre à l'essai
    Homme Profil pro
    Inscrit en
    Janvier 2007
    Messages
    13
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Janvier 2007
    Messages : 13
    Points : 11
    Points
    11
    Par défaut
    Super mais j'ai une toute dernière question,

    Comment notifier à ma table que les données ont changées et que la table doit-être mise à jour?

    J'ai essayé this.table.getModel().fireTableStructureChanged() mais ça ne fonctionne pas!

    Merci


  6. #6
    Expert éminent sénior
    Avatar de Baptiste Wicht
    Homme Profil pro
    Étudiant
    Inscrit en
    Octobre 2005
    Messages
    7 431
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 36
    Localisation : Suisse

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Octobre 2005
    Messages : 7 431
    Points : 21 324
    Points
    21 324
    Par défaut
    Utilise fireTableDataChanged() pour indiquer que les données ont changé

Discussions similaires

  1. Comment faire pour modifier une ligne dans une DBGrid?
    Par Nico62 dans le forum C++Builder
    Réponses: 6
    Dernier message: 29/03/2005, 12h24
  2. Comment faire pour récup une donnée d'une liste déroulante
    Par magic8392 dans le forum Général JavaScript
    Réponses: 8
    Dernier message: 03/03/2005, 15h00
  3. Comment faire pour afficher une image ds une dbgrid
    Par totomaze dans le forum Bases de données
    Réponses: 2
    Dernier message: 16/10/2004, 15h31
  4. Comment faire pour killer une application ?
    Par tintin22 dans le forum API, COM et SDKs
    Réponses: 4
    Dernier message: 17/08/2004, 18h16
  5. comment faire pour qu'une application soit toujours visible ?
    Par goldbar dans le forum Langages de programmation
    Réponses: 2
    Dernier message: 28/03/2004, 14h35

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo