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

AWT/Swing Java Discussion :

Numéros de lignes dans un JTextArea


Sujet :

AWT/Swing Java

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre averti
    Profil pro
    Inscrit en
    Juin 2005
    Messages
    13
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2005
    Messages : 13
    Par défaut Numéros de lignes dans un JTextArea
    Bonjour.
    J'ai un JTextArea nommé textArea. J'aimerais avoir une barre ou quelque chose du genre (comme dans l'IDE NetBeans) qui me nummérote les lignes.
    Comme puis-je faire ? Je n'ais pas d'idée et je ne vois du tout.
    Merci d'avance.

    La source:
    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
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    /*
     * fenetre.java
     *
     * Created on 4 juillet 2006, 16:23
     *
     * To change this template, choose Tools | Template Manager
     * and open the template in the editor.
     */
     
    package notepad;
     
    import javax.swing.*;
    import java.awt.*;
    import java.awt.print.*;
    import java.awt.event.*;
    import java.io.*;
    import java.awt.print.*;
     
    import notepad.perifs.*;
    import notepad.perifs;
     
    //import notepad.events.;
     
    /**
     *
     * @author razord
     */
    public class fenetre{
     
        public static JTextArea textArea = new JTextArea();
        public static JFrame frame = new JFrame("Notepad");
     
        /** Creates a new instance of fenetre */
        public static void nouvelle_fenetre(){
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
     
            //Create and set up the window.
     
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
            //Add and set up the scroll pane (for textArea).
            JScrollPane scrollPane = new JScrollPane(textArea);
            scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
            scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
            frame.getContentPane().add(scrollPane);
     
            //Create menus's variables.
            JMenuBar menuBar;
            JMenu menuFichier, menuEdition, menuAffichage;
            JMenuItem menuSave, menuLoad, menuQuit, menuFontSize, menuFontType, menuPrint, menuLine;
            JCheckBoxMenuItem cbLineWrap, cbLineCounter;
     
     
            /*
             *MENU******************************************************************
             */
            //Create menus
            menuBar = new JMenuBar();
     
            //Build the FILE menu.
            menuFichier = new JMenu("Fichier");
            menuFichier.setMnemonic(KeyEvent.VK_F);
            menuBar.add(menuFichier);
     
            //Build the EDIT menu.
            menuEdition = new JMenu("Edition");
            menuEdition.setMnemonic(KeyEvent.VK_E);
            menuBar.add(menuEdition);
     
            //Build the VIEW menu.
            menuAffichage = new JMenu("Affichage");
            menuAffichage.setMnemonic(KeyEvent.VK_A);
            menuBar.add(menuAffichage);
     
            //Save menu
            menuSave = new JMenuItem("Sauvegarder");
            menuFichier.add(menuSave);
     
            //Load menu
            menuLoad = new JMenuItem("Charger");
            menuFichier.add(menuLoad);
     
            //Separator
            menuFichier.addSeparator();
     
            //Quit menu
            menuQuit = new JMenuItem("Quitter");
            menuFichier.add(menuQuit);
     
            //Print menu
            menuPrint = new JMenuItem("Imprimmer");
            menuEdition.add(menuPrint);
     
            //FontType menu
            menuFontType = new JMenuItem("Police");
            menuAffichage.add(menuFontType);
     
            //Wrap menu
            cbLineWrap = new JCheckBoxMenuItem("Retour à la ligne automatique");
            menuAffichage.add(cbLineWrap);
     
            cbLineCounter = new JCheckBoxMenuItem("Afficher les numéros de lignes");
            menuAffichage.add(cbLineCounter);
     
            //Add menubar to the frame
            frame.setJMenuBar(menuBar);
     
            /*
             *******************************************************************MENU
             *EVENTS****************************************************************
             */
            menuQuit.addActionListener(
                        new ActionListener() { 
                            public void actionPerformed(ActionEvent e) {
                                System.exit(0);
                            }
                        }
                    );
     
            menuFontType.addActionListener(
                        new ActionListener(){
                            public void actionPerformed(ActionEvent e){
                                Font font = textArea.getFont();
                                String fontName = JOptionPane.showInputDialog(null,"Nom de la police:",font.getName());
                                String fontStyle = JOptionPane.showInputDialog(null, "Style de la police:",font.getStyle());
                                String fontsize = JOptionPane.showInputDialog(null, "Taille de la police:", font.getSize());
                                Font newFont = new Font(fontName, Integer.parseInt(fontStyle), Integer.parseInt(fontsize));
                                textArea.setFont(newFont);
                            }
                        }
                    );
     
            cbLineWrap.addItemListener(
                        new ItemListener(){
                            public void itemStateChanged(ItemEvent e){
                                if(e.getStateChange() == ItemEvent.DESELECTED){
                                    textArea.setLineWrap(false);
                                    textArea.setWrapStyleWord(false);
                                }
                                if(e.getStateChange() == ItemEvent.SELECTED){
                                    textArea.setLineWrap(true);
                                    textArea.setWrapStyleWord(true);
                                }
                            }
                        }
                    );
     
            menuPrint.addActionListener(
                        new ActionListener(){
                            public void actionPerformed(ActionEvent e){
                                PrinterJob tache = PrinterJob.getPrinterJob();
                                //tache.setPrintable(new perifs.perifs("Ceci est un teste d?impression en java!"));
        //printDialog affiche la fenetre de sélection de l?imprimante, etc...
        //il retourne true si on clique sur "Ok", false si on clique sur "Annuler"
                                if(! tache.printDialog()) return;
                                try {
                                    tache.print();
                                } catch(Exception ep) {
                                    System.out.println("impossible d?imprimer");
                                }
                            }
                        }
                    );
     
            menuLoad.addActionListener(
                        new ActionListener(){
                            public void actionPerformed(ActionEvent e){
                                JFileChooser choix = new JFileChooser();
                                int retour = choix.showOpenDialog(frame);
                                if(retour == JFileChooser.APPROVE_OPTION) {
                                    choix.getSelectedFile().getName();       // nom du fichier 
                                    String chemin_use = choix.getSelectedFile().getAbsolutePath();// chemin absolu du
                                    BufferedReader lecteurAvecBuffer = null;
                                    String ligne;
                                    try {
                                        lecteurAvecBuffer = new BufferedReader(new FileReader(chemin_use));
                                        while ((ligne = lecteurAvecBuffer.readLine()) != null)
                                            textArea.setText(textArea.getText()+"\n"+ligne);
                                        lecteurAvecBuffer.close();
                                    }
                                    catch(java.io.IOException exc)
                                    {
                                        System.out.println("Erreur d'utilisation du fichier");
                                    }
                                } else ;
                            }
                        }
                    );
     
            menuSave.addActionListener(
                        new ActionListener(){
                            public void actionPerformed(ActionEvent e){
                                JFileChooser choix = new JFileChooser();
                                int retour = choix.showSaveDialog(frame);
                                if(retour == JFileChooser.APPROVE_OPTION) {
                                    choix.getSelectedFile().getName();       // nom du fichier 
                                    String chemin_use = choix.getSelectedFile().getAbsolutePath();// chemin absolu du
                                    PrintWriter ecrivain;
                                    String ligne;
                                    try {
                                        ecrivain =  new PrintWriter(new BufferedWriter(new FileWriter(chemin_use)));
                                        ecrivain.print(textArea.getText());
                                        ecrivain.close();
                                    }
                                    catch(java.io.IOException exc)
                                    {
                                        System.out.println("Erreur d'utilisation du fichier");
                                    }
                                } else ;
                            }
                        }
                    );
     
            /*
             *****************************************************************EVENTS
             */
     
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        }
    }
     
    class perifs implements Printable
    {
        String phrase;
     
        public void perifs(String phrase)
        {
            this.phrase = phrase;
        }
     
        public int print(Graphics g, PageFormat pf, int indexPage)
        {
            if(indexPage > 0) return NO_SUCH_PAGE;
            Graphics2D g2 = (Graphics2D)g;
            g2.setPaint(Color.blue);
            g2.setFont(new Font("Serif", Font.PLAIN, 64));
            g2.drawString(phrase, 96, 144);
            return PAGE_EXISTS;
        }
    }

  2. #2
    Membre averti
    Profil pro
    Inscrit en
    Juin 2005
    Messages
    13
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2005
    Messages : 13
    Par défaut
    C'est bon j'ai trouvé la réponse:
    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
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    /*
     * fenetre.java
     *
     * Created on 4 juillet 2006, 16:23
     *
     * To change this template, choose Tools | Template Manager
     * and open the template in the editor.
     */
     
    package notepad;
     
    import javax.swing.*;
    import java.awt.*;
    import java.awt.print.*;
    import java.awt.event.*;
    import java.io.*;
    import java.awt.print.*;
    import javax.swing.Timer;
     
    import notepad.perifs.*;
    import notepad.perifs;
     
    //import notepad.events.;
     
    /**
     *
     * @author razord
     */
    public class fenetre{
     
        public static JTextArea textArea = new JTextArea();
        public static JTextArea lineNumbers = new JTextArea();
        public static JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,lineNumbers, textArea);
        public static JFrame frame = new JFrame("Notepad");
     
        /** Creates a new instance of fenetre */
        public static void nouvelle_fenetre(){
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
     
            //Create and set up the window.
     
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
            //Add and set up the panel
            JPanel p = new JPanel();
            p.setLayout(new BoxLayout(p, BoxLayout.LINE_AXIS));
     
            //Set up the line number
            lineNumbers.setSize(50,frame.getHeight());
     
            //Add splitpane to panel
            p.add(splitPane);
     
            //Add and set up the scroll pane (for textArea).
            JScrollPane scrollPane = new JScrollPane(p);
            scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
            scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
            frame.getContentPane().add(scrollPane);
     
            //Create menus's variables.
            JMenuBar menuBar;
            JMenu menuFichier, menuEdition, menuAffichage;
            JMenuItem menuSave, menuLoad, menuQuit, menuFontSize, menuFontType, menuPrint, menuLine;
            JCheckBoxMenuItem cbLineWrap, cbLineCounter;
     
     
            /*
             *MENU******************************************************************
             */
            //Create menus
            menuBar = new JMenuBar();
     
            //Build the FILE menu.
            menuFichier = new JMenu("Fichier");
            menuFichier.setMnemonic(KeyEvent.VK_F);
            menuBar.add(menuFichier);
     
            //Build the EDIT menu.
            menuEdition = new JMenu("Edition");
            menuEdition.setMnemonic(KeyEvent.VK_E);
            menuBar.add(menuEdition);
     
            //Build the VIEW menu.
            menuAffichage = new JMenu("Affichage");
            menuAffichage.setMnemonic(KeyEvent.VK_A);
            menuBar.add(menuAffichage);
     
            //Save menu
            menuSave = new JMenuItem("Sauvegarder");
            menuFichier.add(menuSave);
     
            //Load menu
            menuLoad = new JMenuItem("Charger");
            menuFichier.add(menuLoad);
     
            //Separator
            menuFichier.addSeparator();
     
            //Quit menu
            menuQuit = new JMenuItem("Quitter");
            menuFichier.add(menuQuit);
     
            //Print menu
            menuPrint = new JMenuItem("Imprimmer");
            menuEdition.add(menuPrint);
     
            //FontType menu
            menuFontType = new JMenuItem("Police");
            menuAffichage.add(menuFontType);
     
            //Wrap menu
            cbLineWrap = new JCheckBoxMenuItem("Retour à la ligne automatique");
            menuAffichage.add(cbLineWrap);
     
            cbLineCounter = new JCheckBoxMenuItem("Afficher les numéros de lignes");
            cbLineCounter.setSelected(true);
            menuAffichage.add(cbLineCounter);
     
            //Add menubar to the frame
            frame.setJMenuBar(menuBar);
     
            /*
             *******************************************************************MENU
             *EVENTS****************************************************************
             */
            menuQuit.addActionListener(
                        new ActionListener() { 
                            public void actionPerformed(ActionEvent e) {
                                System.exit(0);
                            }
                        }
                    );
     
            menuFontType.addActionListener(
                        new ActionListener(){
                            public void actionPerformed(ActionEvent e){
                                Font font = textArea.getFont();
                                String fontName = JOptionPane.showInputDialog(null,"Nom de la police:",font.getName());
                                String fontStyle = JOptionPane.showInputDialog(null, "Style de la police:",font.getStyle());
                                String fontsize = JOptionPane.showInputDialog(null, "Taille de la police:", font.getSize());
                                Font newFont = new Font(fontName, Integer.parseInt(fontStyle), Integer.parseInt(fontsize));
                                textArea.setFont(newFont);
                            }
                        }
                    );
     
            cbLineWrap.addItemListener(
                        new ItemListener(){
                            public void itemStateChanged(ItemEvent e){
                                if(e.getStateChange() == ItemEvent.DESELECTED){
                                    textArea.setLineWrap(false);
                                    textArea.setWrapStyleWord(false);
                                }
                                if(e.getStateChange() == ItemEvent.SELECTED){
                                    textArea.setLineWrap(true);
                                    textArea.setWrapStyleWord(true);
                                }
                            }
                        }
                    );
     
             cbLineCounter.addItemListener(
                        new ItemListener(){
                            public void itemStateChanged(ItemEvent e){
                                if(e.getStateChange() == ItemEvent.DESELECTED){
                                    lineNumbers.setVisible(false);
                                }
                                 if(e.getStateChange() == ItemEvent.SELECTED){
                                    lineNumbers.setVisible(true);
                                }
                            }
                        }
                     );
     
            menuPrint.addActionListener(
                        new ActionListener(){
                            public void actionPerformed(ActionEvent e){
                                PrinterJob tache = PrinterJob.getPrinterJob();
                                //tache.setPrintable(new perifs.perifs("Ceci est un teste d?impression en java!"));
        //printDialog affiche la fenetre de sélection de l?imprimante, etc...
        //il retourne true si on clique sur "Ok", false si on clique sur "Annuler"
                                if(! tache.printDialog()) return;
                                try {
                                    tache.print();
                                } catch(Exception ep) {
                                    System.out.println("impossible d?imprimer");
                                }
                            }
                        }
                    );
     
            menuLoad.addActionListener(
                        new ActionListener(){
                            public void actionPerformed(ActionEvent e){
                                JFileChooser choix = new JFileChooser();
                                int retour = choix.showOpenDialog(frame);
                                if(retour == JFileChooser.APPROVE_OPTION) {
                                    choix.getSelectedFile().getName();       // nom du fichier 
                                    String chemin_use = choix.getSelectedFile().getAbsolutePath();// chemin absolu du
                                    BufferedReader lecteurAvecBuffer = null;
                                    String ligne;
                                    try {
                                        lecteurAvecBuffer = new BufferedReader(new FileReader(chemin_use));
                                        while ((ligne = lecteurAvecBuffer.readLine()) != null)
                                            textArea.setText(textArea.getText()+"\n"+ligne);
                                        lecteurAvecBuffer.close();
                                    }
                                    catch(java.io.IOException exc)
                                    {
                                        System.out.println("Erreur d'utilisation du fichier");
                                    }
                                } else ;
                            }
                        }
                    );
     
            menuSave.addActionListener(
                        new ActionListener(){
                            public void actionPerformed(ActionEvent e){
                                JFileChooser choix = new JFileChooser();
                                int retour = choix.showSaveDialog(frame);
                                if(retour == JFileChooser.APPROVE_OPTION) {
                                    choix.getSelectedFile().getName();       // nom du fichier 
                                    String chemin_use = choix.getSelectedFile().getAbsolutePath();// chemin absolu du
                                    PrintWriter ecrivain;
                                    String ligne;
                                    try {
                                        ecrivain =  new PrintWriter(new BufferedWriter(new FileWriter(chemin_use)));
                                        ecrivain.print(textArea.getText());
                                        ecrivain.close();
                                    }
                                    catch(java.io.IOException exc)
                                    {
                                        System.out.println("Erreur d'utilisation du fichier");
                                    }
                                } else ;
                            }
                        }
                    );
     
            int delay = 500;
            Timer refreshLines = new Timer(delay,
                        new ActionListener(){
                            public void actionPerformed(ActionEvent e){
                                lineNumbers.setText("");
                                int nombrelignes = textArea.getLineCount();
                                int i;
                                for(i = 1; i <= nombrelignes; i++){
                                    if(nombrelignes != 0){
                                        lineNumbers.setText(lineNumbers.getText()+i+"\n");
                                    }
                                }
                            }
                        }
                    );  
             refreshLines.start();
     
            /*
             *****************************************************************EVENTS
             */
     
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        }
    }
     
    class perifs implements Printable
    {
        String phrase;
     
        public void perifs(String phrase)
        {
            this.phrase = phrase;
        }
     
        public int print(Graphics g, PageFormat pf, int indexPage)
        {
            if(indexPage > 0) return NO_SUCH_PAGE;
            Graphics2D g2 = (Graphics2D)g;
            g2.setPaint(Color.blue);
            g2.setFont(new Font("Serif", Font.PLAIN, 64));
            g2.drawString(phrase, 96, 144);
            return PAGE_EXISTS;
        }
    }

  3. #3
    Membre émérite
    Avatar de bbclone
    Profil pro
    Inscrit en
    Mai 2006
    Messages
    537
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Mai 2006
    Messages : 537
    Par défaut
    bonjour razord :-)
    je voit que tu a resolu ton probleme mais la facon comment tu la fait c'est pas une pratique souvent utiliser.


    faire ca
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    public static JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,lineNumbers, textArea);
    et ensuite un Thread pour mettre a jour ls numero
    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
     
    int delay = 500;
    Timer refreshLines = new Timer(delay,
         new ActionListener(){
           public void actionPerformed(ActionEvent e){
               lineNumbers.setText("");
               int nombrelignes = textArea.getLineCount();
               int i;
               for(i = 1; i <= nombrelignes; i++){
                   if(nombrelignes != 0){
                        lineNumbers.setText(lineNumbers.getText()+i+"\n");
                   }
               }
            }
         }
    );  
    refreshLines.start();
    c'est pas courant comme truc


    ce que je te propose c'est une methode plus simple plus facile a comprendre et plus facile a etendre (si tu veut a cote des numero de ligne une petite image pour marquer un bookmark par exempe ou n'importe quoi :-)
    je change juste le viewport pour afficher un panel que je crer juste avant avec sur le cote une JTable (celle la va contenir les numero de ligne) et a cote de la JTable un JTextArea.

    un petit exemple de test :-))

    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
     
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextArea;
    import javax.swing.table.AbstractTableModel;
    import java.awt.BorderLayout;
    import java.awt.EventQueue;
    import java.awt.Color;
     
    /**
     * This class is an extended scrollPane showing line numbers for <code>JTextArea</code>. <br/>
     * Here is a common use of <code>JTextArea</code>.
     * <code>
     * aContainer.add(new JScrollPane(new JTextArea()));
     * </code>
     * The textarea is almost never directly added to the container but first it's been added to a 
     * scrollPane.
     * <br/> 
     * But this would never display line numbers (scrollPanes can be used for all kind of components).<br/>
     * <br/>
     * Now if you want line numbers, this class is for you. You can use it like this:
     * <code>
     * aContainer.add(new JNumberedScrollPane(new JTextArea()));
     * </code>
     *
     * @author bebe
     */
    public class JNumberedScrollPane extends JScrollPane {
     
       private JTextArea view = null;
       private JTable lineNumbersTable = null;
       private int lineCount = 0;
     
       public JNumberedScrollPane(JTextArea textArea) {
           view = textArea;
           lineNumbersTable = new JTable();
           lineNumbersTable.setModel(new AbstractTableModel() {
     
               /* implemented method from TableModel */
               public int getColumnCount() {
                   // only one column
                   return 1;
               }
     
               /* implemented method from TableModel */
               public int getRowCount() {
                   if (lineCount != view.getLineCount()) {
                       /*
                         each 10-power update the width
                         10^1 = 10
                         10^2 = 100
                         10^3 = 1000
                         ...
                       */
                       int power = (int) (Math.log(view.getLineCount()) / Math.log(10)) + 1;
                       /*
                         ...
                         however, fix at least a minimum width of 2 chars.
                         (the first time width is updated will be at 100).
                       */
                       power = (power <= 2)?2:power;
                       // on the next line, 5 is the margin between to the border ;-)
                       int preferredWidth = power * view.getFontMetrics(view.getFont()).getWidths()['0'] + 5;
     
                       lineNumbersTable.getColumnModel().getColumn(0).setPreferredWidth(preferredWidth);
                       lineNumbersTable.repaint();
                       lineCount = view.getLineCount();
                   }
                   return view.getLineCount();
               }
     
               /* implemented method from TableModel. */
               public Object getValueAt(int rowIndex, int columnIndex){
                   return rowIndex + 1;  // rowIndex is 0-based.
               }
           });
     
           lineNumbersTable.setFont(view.getFont());
           // use the same font height for line numbers that for the view ;-)
           lineNumbersTable.setRowHeight(view.getFontMetrics(view.getFont()).getHeight());
           // define a background and a foregroud color for table.
           lineNumbersTable.setBackground(new Color(255,255,225));
           lineNumbersTable.setForeground(view.getForeground());
           // do not show the grid or each "line number" would be put a border around  and at last disable the table.
           lineNumbersTable.setShowGrid(false);
           lineNumbersTable.setEnabled(false);
     
           JPanel viewPort = new JPanel(new BorderLayout());
           viewPort.add(view);
           viewPort.add(lineNumbersTable, BorderLayout.LINE_START);
           setViewportView(viewPort);
       }
     
       /**
        *
        * @param args
        */
       public static void main(String[] args) {
     
           EventQueue.invokeLater(new Runnable() {
               public void run() {
                   JFrame f = new JFrame("Numbered textarea...");
                   f.add(new JNumberedScrollPane(new JTextArea()));
                   f.setSize(400, 300);
                   f.setLocationRelativeTo(null);
                   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   f.setVisible(true);
               }
           });
       }
    }
    (si tu enleve les comentaire le code fait presque rien ;-) )

    une autre petite remarque
    met le premier caracter du nom de classe en Majuscule et essaye d'utiliser la meme indentation partout. c'est plus facile a lire seulement :-)

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. [Swing]Retour à la ligne dans un JTextArea
    Par Nasky dans le forum AWT/Swing
    Réponses: 7
    Dernier message: 09/03/2006, 20h02
  2. Réponses: 2
    Dernier message: 03/11/2005, 11h49
  3. Rajouter les numéros de ligne dans une colone d'une requete
    Par AntiSAL dans le forum MS SQL Server
    Réponses: 7
    Dernier message: 02/11/2005, 19h07
  4. numéros de lignes dans visual c++
    Par heider dans le forum MFC
    Réponses: 7
    Dernier message: 24/08/2005, 14h06
  5. Afficher le numéro de ligne dans une requete SELECT
    Par tilb dans le forum Langage SQL
    Réponses: 4
    Dernier message: 01/09/2004, 10h20

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