Utilisation JRadioButton dans application java

Résolu/Fermé
Seifou43 - 2 juil. 2020 à 17:35
Seifou43 Messages postés 7 Date d'inscription jeudi 2 juillet 2020 Statut Membre Dernière intervention 15 août 2020 - 10 août 2020 à 16:10
Bonjour,

j'utilise la methode scanner pour parser un fichier texte , dans mon code cité ci-dessous

j'ai introduis deux RadioButton pour pouvoir parser deux fichier dans mon bureau et faire le

traitement nécessaire .

le code ci-dessous ne marche pas quand je fait l'exécution .

j'ai besoin d'aide pour faire améliorer ce bout de code .




public void actionPerformed(ActionEvent e) {

if ( CPV1.isSelected()) {

Try (Scanner ST = new Scanner(new File("C:\\fichier.txt"))) {

ST.useDelimiter("DT");

while (ST.hasNextLine()) {
String data = ST.next();

Matcher matcher = Pattern.compile(reg1).matcher(DT);

while (matcher.find()) {


// le traitement de mon code //


}
}


if ( CPV2.isSelected()) {

Try (Scanner ST = new Scanner(new File("C:\\fichier2.txt"))) {

ST.useDelimiter("DT");

while (ST.hasNextLine()) {
String data = ST.next();

Matcher matcher1 = Pattern.compile(reg2).matcher(DT);

while (matcher1.find()) {

// le traitement de mon code //
.
.
.
.
.

ST.close();


} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}


}


});
.



Merci pour votre aide et support

Configuration: Windows / Chrome 83.0.4103.116
A voir également:

18 réponses

salut :

j'ai besoin de savoir est ce que le bout de code que j'ai mis est correcte pour commencer le

développement de mon application ?

merci pour votre suggestion et support
0
Tech43 Messages postés 8 Date d'inscription mardi 7 juillet 2020 Statut Membre Dernière intervention 16 juillet 2020
14 juil. 2020 à 21:05
salut :

j'ai trouvé une réponse qui m'a aidé à changer le début de mon code en utilisant JFileChooser, ci-dessous le lien du code :

https://forums.commentcamarche.net/forum/affich-27338461-choisir-un-fichier


mais j'ai pas trouvé une solution comment faire utilisés les radiobuttons .

voici le nouveau code corrigé :

		JButton btnrun = new JButton("RUN");
		btnAzzi.setFont(new Font("Tahoma", Font.BOLD, 12));
		
		final JFileChooser chooser = new JFileChooser();
		chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		chooser.setMultiSelectionEnabled(false);
		
		ButtonGroup group = new ButtonGroup();
		group.add(CPV1);
		group.add(CPV2);
		
		btnrun.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e) {

  if (CPV1.isSelected()) {

if (chooser.showOpenDialog(null)==JFileChooser.APPROVE_OPTION)
				{
				    File file = chooser.getSelectedFile();
				    Scanner ST = null;
					try {
						ST = new Scanner(file);
						
						     ST.useDelimiter("DT");
					
				while (ST.hasNextLine()) {
					String data = ST.next(); 

             Matcher matcher1 = Pattern.compile(reg2).matcher(DT);

						while (matcher1.find()) {  
						
						// processing data 
						
						.
						.
					  }
             }
             
             if ( CPV2.isSelected()) {         
                        
              ST.useDelimiter("DT");
					
				while (ST.hasNextLine()) {
					String data = ST.next(); 

             Matcher matcher2 = Pattern.compile(reg2).matcher(DT);

						while (matcher2.find()) {      

                 //   processing data   //
                    .
                 
             ST.close();	


merci pour votre aide et support
0
KX Messages postés 16733 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 31 janvier 2024 3 015
15 juil. 2020 à 11:31
Bonjour,

Il faudrait un code complet, que l'on puisse copier-coller, compiler, exécuter et tester afin de modifier ton programme et te donner la réponse la plus pertinente possible.
0
Tech43 Messages postés 8 Date d'inscription mardi 7 juillet 2020 Statut Membre Dernière intervention 16 juillet 2020
16 juil. 2020 à 13:07
salut KX :

merci beaucoup pour votre réponse :

j'ai deux fichier différent et j'essaye de les parcourir par différent pattern , l'idée que j'ai trouver dans l'URL de l'utilisation du JFileChooser m'a beaucoup encourager pour continuer mais l'utilisation des radiobutton me bloque

voici le code :


import java.awt.EventQueue;

import javax.swing.JFrame;

import java.awt.event.ActionListener;
import java.io.File;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JFileChooser;

import java.io.FileNotFoundException;

import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JRadioButton;

import java.awt.Color;
import javax.swing.JPanel;
import javax.swing.border.TitledBorder;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.RowSpec;
import com.jgoodies.forms.layout.FormSpecs;

import javax.swing.ButtonGroup;
import javax.swing.border.LineBorder;

public class TEST1 {

//	 private static final AbstractButton CPV1 = null;
//	 private static final AbstractButton CPV2 = null;

	private JFrame frame;

	private final ButtonGroup buttonGroup = new ButtonGroup();

	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable(){
			public void run(){
				try {
					TEST1 window = new TEST1();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	public TEST1(){
		initialize();
	}

	private void initialize(){
		frame = new JFrame(" TESTS");
		frame.setBounds(100, 100, 844, 473);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().setLayout(null);

		JButton btnrun = new JButton("RUN");
		btnrun.setFont(new Font("Tahoma", Font.BOLD, 12));

		final JFileChooser chooser = new JFileChooser();
		chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		chooser.setMultiSelectionEnabled(false);

		 ButtonGroup group = new ButtonGroup();
	//	 group.add(CPV1);
	//	 group.add(CPV2);

		btnrun.addActionListener(new ActionListener(){

			public void actionPerformed(ActionEvent e) {

				if (CPV1.isSelected()) {

					if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
						File file = chooser.getSelectedFile();
						Scanner ST = null;
						try {
							ST = new Scanner(file);
						} catch (FileNotFoundException e1) {

							e1.printStackTrace();
						}

						ST.useDelimiter("MAP");

						while (ST.hasNextLine()) {
							String MAP = ST.next();

							Matcher matcher1 = Pattern.compile("(?<vrd>vrd/\\d+)\\s+(?<type>[$\\w]+)").matcher(MAP);

							while (matcher1.find()) {
								System.out.println("///////");

								System.out.println(
										"vrd name" + matcher1.group("vrd") + "type=" + matcher1.group("type") + "\n");
							}
						}

						if (CPV2.isSelected()) {
						}

						ST.useDelimiter("MAP2");

						while (ST.hasNextLine()) {
							String MAP2 = ST.next();

							Matcher matcher2 = Pattern
									.compile("(?<vrrp>vrrp/\\d+)" + ".*" + "\\r?\\n" + ".*" + "\\r?\\n").matcher(MAP2);

							while (matcher2.find()) {
								System.out.println("///////");

								System.out.println("vrrp number " + matcher2.group("vrrp") + "10//12" + "\n");

								ST.close();

							}

						}

					}

				}
			}

		});
		btnrun.setBounds(34, 171, 84, 40);
		frame.getContentPane().add(btnrun);

		JPanel panel = new JPanel();
		panel.setForeground(Color.DARK_GRAY);
		panel.setBorder(new TitledBorder(new LineBorder(new Color(184, 207, 229)), " TYPE", TitledBorder.LEFT,
				TitledBorder.TOP, null, new Color(0, 0, 0)));
		panel.setBounds(24, 57, 98, 77);
		frame.getContentPane().add(panel);
		panel.setLayout(new FormLayout(
				new ColumnSpec[] { FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC,
						FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC, },
				new RowSpec[] { FormSpecs.RELATED_GAP_ROWSPEC, FormSpecs.DEFAULT_ROWSPEC, FormSpecs.RELATED_GAP_ROWSPEC,
						FormSpecs.DEFAULT_ROWSPEC, }));

		JLabel lblNewLabel_2 = new JLabel("ID1");
		lblNewLabel_2.setFont(new Font("Tahoma", Font.BOLD, 11));
		panel.add(lblNewLabel_2, "2, 2");

		JRadioButton CPV1 = new JRadioButton("");
		CPV1.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent arg0) {
			}
		});
		CPV1.setSelected(true);
		buttonGroup.add(CPV1);
		panel.add(CPV1, "4, 2");

		JLabel lblNewLabel_3 = new JLabel("ID2");
		lblNewLabel_3.setFont(new Font("Tahoma", Font.BOLD, 11));
		panel.add(lblNewLabel_3, "2, 4");

		JRadioButton CPV2 = new JRadioButton("");
		CPV2.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
			}
		});
		CPV2.setSelected(true);
		buttonGroup.add(CPV2);
		panel.add(CPV2, "4, 4");

	}
}



merci .
0
KX Messages postés 16733 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 31 janvier 2024 3 015
Modifié le 16 juil. 2020 à 18:50
Tu t'étais emmêlé les pinceaux entre les AbstractButton static CPV1 et CPV2 et les JRadioButton CPV1 et CPV2.
J'ai remis tout cela en ordre, ainsi qu'un certain nombre d'autres changements au passage en particulier sur l'actionPerformed qui contrôle CPV1.isSelected() et CPV2.isSelected().

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.Scanner;
import java.util.function.Function;
import java.util.regex.*;
import javax.swing.*;
import javax.swing.border.*;
import com.jgoodies.layout.layout.*;

public class Test1 extends JFrame {

    public Test1(){
        super("TESTS");
        setBounds(100, 100, 844, 473);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(null);

        // JPanel TYPE

        JPanel panel = new JPanel();
        panel.setForeground(Color.DARK_GRAY);
        panel.setBorder(new TitledBorder(new LineBorder(new Color(184, 207, 229)), " TYPE", TitledBorder.LEFT, TitledBorder.TOP, null, new Color(0, 0, 0)));
        panel.setBounds(24, 57, 98, 77);
        add(panel);
        panel.setLayout(new FormLayout(new ColumnSpec[] { FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC, FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC },
                new RowSpec[] { FormSpecs.RELATED_GAP_ROWSPEC, FormSpecs.DEFAULT_ROWSPEC, FormSpecs.RELATED_GAP_ROWSPEC, FormSpecs.DEFAULT_ROWSPEC }));

        // JLabel ID1

        JLabel ID1 = new JLabel("ID1");
        ID1.setFont(new Font("Tahoma", Font.BOLD, 11));
        panel.add(ID1, "2, 2");

        // JRadioButton CPV1

        JRadioButton CPV1 = new JRadioButton("");
        CPV1.setSelected(true);
        panel.add(CPV1, "4, 2");

        // JLabel ID2

        JLabel ID2 = new JLabel("ID2");
        ID2.setFont(new Font("Tahoma", Font.BOLD, 11));
        panel.add(ID2, "2, 4");

        // JRadioButton CPV2

        JRadioButton CPV2 = new JRadioButton("");
        CPV2.setSelected(false);
        panel.add(CPV2, "4, 4");

        // ButtonGroup

        ButtonGroup buttonGroup = new ButtonGroup();
        buttonGroup.add(CPV1);
        buttonGroup.add(CPV2);

        // JButton RUN

        JButton btnrun = new JButton("RUN");
        btnrun.setFont(new Font("Tahoma", Font.BOLD, 12));
        btnrun.setBounds(34, 171, 84, 40);
        btnrun.addActionListener(e -> {
            if (CPV1.isSelected()) {
                readFile("MAP", "(?<vrd>vrd/\\d+)\\s+(?<type>[$\\w]+)", matcher -> "vrd name" + matcher.group("vrd") + "type=" + matcher.group("type") + "\n");
            }
            if (CPV2.isSelected()) {
                readFile("MAP2", "(?<vrrp>vrrp/\\d+)" + ".*" + "\\r?\\n" + ".*" + "\\r?\\n", matcher -> "vrrp number " + matcher.group("vrrp") + "10//12" + "\n");
            }
        });
        add(btnrun);
    }

    private void readFile(String delimiter, String regex, Function<Matcher, String> result) {
        System.out.println("action " + delimiter + " : START");
        final JFileChooser chooser = new JFileChooser();
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        chooser.setMultiSelectionEnabled(false);
        if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
            File file = chooser.getSelectedFile();
            System.out.println("action " + delimiter + " : " + file.getAbsolutePath());
            try (Scanner ST = new Scanner(file)) {
                ST.useDelimiter(delimiter);
                while (ST.hasNext()) {
                    Matcher matcher = Pattern.compile(regex).matcher(ST.next());
                    while (matcher.find()) {
                        System.out.println("///////");
                        System.out.println(result.apply(matcher));
                    }
                }
            } catch (FileNotFoundException e1) {
                e1.printStackTrace();
            }
        }
        System.out.println("action " + delimiter + " : FINISH");
    }

    public static void main(String[] args) {
        new Test1().setVisible(true);
    }
}
0
Tech43 Messages postés 8 Date d'inscription mardi 7 juillet 2020 Statut Membre Dernière intervention 16 juillet 2020
16 juil. 2020 à 18:44
salut KX :

je vous remercie de m'avoir répondu .

pour le moment L' IDE que j'ai , est JAVA Eclipse Mars 2.0 et la version JRE System Librairie est
[ JAVA SE-1.7] , je ferai les mise à jours nécessaire après et je te reviendrai avec les résultats.


NB: j'ai une petite question :

Est ce que je peux ajouter d'autre pattern avec des expression pour les deux fichiers ?

j 'en ai plusieurs pour les deux fichiers .

par example:


   btnrun.addActionListener(e -> {
            if (CPV1.isSelected()) {
                readFile("MAP", "(?<vrd>vrd/\\d+)\\s+(?<type>[$\\w]+)", matcher -> "vrd name" + matcher.group("vrd") + "type=" + matcher.group("type") + "\n");

readFile("MAP", "(\\s+TTL.*" + "\\r?\\n"+ "(?<trace>trac\\d+)", matcher -> "trace ID" + matcher.group("trac") + "\n");

            }
            if (CPV2.isSelected()) {
                readFile("MAP2", "(?<vrrp>vrrp/\\d+)" + ".*" + "\\r?\\n" + ".*" + "\\r?\\n", matcher -> "vrrp number " + matcher.group("vrrp") + "10//12" + "\n");

         readFile("MAP2", "(?<vrrp>vrrp/\\d+)" , matcher -> "vrrp number " + matcher.group("vrrp") + "\n");
               }
        });
        add(btnrun);
    }


Merci
0
KX Messages postés 16733 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 31 janvier 2024 3 015
Modifié le 16 juil. 2020 à 19:23
Tu pourrais faire une interface, par exemple :

public interface IFileParser {
    String getDelimiter();
    String getRegex();
    String computeResult(Matcher matcher);
}

public class FileParser1 implements IFileParser {
    @Override
    public String getDelimiter(){
          return "MAP";
    }
    @Override
    public String getRegex(){
        return "(?<vrd>vrd/\\d+)\\s+(?<type>[$\\w]+)";
    }
    @Override
    public String computeResult(Matcher matcher);{
        return "vrd name" + matcher.group("vrd") + "type=" + matcher.group("type") + "\n";
    }
}

Puis utiliser un objet de FileParser1, FileParser2, etc. (voire une liste de IFileParser si besoin) pour appeler la méthode readFile (légèrement modifiée) avec un IFileParser en paramètre.
0

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

Posez votre question
salut KX:

la mise à jour a été effectué j'utilise maintenant java Eclipse photon avec JRE [ JAVA SE-1.8] .

j'ai rencontré problème d'instalation jGoodies et j'ai été obligé de faire des modification sur le

code que tu as envoyé ,évidement les suggestions et les corrections proposées par le compilateur .

voici les erreurs trouvé :

1/ Multiple markers at this line
- The method isSelected() is undefined for the type CPV1
- The method isSelected() is undefined for the type CPV2

2 / quand à l’implémentation méthode readFile j'ai pas su le faire il y a trop d'erreurs:

voici le code :

import java.awt.*;

import java.io.*;
import java.util.Scanner;
import java.util.function.Function;
import java.util.regex.*;
import javax.swing.*;

import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.RowSpec;
import com.jgoodies.forms.layout.FormSpecs;

public class Test1 extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private final ButtonGroup buttonGroup = new ButtonGroup();
	private TextArea textArea;

	public interface IFileParser {
		String getDelimiter();

		String getRegex();

		String computeResult(Matcher matcher);
	}

	public abstract class FileParser1 implements IFileParser {
		@Override
		public String getDelimiter(){
			return "MAP";
		}

		@Override
		public String getRegex(){
			return "(?<vrd>vrd/\\d+)\\s+(?<type>[$\\w]+)";
		}

		@Override
		public abstract String computeResult(Matcher matcher);

		{
			Matcher matcher;
			return "(vrd name" + matcher.group("vrd") + "type=" + matcher.group("type") + "\n)";
		}
	}

	public abstract class FileParser2 implements IFileParser {
		@Override
		public String getDelimiter(){
			return "MAP2";
		}

		@Override
		public String getRegex(){
			return "(?<vrrp>vrrp/\\d+)" + ".*" + "\\r?\\n" + ".*" + "\\r?\\n";
		}

		@Override
		public abstract String computeResult(Matcher matcher);{
	        Matcher matcher;
			return "(vrrp number \" + matcher2.group(\"vrrp\") + \"10//12\" + \"\\n\)";
	    }
	}

	public Test1(){
		super("TESTS");
		setBounds(100, 100, 844, 473);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		getContentPane().setLayout(null);

		JPanel panel = new JPanel();
		panel.setBounds(99, 37, 161, 143);
		getContentPane().add(panel);
		panel.setLayout(new FormLayout(
				new ColumnSpec[] { FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC,
						FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC, FormSpecs.RELATED_GAP_COLSPEC,
						FormSpecs.DEFAULT_COLSPEC, FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC, },
				new RowSpec[] { FormSpecs.RELATED_GAP_ROWSPEC, FormSpecs.DEFAULT_ROWSPEC, FormSpecs.RELATED_GAP_ROWSPEC,
						FormSpecs.DEFAULT_ROWSPEC, FormSpecs.RELATED_GAP_ROWSPEC, FormSpecs.DEFAULT_ROWSPEC, }));

		JLabel lblId = new JLabel("ID1");
		panel.add(lblId, "2, 2");

		JRadioButton CPV1 = new JRadioButton("");
		buttonGroup.add(CPV1);
		CPV1.setSelected(true);
		panel.add(CPV1, "8, 2");

		JLabel lblId_1 = new JLabel("ID2");
		panel.add(lblId_1, "2, 6");

		JRadioButton CPV2 = new JRadioButton("");
		buttonGroup.add(CPV1);
		CPV1.setSelected(false);
		panel.add(CPV2, "8, 6");

		JButton btnrun = new JButton("RUN");
		btnrun.setFont(new Font("Tahoma", Font.BOLD, 12));
		btnrun.setBounds(134, 242, 84, 40);
		btnrun.addActionListener(e -> {
			if (CPV1.isSelected()) {
				// readFile ;

			}
			if (CPV2.isSelected()) {
				// readFile;
			}
		});

		getContentPane().add(btnrun);

		TextArea textArea = new TextArea();
		textArea.setBounds(236, 186, 380, 160);
		getContentPane().add(textArea);
	}

	private void readFile(String delimiter, String regex, Function<Matcher, String> result) {
		System.out.println("action " + delimiter + " : START");
		final JFileChooser chooser = new JFileChooser();
		chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		chooser.setMultiSelectionEnabled(false);
		if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
			File file = chooser.getSelectedFile();
			System.out.println("action " + delimiter + " : " + file.getAbsolutePath());
			try (Scanner ST = new Scanner(file)) {
				ST.useDelimiter(delimiter);
				while (ST.hasNext()) {
					Matcher matcher = Pattern.compile(regex).matcher(ST.next());
					while (matcher.find()) {
						// System.out.println("///////");
						textArea.append(result.apply(matcher));
					}
				}
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			}
		}
		textArea.append("action " + delimiter + " : FINISH");
	}

	public static void main(String[] args) {
		new Test1().setVisible(true);
	}
}




Merci
0
KX Messages postés 16733 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 31 janvier 2024 3 015
Modifié le 18 juil. 2020 à 09:14
Pour la méthode readFile, le fait que tu sois passé en Java 8 règle le problème, tu peux revenir à la première version que j'avais proposé (avec les lambdas), l'interface était une alternative pour que ça fonctionne en Java 7.

En Java 8 :
import java.awt.*;
import java.io.*;
import java.util.Scanner;
import java.util.function.Consumer;
import java.util.regex.*;
import javax.swing.*;
import com.jgoodies.forms.layout.*;

public class Test1 extends JFrame {
    private static final long serialVersionUID = 1;

    public Test1(){
        super("TESTS");
        setBounds(100, 100, 844, 473);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(null);

        JPanel panel = new JPanel();
        panel.setBounds(99, 37, 161, 143);
        panel.setLayout(new FormLayout(new ColumnSpec[] { FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC, //
                FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC, FormSpecs.RELATED_GAP_COLSPEC, //
                FormSpecs.DEFAULT_COLSPEC, FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC, }, //
                new RowSpec[] { FormSpecs.RELATED_GAP_ROWSPEC, FormSpecs.DEFAULT_ROWSPEC, FormSpecs.RELATED_GAP_ROWSPEC, //
                        FormSpecs.DEFAULT_ROWSPEC, FormSpecs.RELATED_GAP_ROWSPEC, FormSpecs.DEFAULT_ROWSPEC, })); //
        add(panel);

//      JLabel lblId = new JLabel("ID1");
//      panel.add(lblId, "2, 2");

        JRadioButton CPV1 = new JRadioButton("ID1");
        CPV1.setSelected(true);
        panel.add(CPV1, "8, 2");

//      JLabel lblId_1 = new JLabel("ID2");
//      panel.add(lblId_1, "2, 6");

        JRadioButton CPV2 = new JRadioButton("ID2");
        CPV1.setSelected(false);
        panel.add(CPV2, "8, 6");

        ButtonGroup buttonGroup = new ButtonGroup();
        buttonGroup.add(CPV1);
        buttonGroup.add(CPV1);

        TextArea textArea = new TextArea();
        textArea.setBounds(236, 186, 380, 160);
        add(textArea);

        JButton btnrun = new JButton("RUN");
        btnrun.setFont(new Font("Tahoma", Font.BOLD, 12));
        btnrun.setBounds(134, 242, 84, 40);
        btnrun.addActionListener(e -> {
            if (CPV1.isSelected()) {
                readFile("MAP", "(?<vrd>vrd/\\d+)\\s+(?<type>[$\\w]+)", //
                        matcher -> textArea.append("(vrd name" + matcher.group("vrd") + "type=" + matcher.group("type") + "\n)"));
            }
            if (CPV2.isSelected()) {
                readFile("MAP2", "(?<vrrp>vrrp/\\d+)" + ".*" + "\\r?\\n" + ".*" + "\\r?\\n", //
                        matcher -> textArea.append("(vrrp number " + matcher.group("vrrp") + "10//12" + "\n"));
            }
        });

        add(btnrun);
    }

    private void readFile(String delimiter, String regex, Consumer<Matcher> resultConsumer) {
        System.out.println("action " + delimiter + " : START");
        final JFileChooser chooser = new JFileChooser();
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        chooser.setMultiSelectionEnabled(false);
        if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
            File file = chooser.getSelectedFile();
            System.out.println("action " + delimiter + " : " + file.getAbsolutePath());
            try (Scanner ST = new Scanner(file)) {
                ST.useDelimiter(delimiter);
                while (ST.hasNext()) {
                    Matcher matcher = Pattern.compile(regex).matcher(ST.next());
                    while (matcher.find()) {
                        resultConsumer.accept(matcher);
                    }
                }
            } catch (FileNotFoundException e1) {
                e1.printStackTrace();
            }
        }
        System.out.println("action " + delimiter + " : FINISH");
    }
    
    public static void main(String[] args) {
        new Test1().setVisible(true);
    }
}

Remarque : jgoodies n'a rien de standard, tu pourrais faire la même chose avec des Layout standards.
https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
0
salut kx:

merci pour votre réponse et désolé pour le retard .

je ne t'avais pas compris , j'ai cru que les expressions lambdas nécessite une mise à jour java

vers java 8 , je dois avouer que c'est la première fois que j'utilise lambdas .

je n'ai pas trouver des exemple de création des interface en utilisant les expressions lambda.

parce que dans mon code j'ai beaucoup des expression régulière à mettre en oeuvre .

je ferai d'autre test et je te reviendrai .
0
KX Messages postés 16733 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 31 janvier 2024 3 015
22 juil. 2020 à 20:23
"j'ai cru que les expressions lambdas nécessite une mise à jour java vers java 8"
Oui c'est le cas, les lambdas ont été introduites en Java 8.
Ceci dit la version la plus récente c'est Java 14 (!) donc c'est tout à fait normal que sur un forum on te propose de faire des lambdas ou d'autres fonctionnalités plus récentes...

"je n'ai pas trouver des exemple de création des interface en utilisant les expressions lambda"
Les lambdas ne sont pas spécifiques aux interface graphiques, c'est une manière de coder qui peut s'appliquer partout (y compris sur les interfaces graphiques).
D'ailleurs dans ton cas, si j'ai utilisé les lambdas dans le code de l'interface graphique c'est parce que tu as mis tout le code du programme au même endroit, mais en vrai c'est sur la partie traitement du fichier que se trouve les lambdas (plus exactement dans l'extraction du résultat de l'expression régulière).
0
salut KX:

merci pour les remarque j'ai appris beaucoup de choses .

actuellement j'ai pu réglé plusieurs problème de la partie une , et la compilation se fait normalement .

mais le résultat recherché ne s'affiche pas après compilation dans TextArea ?

j'ai seulement ça qui s'affichent sur la console :

action MAP : START
action MAP : C:\Users\Tech42\Desktop\fichier1.txt
action MAP : FINISH

action MAP2 : START
action MAP2 : C:\Users\Tech42\Desktop\fichier2.txt
action MAP2 : FINISH


voici le code qui marche sur mon PC

import java.awt.*;

import java.io.*;
import java.util.Scanner;

import java.util.regex.*;
import javax.swing.*;

import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.RowSpec;
import com.jgoodies.forms.layout.FormSpecs;
import java.util.function.Consumer;

public class Test1 extends JFrame {
	
	private static final long serialVersionUID = 1L;

	private final ButtonGroup buttonGroup_1 = new ButtonGroup();
	private TextArea textArea ;

	public Test1(){
		super("TESTS");
		setBounds(100, 100, 309, 441);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		getContentPane().setLayout(null);

		JPanel panel = new JPanel();
		panel.setBounds(99, 37, 100, 87);
		getContentPane().add(panel);
		panel.setLayout(new FormLayout(
				new ColumnSpec[] { FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC,
						FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC, FormSpecs.RELATED_GAP_COLSPEC,
						FormSpecs.DEFAULT_COLSPEC, FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC, },
				new RowSpec[] { FormSpecs.RELATED_GAP_ROWSPEC, FormSpecs.DEFAULT_ROWSPEC, FormSpecs.RELATED_GAP_ROWSPEC,
						FormSpecs.DEFAULT_ROWSPEC, FormSpecs.RELATED_GAP_ROWSPEC, FormSpecs.DEFAULT_ROWSPEC, }));

		JLabel lblId = new JLabel("ID1");
		panel.add(lblId, "2, 2");

		JRadioButton CPV1 = new JRadioButton("");
		buttonGroup_1.add(CPV1);
		panel.add(CPV1, "8, 2");

		JLabel lblId_1 = new JLabel("ID2");
		panel.add(lblId_1, "2, 6");

		JRadioButton CPV2 = new JRadioButton("");
		buttonGroup_1.add(CPV2);
		CPV1.setSelected(true);
		panel.add(CPV2, "8, 6");

		JButton btnrun = new JButton("RUN");
		btnrun.setFont(new Font("Tahoma", Font.BOLD, 12));
		btnrun.setBounds(99, 160, 84, 40);
		btnrun.addActionListener(e -> {
			if (CPV1.isSelected()) {
				readFile("MAP", "(?<vrd>vrd-\\d+)\\s+(?<type>[$\\w]+)", 
						matcher -> textArea.append("(vrd name" + matcher.group("vrd") + "type=" + matcher.group("type") + "\n)"));
			}
			if (CPV2.isSelected()) {
				readFile("MAP2", "(?<vrrp>vrrp-\\d+)" + ".*" + "\\r?\\n" + ".*" + "\\r?\\n", 
						matcher -> textArea.append("(vrrp number " + matcher.group("vrrp") + "10//12" + "\n"));
			}
		});

		getContentPane().add(btnrun);

		TextArea textArea = new TextArea();
		textArea.setBounds(10, 234, 273, 146);
		getContentPane().add(textArea);
	}

	private void readFile(String delimiter, String regex, Consumer<Matcher> resultConsumer) {
		System.out.println("action " + delimiter + " : START");
		final JFileChooser chooser = new JFileChooser();
		chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		chooser.setMultiSelectionEnabled(false);
		if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
			File file = chooser.getSelectedFile();
			System.out.println("action " + delimiter + " : " + file.getAbsolutePath());
			try (Scanner ST = new Scanner(file)) {
				ST.useDelimiter(delimiter);
				while (ST.hasNext()) {
					Matcher matcher = Pattern.compile(regex).matcher(ST.next());
					while (matcher.find()) {
						resultConsumer.accept(matcher);
					}
				}
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			}
		}
		System.out.println("action " + delimiter + " : FINISH");
	}

	public static void main(String[] args) {
		new Test1().setVisible(true);
	}
}



merci
0
KX Messages postés 16733 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 31 janvier 2024 3 015
24 juil. 2020 à 23:37
Le problème c'est que tu as 2 textArea :
  • celui de la ligne 20 où l'on ajoute les données via les lambdas lignes 59 et 63
  • celui de la ligne 69 qui est ajouté à l'interface ligne 71 et donc affiché

Pour que ça fonctionne il faudrait qu'il n'y en ait qu'un seul, en supprimant la ligne 20 et en mettant les lignes 69 à 71 avant la ligne 53.
0
Salut KX:

Les modifications apportées au fichier ont donné une bonne résultat merci beaucoup.

En ce qui concerne la deuxième partie :

Je dois avoir 20 objets de FileParser1, FileParser2, ...........FileParser20.

Comment appeler la méthode Read File avec la listes des IFileParser en paramètre ?

Est cet ce que les 20 objets que je dois les ajoutées par cette manière cité ci-dessous ?


import java.awt.*;

import java.io.*;
import java.util.Scanner;

import java.util.regex.*;
import javax.swing.*;

import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.RowSpec;
import com.jgoodies.forms.layout.FormSpecs;
import java.util.function.Consumer;

public class Test1 extends JFrame {

	private static final long serialVersionUID = 1L;

	private final ButtonGroup buttonGroup_1 = new ButtonGroup();

	public interface IFileParser {
		String getDelimiter();

		String getRegex();

		String computeResult(Matcher matcher);
	}

	public abstract class FileParser1 implements IFileParser {
		@Override
		public String getDelimiter(){
			return "MAP";
		}

		@Override
		public String getRegex(){
			return "(?<vrd>vrd/\\d+)\\s+(?<type>[$\\w]+)";
		}

		@Override
		public abstract String computeResult(Matcher matcher);

		{
			Matcher matcher;
			return "(vrd name" + matcher.group("vrd") + "type=" + matcher.group("type") + "\n)";
		}
	}

	public abstract class FileParser2 implements IFileParser {
		@Override
		public String getDelimiter(){
			return "MAP2";
		}

		@Override
		public String getRegex(){
			return "(?<vrrp>vrrp/\\d+)" + ".*" + "\\r?\\n" + ".*" + "\\r?\\n";
		}

		@Override
		public abstract String computeResult(Matcher matcher);

		{
	        Matcher matcher;
			return "(vrrp number \" + matcher2.group(\"vrrp\") + \"10//12\" + "\\n)";
	    }
	}

	public Test1(){
		super("TESTS");
		setBounds(100, 100, 309, 441);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		getContentPane().setLayout(null);

		JPanel panel = new JPanel();
		panel.setBounds(99, 37, 100, 87);
		getContentPane().add(panel);
		panel.setLayout(new FormLayout(
				new ColumnSpec[] { FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC,
						FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC, FormSpecs.RELATED_GAP_COLSPEC,
						FormSpecs.DEFAULT_COLSPEC, FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC, },
				new RowSpec[] { FormSpecs.RELATED_GAP_ROWSPEC, FormSpecs.DEFAULT_ROWSPEC, FormSpecs.RELATED_GAP_ROWSPEC,
						FormSpecs.DEFAULT_ROWSPEC, FormSpecs.RELATED_GAP_ROWSPEC, FormSpecs.DEFAULT_ROWSPEC, }));

		JLabel lblId = new JLabel("ID1");
		panel.add(lblId, "2, 2");

		JRadioButton CPV1 = new JRadioButton("");
		buttonGroup_1.add(CPV1);
		panel.add(CPV1, "8, 2");

		JLabel lblId_1 = new JLabel("ID2");
		panel.add(lblId_1, "2, 6");

		JRadioButton CPV2 = new JRadioButton("");
		buttonGroup_1.add(CPV2);
		CPV1.setSelected(true);
		panel.add(CPV2, "8, 6");

		JButton btnrun = new JButton("RUN");
		btnrun.setFont(new Font("Tahoma", Font.BOLD, 12));
		btnrun.setBounds(99, 160, 84, 40);
		btnrun.addActionListener(e -> {
			if (CPV1.isSelected()) {
		////		readFile( );
						
			}
			if (CPV2.isSelected()) {
		/////		readFile (); 
			}
		});

		getContentPane().add(btnrun);
0
KX Messages postés 16733 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 31 janvier 2024 3 015
26 juil. 2020 à 20:05
Dans la mesure où tu es passé sur du Java 8, avec les lambdas, l'interface IFileParser ne sert plus à rien, c'était juste une manière de le faire en Java 7.

Et c'est sur les lambdas qu'il faut que tu t'appuies pour regrouper les différents traitements que tu souhaites faire.

Exemple :

public enum FileParser {
    CPV1("MAP", "(?<vrd>vrd-\\d+)\\s+(?<type>[$\\w]+)", matcher -> "(vrd name" + matcher.group("vrd") + "type=" + matcher.group("type") + "\n)"), 
    CPV2("MAP2", "(?<vrrp>vrrp-\\d+)" + ".*" + "\\r?\\n" + ".*" + "\\r?\\n", matcher -> "(vrrp number " + matcher.group("vrrp") + "10//12" + "\n"),
    ...
    CPV20(...);

    private final String delimiter;
    private final String regex;
    private final Function<Matcher, String> matcherFunction;

    private FileParser(String delimiter, String regex, Function<Matcher, String> matcherFunction) {
        this.delimiter = delimiter;
        this.regex = regex;
        this.matcherFunction = matcherFunction;
    }
}

Ensuite il s'agit d'adapter la méthode readFile, par exemple :
void readFile(FileParser parser, TextArea textArea)

Où le paramètre parser contient tout ce qu'il te faut pour analyser ton fichier en fonction de son type.
0
salut KX:

merci beaucoup pour les nouveaux astuces apporter tel que l’utilisation des énumérations ..

1/ je suis confronté à autre problème , je doit utilisé 20 regex pour le bouton 1 et 20 pour

bouton 2 donc dans la déclaration des enums je dois mettre que CPV1 et CPV2 .

en commençant j'ai les erreurs suivantes :

Duplicate field Test1.FileParser.CPV1
Duplicate field Test1.FileParser.CPV2


voici le code :

import java.awt.*;

import java.io.*;
import java.util.Scanner;

import java.util.regex.*;
import javax.swing.*;

import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.RowSpec;
import com.jgoodies.forms.layout.FormSpecs;
import java.util.function.Consumer;
import java.util.function.Function;

public class Test1 extends JFrame {

	private static final long serialVersionUID = 1L;

	private final ButtonGroup buttonGroup_1 = new ButtonGroup();
	

	
	public enum FileParser {
  CPV1("MAP", "(?<vrd>vrd-\\d+)\\s+(?<type>[$\\w]+)", matcher -> "(vrd name" + matcher.group("vrd") + "type=" + matcher.group("type") + "\n)"), 
  CPV1("MAP", "(?<vrd>vrd-\\d+)\\s+)", matcher -> "(vrd name" + matcher.group("vrd")  + "\n)"), 
  CPV2("MAP2", "(?<vrrp>vrrp-\\d+)" + ".*" + "\\r?\\n" + ".*" + "\\r?\\n", matcher -> "(vrrp number " + matcher.group("vrrp") + "10//12" + "\n"),
  CPV2("MAP2", "(?<vrrp>vrrp-\\d+)" , matcher -> "(vrrp number " + matcher.group("vrrp") + "10//12" + "\n");
	    

	    private final String delimiter;
	    private final String regex;
	    private final Function<Matcher, String> matcherFunction;

	    private FileParser(String delimiter, String regex, Function<Matcher, String> matcherFunction) {
	        this.delimiter = delimiter;
	        this.regex = regex;
	        this.matcherFunction = matcherFunction;
	    }
	}

	public Test1(){
		super("TESTS");
		setBounds(100, 100, 309, 441);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		getContentPane().setLayout(null);

		JPanel panel = new JPanel();
		panel.setBounds(99, 37, 100, 87);
		getContentPane().add(panel);
		panel.setLayout(new FormLayout(
				new ColumnSpec[] { FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC,
						FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC, FormSpecs.RELATED_GAP_COLSPEC,
						FormSpecs.DEFAULT_COLSPEC, FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC, },
				new RowSpec[] { FormSpecs.RELATED_GAP_ROWSPEC, FormSpecs.DEFAULT_ROWSPEC, FormSpecs.RELATED_GAP_ROWSPEC,
						FormSpecs.DEFAULT_ROWSPEC, FormSpecs.RELATED_GAP_ROWSPEC, FormSpecs.DEFAULT_ROWSPEC, }));

		JLabel lblId = new JLabel("ID1");
		panel.add(lblId, "2, 2");

		JRadioButton CPV1 = new JRadioButton("");
		buttonGroup_1.add(CPV1);
		panel.add(CPV1, "8, 2");

		JLabel lblId_1 = new JLabel("ID2");
		panel.add(lblId_1, "2, 6");

		JRadioButton CPV2 = new JRadioButton("");
		buttonGroup_1.add(CPV2);
		CPV1.setSelected(true);
		panel.add(CPV2, "8, 6");

		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(10, 234, 273, 146);
		getContentPane().add(scrollPane);

		TextArea textArea = new TextArea();
		scrollPane.setViewportView(textArea);

		JButton btnrun = new JButton("RUN");
		btnrun.setFont(new Font("Tahoma", Font.BOLD, 12));
		btnrun.setBounds(99, 160, 84, 40);
		btnrun.addActionListener(e -> {
			if (CPV1.isSelected()) {
				readFile("MAP", "(?<vrd>vrd-\\d+)\\s+(?<type>[$\\w]+)", 
						matcher -> textArea.append("(vrd name" + matcher.group("vrd") + "type=" + matcher.group("type") + "\n)"));

                                readFile("MAP", "(?<vrd>vrd-\\d+)", 
						matcher -> textArea.append("(vrd name" + matcher.group("vrd") + "type=" + matcher.group("type") + "\n)"));
			}
			if (CPV2.isSelected()) {
				readFile("MAP2", "(?<vrrp>vrrp-\\d+)" + ".*" + "\\r?\\n" + ".*" + "\\r?\\n", 
						matcher -> textArea.append("(vrrp number " + matcher.group("vrrp") + "10//12" + "\n"));
                               if (CPV2.isSelected()) {
				readFile("MAP2", "(?<vrrp>vrrp-\\d+)", 
						matcher -> textArea.append("(vrrp number " + matcher.group("vrrp") + "10//12" + "\n"));
			}
		});

		getContentPane().add(btnrun);

	}


	
}

void readFile(FileParser parser, TextArea textArea) {
}


private void readFile(String delimiter, String regex, Consumer<Matcher> resultConsumer) {
		System.out.println("action " + delimiter + " : START");
		final JFileChooser chooser = new JFileChooser();
		chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		chooser.setMultiSelectionEnabled(false);
		if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
			File file = chooser.getSelectedFile();
			System.out.println("action " + delimiter + " : " + file.getAbsolutePath());
			try (Scanner ST = new Scanner(file)) {
				ST.useDelimiter(delimiter);
				while (ST.hasNext()) {
					Matcher matcher = Pattern.compile(regex).matcher(ST.next());
					while (matcher.find()) {
						resultConsumer.accept(matcher);
					}
				}
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			}
		}
		System.out.println("action " + delimiter + " : FINISH");
	}

	public static void main(String[] args) {
		new Test1().setVisible(true);
	}
}



merci pour votre aide et support .
0
KX Messages postés 16733 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 31 janvier 2024 3 015
3 août 2020 à 14:50
Bonjour,

Dans la déclaration de l'enum FileParser, aux lignes 25 et 26 tu as deux fois la valeur CPV1, idem pour les lignes 27 et 28 où tu as deux fois la valeur CPV2, or chaque valeur doit avoir un nom différent (CPV1, CPV2, CPV3...)
0
salut:

j'ai cru que chaque bouton d'ou boutton1 avec variable CPV1 et boutton2 avec variable CPV2 ont leur prorpe objets.

j'ai fait les modifications recommandées dans cette portion :

public enum FileParser {
  CPV1("MAP", "(?<vrd>vrd-\\d+)\\s+(?<type>[$\\w]+)", matcher -> "(vrd name" + matcher.group("vrd") + "type=" + matcher.group("type") + "\n)"), 
  CPV2("MAP", "(?<vrd>vrd-\\d+)\\s+)", matcher -> "(vrd name" + matcher.group("vrd")  + "\n)"), 
  CPV3("MAP2", "(?<vrrp>vrrp-\\d+)" + ".*" + "\\r?\\n" + ".*" + "\\r?\\n", matcher -> "(vrrp number " + matcher.group("vrrp") + "10//12" + "\n"),
  CPV4("MAP2", "(?<vrrp>vrrp-\\d+)" , matcher -> "(vrrp number " + matcher.group("vrrp") + "10//12" + "\n");



maintenant j'ai deux méthode pour lire le fichier ( static et non static )


1/private void readFile(String delimiter, String regex, Consumer<Matcher> resultConsumer) 

2/ void readFile(FileParser parser, TextArea textArea)



Est ce que tu peux m'aider comment implémenter dans ce bout de code ?


		btnrun.addActionListener(e -> {
			if (CPV1.isSelected()) {
				readFile("MAP", "(?<vrd>vrd-\\d+)\\s+(?<type>[$\\w]+)", 
						matcher -> textArea.append("(vrd name" + matcher.group("vrd") + "type=" + matcher.group("type") + "\n)"));

                                readFile("MAP", "(?<vrd>vrd-\\d+)", 
						matcher -> textArea.append("(vrd name" + matcher.group("vrd") + "type=" + matcher.group("type") + "\n)"));
			}
			if (CPV2.isSelected()) {
				readFile("MAP2", "(?<vrrp>vrrp-\\d+)" + ".*" + "\\r?\\n" + ".*" + "\\r?\\n", 
						matcher -> textArea.append("(vrrp number " + matcher.group("vrrp") + "10//12" + "\n"));
                               if (CPV2.isSelected()) {
				readFile("MAP2", "(?<vrrp>vrrp-\\d+)", 
						matcher -> textArea.append("(vrrp number " + matcher.group("vrrp") + "10//12" + "\n"));
			}
		});

		getContentPane().add(btnrun);

	}




merci
0
KX Messages postés 16733 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 31 janvier 2024 3 015
3 août 2020 à 17:56
Voici la seule méthode readFile qu'il faut garder, avec la signature de ta 2) et le corps de ta 1) modifié

private void readFile(FileParser parser, TextArea textArea) {
    System.out.println("readFile " + parser + " : START");
    final JFileChooser chooser = new JFileChooser();
    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    chooser.setMultiSelectionEnabled(false);
    if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
        File file = chooser.getSelectedFile();
        System.out.println("readFile " + parser + " : " + file.getAbsolutePath());
        try (Scanner ST = new Scanner(file)) {
            ST.useDelimiter(parser.delimiter);
            while (ST.hasNext()) {
                Matcher matcher = Pattern.compile(parser.regex).matcher(ST.next());
                while (matcher.find()) {
                    textArea.setText(parser.matcherFunction.apply(matcher));
                }
            }
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
    }
    System.out.println("readFile " + parser + " : FINISH");
}

Quant à son intégration ça donnerait ceci :
btnrun.addActionListener(e -> {
    if (CPV1.isSelected()) {
        readFile(FileParser.CPV1, textArea);
    }
    if (CPV2.isSelected()) {
        readFile(FileParser.CPV2, textArea);
    }
}
0
salut kx:

j'ai implémenter vos recommandation ça marche bien . mais il y a un problème d’affichage.

ce qui est affiché dans textarea il y a que CPV1 si je choisi radiobutton 1 ou CPV2 si je choisi

radiobutton 2.

CPV3 ....... CPV20 ne sont pas affichées .



public enum FileParser {
  CPV1("MAP", "(?<vrd>vrd-\\d+)\\s+(?<type>[$\\w]+)", matcher -> "(vrd name" + matcher.group("vrd") + "type=" + matcher.group("type") + "\n)"), 
  CPV2("MAP", "(?<vrd>vrd-\\d+)\\s+)", matcher -> "(vrd name" + matcher.group("vrd")  + "\n)"), 
  CPV3("MAP2", "(?<vrrp>vrrp-\\d+)" + ".*" + "\\r?\\n" + ".*" + "\\r?\\n", matcher -> "(vrrp number " + matcher.group("vrrp") + "10//12" + "\n"),
  CPV4("MAP2", "(?<vrrp>vrrp-\\d+)" , matcher -> "(vrrp number " + matcher.group("vrrp") + "10//12" + "\n");



merci beaoucoup pour votre support habituel .
0
KX Messages postés 16733 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 31 janvier 2024 3 015
Modifié le 4 août 2020 à 19:06
Bonjour,

En effet, les boutons sont actuellement gérés indépendamment de la valeur de l'enum. Il faudrait les ajouter dynamiquement, l'occasion de revoir les layout (notamment supprimer jGoodies) et réorganiser ton code.

Exemple :

import java.awt.*;
import java.io.File;
import java.util.*;
import java.util.function.Function;
import java.util.regex.*;
import javax.swing.*;

public class Test1 extends JFrame {
    private static final long serialVersionUID = 1L;

    private enum FileParser {
        CPV1("MAP", "(?<vrd>vrd-\\d+)\\s+(?<type>[$\\w]+)", matcher -> "(vrd name" + matcher.group("vrd") + "type=" + matcher.group("type") + "\n)"), //
        CPV2("MAP", "(?<vrd>vrd-\\d+)\\s+)", matcher -> "(vrd name" + matcher.group("vrd") + "\n)"), //
        CPV3("MAP2", "(?<vrrp>vrrp-\\d+)" + ".*" + "\\r?\\n" + ".*" + "\\r?\\n", matcher -> "(vrrp number " + matcher.group("vrrp") + "10//12" + "\n"), //
        CPV4("MAP2", "(?<vrrp>vrrp-\\d+)", matcher -> "(vrrp number " + matcher.group("vrrp") + "10//12" + "\n");

        private final String delimiter;
        private final String regex;
        private final Function<Matcher, String> matcherFunction;

        private FileParser(String delimiter, String regex, Function<Matcher, String> matcherFunction) {
            this.delimiter = delimiter;
            this.regex = regex;
            this.matcherFunction = matcherFunction;
        }
    }

    public Test1(){
        // NORTH
        JPanel buttonsPanel = new JPanel();
        buttonsPanel.setLayout(new GridLayout(5, 8));
        ButtonGroup buttonGroup = new ButtonGroup();
        EnumMap<FileParser, JRadioButton> buttons = new EnumMap<>(FileParser.class);
        for (FileParser parser : FileParser.values()) {
            JRadioButton button = new JRadioButton(parser.name());
            buttonGroup.add(button);
            buttons.put(parser, button);
            buttonsPanel.add(button);
        }
        add(buttonsPanel, BorderLayout.NORTH);

        // CENTER
        JScrollPane scrollPane = new JScrollPane();
        TextArea textArea = new TextArea();
        scrollPane.setViewportView(textArea);
        add(scrollPane, BorderLayout.CENTER);

        // SOUTH
        JButton btnrun = new JButton("RUN");
        btnrun.setFont(new Font("Tahoma", Font.BOLD, 12));
        btnrun.addActionListener(e -> {
            buttons.forEach((parser, button) -> {
                if (button.isSelected()) {
                    readFile(parser, textArea);
                }
            });
        });
        add(btnrun, BorderLayout.SOUTH);

        // COMMON
        setTitle("TESTS");
        pack();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    private void readFile(FileParser parser, TextArea textArea) {
        System.out.println("readFile " + parser + " : START");
        final JFileChooser chooser = new JFileChooser();
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        chooser.setMultiSelectionEnabled(false);
        if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
            File file = chooser.getSelectedFile();
            System.out.println("readFile " + parser + " : " + file.getAbsolutePath());
            try (Scanner scanner = new Scanner(file)) {
                scanner.useDelimiter(parser.delimiter);
                while (scanner.hasNext()) {
                    Matcher matcher = Pattern.compile(parser.regex).matcher(scanner.next());
                    while (matcher.find()) {
                        textArea.setText(parser.matcherFunction.apply(matcher));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                JOptionPane.showMessageDialog(this, e.getMessage(), e.getClass().getSimpleName(), JOptionPane.ERROR_MESSAGE);
            }
        }
        System.out.println("readFile " + parser + " : FINISH");
    }

    public static void main(String[] args) {
        new Test1();
    }
}
0
Salut KX:

merci beaucoup pour votre support .

j'ai testé l'application , chaque fois je choisi le bouton et ensuite pour cancatener le résultat de tous les boutons dans textarea je clic sur RUN à tour de role .

juste une dernière question :

Est ce que c'est faisable ?

je vais faire deux bouton par example CPV21 et un autre CPV22 et je cherche à entrer deux nombre entier depuis textField & textField1 pour faire un calcul et aficher le resultat dans textarea comme notre example , sachant que la methode scanner est utilisé que pour la lecture du fichier .

				if  (textField.getText().trim().equals(""))
				{	
					JOptionPane.showMessageDialog(null, "Please enter Value");
						} else {
					
				
				textarea.append(""+"\n");
				
	textarea.append("test:"+textField.getText()+","+"valeur:"+ (1+3*Integer.parseInt(textField.getText()))+":"+((4*Integer.parseInt(textField.getText());
	
			if  (textField1.getText().trim().equals(""))
				{	
					JOptionPane.showMessageDialog(null, "Please enter Value");
						} else {
	
			textarea.append("test:"+textField1.getText()+","+"valeur:"+ (1+3*Integer.parseInt(textField1.getText()))+":"+((4*Integer.parseInt(textField1.getText());
			}
			}




je cherche à avoir ceci :


			
				public enum FileParser {
   CPV21("MAP", "(?<vrd>vrd-\\d+)\\s+(?<type>[$\\w]+)", matcher -> "(vrd name" + matcher.group("vrd") + "type=" + matcher.group("type") +"valeur1='"test:"+textField.getText()+","+"valeur:"+ (1+3*Integer.parseInt(textField.getText()))+":"+((4*Integer.parseInt(textField.getText()+ "\n)"),
   CPV22("MAP", "(?<vrd>vrd-\\d+)\\s+(?<type>[$\\w]+)", matcher -> "(vrd name" + matcher.group("vrd") + "type=" + matcher.group("type") +"valeur2='"test:"+textField1.getText()+","+"valeur:"+ (1+3*Integer.parseInt(textField1.getText()))+":"+((4*Integer.parseInt(textField1.getText()+ "\n)"),



merci
0
KX Messages postés 16733 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 31 janvier 2024 3 015
5 août 2020 à 16:45
Je ne suis pas sûr d'avoir compris.

Tu veux que ta String à afficher ne dépende pas que de la regex, mais également de valeurs saisies ? Dans ce cas tu peux modifier matcherFunction pour qu'en plus du Matcher elle prenne également en paramètre tes valeurs.

Exemple :
private enum FileParser {
    CPV21("MAP", "(?<vrd>vrd-\\d+)\\s+(?<type>[$\\w]+)", (matcher, values) ->
        "(vrd name" + matcher.group("vrd") + "type=" + matcher.group("type") + " // " + values[0] + " " + values[1] + "\n");

    private final String delimiter;
    private final String regex;
    private final BiFunction<Matcher, String[], String> matcherFunction;

    private FileParser(String delimiter, String regex, BiFunction<Matcher, String[], String> matcherFunction) {
        this.delimiter = delimiter;
        this.regex = regex;
        this.matcherFunction = matcherFunction;
    }
}

String[] values = {textField.getText(), textField1.getText()};
// ...
Matcher matcher = Pattern.compile(parser.regex).matcher(scanner.next());
while (matcher.find()) {
    textArea.setText(parser.matcherFunction.apply(matcher, values));
}
0
salut:

je veux avoir les deux ( regex + les valeurs ) uniquement pour CPV21 et CPV22.

DU CPV1 au CPV20 ( regex seulement )

merci
0
KX Messages postés 16733 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 31 janvier 2024 3 015
5 août 2020 à 17:32
Ça ne change pas grand chose, il suffit de ne pas te servir des valeurs dans la construction du String.

Éventuellement tu peux faire un second constructeur dans le FileParser mais ça ne fera qu'ignorer les String.
private enum FileParser {
    CPV1("MAP", "(?<vrd>vrd-\\d+)\\s+(?<type>[$\\w]+)", (matcher) -> "(vrd name" + matcher.group("vrd") + "type=" + matcher.group("type") + ")\n"),
    CPV20("MAP", "(?<vrd>vrd-\\d+)\\s+(?<type>[$\\w]+)", (matcher, values) -> "(vrd name" + matcher.group("vrd") + "type=" + matcher.group("type") + ") // " + values[0] + " " + values[1] + "\n");

    private final String delimiter;
    private final String regex;
    private final BiFunction<Matcher, String[], String> matcherFunction;

    private FileParser(String delimiter, String regex, BiFunction<Matcher, String[], String> matcherFunction) {
        this.delimiter = delimiter;
        this.regex = regex;
        this.matcherFunction = matcherFunction;
    }

    private FileParser(String delimiter, String regex, Function<Matcher, String> matcherFunction) {
        this(delimiter, regex, (matcher, values) -> matcherFunction.apply(matcher));
    }
}
0
salut KX:

j'ai pas pu ajouter les deux textField & textField1 dand Jframe malgré que j'ai mis :

setResizable(true); elle été false .

est ce qu'il y a quelque chose à changer ?

merci
0
KX Messages postés 16733 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 31 janvier 2024 3 015
5 août 2020 à 22:45
Je ne sais pas où tu veux les mettre, mais voici un exemple pour les positionner à côté du bouton :

// SOUTH
JPanel south = new JPanel(new GridLayout(1, 3));
JTextField textField1 = new JTextField();
JTextField textField2 = new JTextField();
south.add(textField1);
south.add(textField2);
JButton btnrun = new JButton("RUN");
btnrun.setFont(new Font("Tahoma", Font.BOLD, 12));
btnrun.addActionListener(e -> {
    buttons.forEach((parser, button) -> {
        if (button.isSelected()) {
            readFile(parser, textArea, textField1, textField2);
        }
    });
});
south.add(btnrun);
add(south, BorderLayout.SOUTH); 
0
salut kx:

merci beaucoup pour les nouveaux astuces ( GridLayout , BorderLayout).

j'ai encore besoin d'aide , juste une petite addition :

1/ le nombre entier que je dois récupéré depuis textfield je dois le multiplier x2 et additionner à10.

idem pour textfield1.

2/ j'ai l'erreur suivante :

Multiple markers at this line
- The method getText() is undefined for the type
textField
- The method getText() is undefined for the type
textField1

veuillez trouver ci-dessous le code complet :


public class Test1 extends JFrame {

	private static final long serialVersionUID = 1L;	

	public enum FileParser {		
		
		  CPV1("MAP", "(?<vrd>vrd-\\d+)\\s+(?<type>[$\\w]+)", (matcher) -> "(vrd name" + matcher.group("vrd") + "type=" + matcher.group("type") + ")\n"),
                   // ......
                  CPV20("MAP", "(?<vrd>vrd-\\d+)\\s+(?<type>[$\\w]+)", (matcher, values) -> "(vrd name" + matcher.group("vrd") + "type=" + matcher.group("type") + ") 
                 // " + values[0]*2 + "// " + (values[0]+10) + "\n"),
                  CPV21("MAP", "(?<vrd>vrd-\\d+)\\s+(?<type>[$\\w]+)", (matcher, values) -> "(vrd name" + matcher.group("vrd") + "type=" + matcher.group("type") + ") 
                 // " + values[1]*2 + "// " + (values[1]+10) + "\n");

		    private final String delimiter;
		    private final String regex;
		    private final BiFunction<Matcher, String[], String> matcherFunction;

		    private FileParser(String delimiter, String regex, BiFunction<Matcher, String[], String> matcherFunction) {
		        this.delimiter = delimiter;
		        this.regex = regex;
		        this.matcherFunction = matcherFunction;
		        
		    }
		        
		  private FileParser(String delimiter, String regex, Function<Matcher, String> matcherFunction) {
		        this(delimiter, regex, (matcher, values) -> matcherFunction.apply(matcher));
		    }
		}

	public Test1(){
		// NORTH
		JPanel buttonsPanel = new JPanel();
		buttonsPanel.setLayout(new GridLayout(5, 8));
		ButtonGroup buttonGroup = new ButtonGroup();
		EnumMap<FileParser, JRadioButton> buttons = new EnumMap<>(FileParser.class);
		for (FileParser parser : FileParser.values()) {
			JRadioButton button = new JRadioButton(parser.name());
			buttonGroup.add(button);
			buttons.put(parser, button);
			buttonsPanel.add(button);
		}
		add(buttonsPanel, BorderLayout.NORTH);

		// CENTER
		JScrollPane scrollPane = new JScrollPane();
		TextArea textArea = new TextArea();
		scrollPane.setViewportView(textArea_1);
		add(scrollPane, BorderLayout.CENTER);
		
		JPanel south = new JPanel(new GridLayout(1, 3));
		JTextField textField1 = new JTextField();
		JTextField textField2 = new JTextField();
		south.add(textField1);
		south.add(textField2);

		// SOUTH
		JButton btnrun = new JButton("RUN");
		btnrun.setFont(new Font("Tahoma", Font.BOLD, 12));
		btnrun.addActionListener(e -> {
			buttons.forEach((parser, button) -> {
				
				
				if (button.isSelected()) {
					
					readFile(parser, textArea, textField, textField1);
				}
			});
		});
		getContentPane().add(btnrun);
		south.add(btnrun);
		add(south, BorderLayout.SOUTH); 

		// COMMON
		setTitle("TESTS");
		pack();
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setLocationRelativeTo(null);
		setVisible(true);
	}

	private void readFile(FileParser parser, TextArea textArea) {
		
		System.out.println("readFile " + parser + " : START");
		final JFileChooser chooser = new JFileChooser();
		chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		chooser.setMultiSelectionEnabled(false);
		if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
			File file = chooser.getSelectedFile();
			System.out.println("readFile " + parser + " : " + file.getAbsolutePath());
			
			String[] values = {textField.getText(), textField1.getText()};
			
			try (Scanner scanner = new Scanner(file)) {
				
				scanner.useDelimiter(parser.delimiter);
				
				while (scanner.hasNext()) {
					
					
					Matcher matcher = Pattern.compile(parser.regex).matcher(scanner.next());
					
					while (matcher.find()) {
						
					    textArea.settext(parser.matcherFunction.apply(matcher, values));
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				JOptionPane.showMessageDialog(this, e.getMessage(), e.getClass().getSimpleName(),
						JOptionPane.ERROR_MESSAGE);
			}
		}
		System.out.println("readFile " + parser + " : FINISH");
	}

	public static void main(String[] args) {
		new Test1().setVisible(true);
	}
}


merci
0
KX Messages postés 16733 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 31 janvier 2024 3 015
6 août 2020 à 14:02
Tu ne peux pas écrire
values[0]*2
ou
values[0]+10 
alors que values[0] est un String.
Il faut faire les conversions en int avec Integer.parseInt

Quant à la méthode readFile il faut lui ajouter les deux paramètres JTextField :
private void readFile(FileParser parser, TextArea textArea, JTextField textField, JTextField textField1) {
0
SALUT KX:

le nécessaire a été fait et ça marche bien merci beaucoup , mais à chaque fois d'autre questions s'imposent .

j'ai deux questions:

1/ comment ajouter un entête pour chaque bouton quand je clic sur ce dernier et l'afficher dans le texteArea.

private enum FileParser {
        CPV1("MAP", '' !!!!!  START CPV1 !!!! +"\n"+ "(?<vrd>vrd-\\d+)\\s+(?<type>[$\\w]+)", matcher -> "(vrd name" + matcher.group("vrd") + "type=" + matcher.group("type") + "\n)"), //
        CPV2("MAP", '' !!!!!  START CPV2 !!!! +"\n"+ "(?<vrd>vrd-\\d+)\\s+)", matcher -> "(vrd name" + matcher.group("vrd") + "\n)"), //



2/ Est ce qu'il y a un astuce quand je met rien dans l'un des deux textfield && textfield1 ,quand je clic sur CPV20 ou CPV21.
cette Erreur de compilation ne s'affiche plus ( ignorer l'erreur et continuer l'exécution ).

java.lang.NumberFormatException: For input string: "" 


j'ai commencer par ça :

		if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
			File file = chooser.getSelectedFile();
			System.out.println("readFile " + parser + " : " + file.getAbsolutePath());

			String[] values = { textField.getText(), textField1.getText() };
			if  (textField.getText().trim().equals(""))
			{	
				JOptionPane.showMessageDialog(null, "Please enter Value");
					} else {
						if  (textField1.getText().trim().equals(""))
							JOptionPane.showMessageDialog(null, "Please enter Value");		
					}

			try (Scanner scanner = new Scanner(file)) {

				scanner.useDelimiter(parser.delimiter);

				while (scanner.hasNext()) {



merci
0
salut KX:

juste une petite addition pour deuxième question :

il y a une fonction dans delphi (StrToIntDef ) , est ce que java a une fonction similaire ?

merci
0
KX Messages postés 16733 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 31 janvier 2024 3 015
10 août 2020 à 13:17
Pour la première question, il faut enrichir l'enum avec l'en-tête que tu souhaites afficher.
private enum FileParser {
        CPV1("header1", ...),
        CPV2("header2", ...);

     private final String header;

     private FileParser(String header, ...) {
          this.header = header;
          ...
     }
		        
     public String getHeader(){
          return header;
     }
}

Il s'agit ensuite de récupérer ton en-tête au moment où tu appuies sur le bouton :
private void readFile(FileParser parser, TextArea textArea) {
    System.out.println("readFile " + parser + " : START");
    textArea.append(parser.getHeader());
    ...
}

Quant à la deuxième quesion, ce qui se rapproche le plus de StrToIntDef c'est Integer.parseInt mais elle ne couvre pas tout les cas, tu peux très bien te faire une méthode qui le fait pour toi.
public static int toInt(String str) {
    try {
        return Integer.parseInt(str);
    } catch (RuntimeException e) {
        System.err.println(e);
        return 0; // par défaut
    }
}
0
Seifou43 Messages postés 7 Date d'inscription jeudi 2 juillet 2020 Statut Membre Dernière intervention 15 août 2020
10 août 2020 à 16:10
salut kx:

1000 merci pour votre support ça marche bien .
0