Selection problem in JTextArea

hi all
i have a TextArea in which i have some coded charecters in a group of ten charactes i treet these ten characters as a single character ,so when i delete or insert these charactes all these charactes r deleted and no other character r inserted in between , i do it with the caretListener,
But the problem which i face is on the selection i want to select these characters as when we select some part of the URL then it is selected completely.
help in the prob.

this might work
paste some text into the textArea (ensure it contains a sequence "12345")
click anywhere in area of 12345
import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
class Testing extends JFrame
  String specialChars = "12345";
  boolean settingCaret = false;
  public Testing()
    setSize(200,200);
    setLocation(300,200);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    final JTextArea ta = new JTextArea(10,10);
    JScrollPane sp = new JScrollPane(ta);
    sp.setPreferredSize(new Dimension(175,150));
    JPanel jp = new JPanel();
    jp.add(sp);
    getContentPane().add(jp);
    pack();
    ta.addCaretListener(new CaretListener(){
      public void caretUpdate(CaretEvent ce){
        if(settingCaret == false)
          int startPos = ta.getText().indexOf(specialChars);
          if(startPos > -1)
            if(ta.getCaretPosition() >= startPos && ta.getCaretPosition() <= startPos+specialChars.length())
              settingCaret = true;
              ta.setSelectionStart(startPos);
              ta.setSelectionEnd(startPos+specialChars.length());
            settingCaret = false;
  public static void main(String[] args){new Testing().setVisible(true);}
}

Similar Messages

  • Selection Problem with JTable

    Hello,
    i have a selection problem with JTable. I want to allow only single cell selection and additionally limit the selection to the first column.
    I preffered the style from MS Outlook Express where you can select the email accounts to edit.
    It is a table like this:
    Account name  |   Type  |   ...
    --------------|---------|---------------------
    Hotmail       |   POP3  |
    GMX           |   IMAP  |The selection should be only avaibable at 'Hotmail' or 'GMX' - not at 'POP3', 'IMAP' or as complete row selection.
    Please help me!
    Thanks.
    Warlock

    Maybe this will helpimport java.awt.*;
    import javax.swing.*;
    public class Test3 extends JFrame {
      public Test3() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = getContentPane();
        String[] head = {"One", "Two"};
        String[][] data = {{"R1-C1", "R1-C2"}, {"R2-C1", "R2-C2"}};
        JTable jt = new JTable(data, head);
        jt.getColumnModel().setSelectionModel(new MyTableSelectionModel());
        content.add(new JScrollPane(jt), BorderLayout.CENTER);
        jt.setCellSelectionEnabled(true);
        jt.setRowSelectionAllowed(false);
        jt.setColumnSelectionAllowed(false);
        setSize(300, 300);
        setVisible(true);
      public static void main(String[] arghs) { new Test3(); }
    class MyTableSelectionModel extends DefaultListSelectionModel {
      public void setSelectionInterval(int index0, int index1) {
        super.setSelectionInterval(0, 0);
    }

  • How to write selected text in JTextArea in selected location

    iam using JTextArea ...
    i want to writer selected text in selected location,,,,,,

    use
    JTextArea.getSelectedText() and
    JTextArea.replaceRange(String str, int start, int end)
    methods.

  • Problem using JTextArea

    Hi!
         I' ve a problem using JTextArea. I'm trying to discuss in a brief.....
    I've created an application that is used as a front end for a SQL database application.
    There is a text area (JTextArea). Clicking on a button, what I enter in the text area would be saved into the database. As well as, the text area would be used to display the data (a few line) that the database already contains. That is to say, that a user can edit new text to store into the database and modify older text that is already stored in the database.
    A line the text area would contain could be as long
    as this line.
    Or, a line may be long like this.
    < There may be a gap / empty line >
         A line may be start & end in these positions.
    figure: a text area (JTextArea)
    Suppose that someone used this text area to edit a few lines as the figure displays.
    Now, the next time when he will return here after doing some other tasks with this application or, after reopening the application; the text area should display the entire text the database contains in the format it was edited (See the figure).
    But, I failed to do all the things I sated above! (Except the job with database)
    I don't have any problem in database connectivity or getting the text (String) a database contains.
    Would you please send me a code that explains how to achieve the things I need?
    Please........

    Hellow again !
    Your suggestion to use the methd trim() did not help to the problem I mentioned. But you would be glad to know that the method solve the another problem I had.
    But !...but I' m still in the same condition.
    Well, Canad! I think the another one you said the 'padding' is unable to work successfully as the text area and hereafter the database would contain multiple lines and not only one line. Because, after editing one line if I fill the rest of the space ( space to store string / text in a column of the database ) then where the other lines that would be entered into the text area would be stored ?! (See your suggestion 'padding')
    I can not find out anything & I'm getting tired. Would you do something at my request ?
    Please...Please...Please... send me a code that helps to achieve what the actually I need and ofcourse, explains clearly.

  • Select Problem For 'Back Menus' - Zen V P

    Just got the Zen V Plus and tried to set the time/date. Followed the 'guide' and after the time/date screen pressed the 'back button'. Got the Set Alarm/Date/Time (etc) menu but when I selected an option (moved joystick down to desired option then pressed the joystick) the time/date display came up and I was NOT ABLE to set the date. Same thing occurred trying to set the date (tried it several times and it worked once .... then attempted again - several times (4) but it only worked once). Turns out I have the same problem with any option in ANY 'back' menu. Suggestion?
    Do I have a defecti've unit (can't be the 'operator' who is defecti've! haha)? Should I return it and try another?
    Actually not that interested in playing music .... it's more for playing .wma(DRM) book files.

    Latest ... updated my firmware (to ZENVPlus_PCFW_P4S_L2___0.exe) and it fixed the select problem for SET DATE/TIME etc however
    the SELECT procedure doesn't always work for 'back button' menus. Example: tried to set a bookmark... following procedure in 'guide', pressed 'back button' and held it, from 'NOW PLAYING' screen - works 2 out of 5 times. Most of the time, pressing and holding takes you back to the previous menu - not to the 'back' (or in this case the SET BOOKMARK) menu. Sounds like something for the next version of firmware ... the code doesn't always set an internal timer correctly (am a programmer of 30 years ... part of that time pgmmng firmware).

  • Print selection problem

    when i select a page to be print from my pc the page select in

    Hello. I feel your pain and frustration with the print selection problem in safari, especially in Snow Leopard. I have spent hours trawling help pages and forums etc. BUT YEE HAA (sorry got a bit excited, but it really was hours) I found the answer. So here goes.
    Click on Safari
    Scroll down to services then slide to right
    Scroll down to services preferences and click
    Scroll down to the Text section
    If you Tick the Text box it will choose all options for you. Or if you don't want all options in the Text list, then untick Text box and tick options you do want.
    BUT for your print selection problem make sure you tick NEW TEXT EDIT WINDOW CONTAINING SELECTION.
    Then when you want to select something in a web page you want to print (including pictures etc) then highlight it, then Right click. And low and behold, in the list is NEW TEXT EDIT WINDOW CONTAINING SELECTION. Click that, Then press cmd+p and your printing.
    I really hope that helps with your problem
    I can now go to sleep.

  • At Line selection problem

    hi,
    iam stuck up with AT LINE-SELECTION problem ie i designed a screen where they need month list on clicking F4. i got the month list using month_names_get in the screen but while clicking the relevant month no.it's not entering into the required parameter. i have attached the codings,
    MODULE MONTH_DIS OUTPUT.
      SUPPRESS DIALOG.
      LEAVE TO LIST-PROCESSING AND RETURN TO SCREEN 0.
      SET PF-STATUS SPACE.
      NEW-PAGE NO-TITLE.
      WRITE:/ 'SELECT MONTH' COLOR COL_HEADING.
      ULINE.
      DATA: T_MNTH LIKE T247 OCCURS 12 WITH HEADER LINE.
      refresh t_mnth.
      CALL FUNCTION 'MONTH_NAMES_GET'
       EXPORTING
         LANGUAGE                    = SY-LANGU
    IMPORTING
      RETURN_CODE                 =
        TABLES
          MONTH_NAMES                 = T_MNTH
       EXCEPTIONS
         MONTH_NAMES_NOT_FOUND       = 1
         OTHERS                      = 2
      IF SY-SUBRC <> 0.
        MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
                WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
      ENDIF.
      loop at t_mnth.
        write:/ t_mnth-mnr, t_mnth-ltx.
      endloop.
      CLEAR T_MNTH-MNR.
    ENDMODULE.                 " MONTH_DIS  OUTPUT
    AT LINE-SELECTION.
      p_period = t_mnth-mnr.
      CHECK NOT p_period IS INITIAL.
      LEAVE TO SCREEN 0.
    here in the AT LINE-SELECTION, the selected month is not coming to the required parameter.
    pls help me in this issue,
    Thanks in advance,
    Premnath.

    You need to set a "Hide" after the write... I suggest you also set your own dialog PF-STATUS too so you can have just a PF2 "pick" button and a Cancel button ( this will look better to the user).
    loop at t_mnth.
      write:/ t_mnth-mnr, t_mnth-ltx.
      hide: t_mnth.  "needs this
    endloop.
    clear: t_mnth.

  • Weird BGP path selection problem

    Hi, all,
    I am seeing a weird BGP path selection problem on 4948 switch running cat4500-entservicesk9-mz.122-46.SG.bin code, this switch has two uplinks to the same ISP's different edge router, one circuit is primary the other one is strict backup, only default route is accepted from ISP. I am setting both local preference and weight to the default route advertised over backup link, however neither one is taking effect, BGP still thinks the backup link is better, what could be wrong?
    rtr#sh ip bgp 0.0.0.0/0
    BGP routing table entry for 0.0.0.0/0, version 105
    Paths: (3 available, best #2, table Default-IP-Routing-Table, not advertised to EBGP peer)
      Not advertised to any peer
      17675, (received & used)
        203.169.8.37 from 203.169.8.37 (61.211.160.150)
          Origin IGP, localpref 100, valid, external
          Community: 65001:0 no-export
      17675
        203.169.8.45 from 203.169.8.45 (61.211.160.151)
          Origin IGP, localpref 90, weight 90, valid, external, best <====
          Community: 65001:0 no-export
      17675, (received-only)
        203.169.8.45 from 203.169.8.45 (61.211.160.151)
          Origin IGP, localpref 100, valid, external
          Community: 65001:0 no-export
    Thanks

    Hi,
    On cisco routers , weight is having highest preference to decide best path. By default for received route, weight is 0 but you are setting weight 90 to backup path and that is why it is getting preferred (higher is better). Please remove weight and let local preference be 90 (lesser than route on primary path)
    --Pls dont forget to rate helpful posts--
    Regards,
    Akash

  • Certificate selection problem in Safari

    Hi ,
    I have certifcates A,B,C,D for the same site , whenever i use the Mozilla it is asking which one to select , but somehow i dont know why Safari is asking the same option.
    It is forcing me to accept Certifcate A to that paricular site. How to solve this problem in safari.
    Regards
    Vikranth

    Hello. I feel your pain and frustration with the print selection problem in safari, especially in Snow Leopard. I have spent hours trawling help pages and forums etc. BUT YEE HAA (sorry got a bit excited, but it really was hours) I found the answer. So here goes.
    Click on Safari
    Scroll down to services then slide to right
    Scroll down to services preferences and click
    Scroll down to the Text section
    If you Tick the Text box it will choose all options for you. Or if you don't want all options in the Text list, then untick Text box and tick options you do want.
    BUT for your print selection problem make sure you tick NEW TEXT EDIT WINDOW CONTAINING SELECTION.
    Then when you want to select something in a web page you want to print (including pictures etc) then highlight it, then Right click. And low and behold, in the list is NEW TEXT EDIT WINDOW CONTAINING SELECTION. Click that, Then press cmd+p and your printing.
    I really hope that helps with your problem
    I can now go to sleep.

  • Selection problem in rendered JtextArea.

    I create a jtable by rendering one column using jTextarea. While selecting the row, color of selection not geting to the rendered Jtextarea. How can i solve this problem.
    please help me

    Do you include code in your getTableCellRendererComponent method to change
    the color depending on if the row is selected or not? You'll need something like
         if ( isSelected ) {
              setForeground( table.getSelectionForeground() );
              setBackground( table.getSelectionBackground() );
         } else {
              setForeground( table.getForeground() );
              setBackground( table.getBackground() );
         }: jay

  • Select problem in the JTextArea

    Hi
    I have a problem on the select(), I am trying to select multiple lines of text in the JTextArea, but select(int start, int end) can only select single line, int end will be cut to the length of the line instead of going to the next line. Can anyone give me any advice?
    Thanks in advance

    DefaultHighlighter highlighter = (DefaultHighlighter)textArea.getHighlighter();
    highlighter.setDrawsLayeredHighlights(false);

  • Select part of jtextarea content over a button click

    Hi,
    i would like to do something quite simple, but i don't manage to do it and don't understand why my code doesn't work :s
    Actually, i would like to select a part of the text contained in a jtextarea when the user clicks over a jbutton ; here is my code:
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JTextArea;
    public class BasicFrame extends JFrame implements ActionListener {
         private static final long serialVersionUID = 1L;
         private JTextArea jta;
         private JButton b;
         public BasicFrame() {
              this.setSize(400,400);
              this.getContentPane().setLayout(new GridLayout(2,1));
              this.getContentPane().add(this.jta = new JTextArea());
              this.getContentPane().add(this.b = new JButton("foo"));
              this.b.addActionListener(this);
              this.setVisible(true);
              this.setDefaultCloseOperation(EXIT_ON_CLOSE);
              this.setLocationRelativeTo(null);
         @Override
         public void actionPerformed(ActionEvent arg0) {
         //     this.jta.select(2, 5);
              this.jta.setCaretPosition(2);
              this.jta.moveCaretPosition(5);
         public static void main(String [] args) {
              BasicFrame bs = new BasicFrame();
              bs.jta.setText("this crap won t work");
    }notice that this solution doesn't work, but if the "select" (or setcaret+movecaret) instruction is put directly in the main, it will work
    Suggestions? Advices? Answers?
    Thanks in advance!

    the code does work, problem is the textArea needs the focus to show the highlighted (selected) text,
    but when you click the button, focus goes to the button.
    run the code then tab (not click) to the textArea, you will see the text selected
    simple fix is to add this line at the end of the constructor
    b.setFocusable(false);

  • Clipboard Problem in JTextArea

    I am writing a text editor in swing and when i used the system clipboard for my JTextArea, the pop-up menu of cut,copy,paste delete and select all that normally appears in TextArea didn't appear. What could be the possible solution? Please note that when i use TextArea instead of JTextArea, my menubar goes behind the text area, and thus creates problem.
    Could anyone give me a hand please? I would request you to be elaborative and give me some lines of codes if you can find the solution.
    Thanks

    JTextArea by default does not show the drop down menu. You have to trap the right click on the JTextArea and show the JPopupMenu. Also, to enable cut, copy, paste etc.. you have to call the JTextArea.cut(),copy(),paste() and the selectAll() methods on the action event occuring during the menu item selection of your popup menu.
    Cheers

  • Problem with JTextArea or is it my code, Help!!!

    Hi,
    I am going crazy. I am sending a message to a JTextArea and I get some very wierd things happening? I really need help because this is driving me crazy. Please see the following code to see my annotations for the problems. Has anyone else experienced problems with this component?
    Thanks,
    Steve
    // THIS IS THE CLASS THAT HANDLES ALL OF THE WORK
    public class UpdateDataFields implements ActionListener {     // 400
         JTextArea msg;
         JPanel frameForCardPane;
         CardLayout cardPane;
         TestQuestionPanel fromRadio;
         public UpdateDataFields( JTextArea msgout ) {     // 100
              msg = msgout;
          }       // 100
         public void actionPerformed(ActionEvent evt) {     // 200
              String command = evt.getActionCommand();
              String reset = "Test of reset.";
              try{
                   if (command.equals("TestMe")){     // 300
                        msg.append("\nSuccessful");
                        Interface.changeCards();
                        }     // 300
              catch(Exception e){
                   e.printStackTrace();
              try{
                   if (command.equals("ButtonA")){     // 300
    // WHEN I CALL BOTH OF THE FOLLOWING METHODS THE DISPLAY WORKS
    // BUT THE CHANGECARDS METHOD DOES NOT WORK.  WHEN I COMMENT OUT
    // THE CALL TO THE DISPLAYMESSAGE METHOD THEN THE CHANGECARDS WORKS
    // FINE.  PLEASE THE INTERFACE CLASS NEXT.
                        Interface.changeCards();
                        Interface.displayMessage("test of xyz");
                        }     // 300
              catch(Exception e){
                   e.printStackTrace();
         }     // 200
    }     // 400
    // END OF UPDATEDATAFIELS  END END END
    public class Interface extends JFrame {     // 300
         static JPanel frameForCardPane;
         static CardLayout cardPane;
         static JTextArea msgout;
         TestQuestionPanel radio;
         Interface () {     // 100
              super("This is a JFrame");
            setSize(800, 400);  // width, height
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              // set-up card layout
              cardPane = new CardLayout();
              frameForCardPane = new JPanel();     // for CardLayout
              frameForCardPane.setLayout(cardPane);     // set the layout to cardPane = CardLayout
              TestQuestionPanel cardOne = new TestQuestionPanel("ABC", "DEF", msgout, radio);
              TestQuestionPanel cardTwo = new TestQuestionPanel("GHI", "JKL", msgout, radio);
              frameForCardPane.add(cardOne, "first");
              frameForCardPane.add(cardTwo, "second");
              // end set-up card layout
              // set-up main pane
              // declare components
              msgout = new JTextArea( 8, 40 );
              ButtonPanel commandButtons = new ButtonPanel(msgout);
              JPanel pane = new JPanel();
              pane.setLayout(new GridLayout(2, 4, 5, 15));             pane.setBorder(BorderFactory.createEmptyBorder(30, 20, 10, 30));
              pane.add(frameForCardPane);
                 pane.add( new JScrollPane(msgout));
                 pane.add(commandButtons);
              msgout.append("Successful");
              setContentPane(pane);
              setVisible(true);
         }     // 100
    // HERE ARE THE METHODS THAT SHOULD HANDLE THE UPDATING
         static void changeCards() {     // 200
                   cardPane.next(frameForCardPane);
                   System.out.println("Calling methods works!");
         }     // 200
         static void displayMessage(String test) {     // 200
                   String reset = "Test of reset.";
                   String passMessage = test;
                   cardPane.next(frameForCardPane);
                   System.out.println("Calling methods works!");
                   msgout.append("\n"+ test);
         }     // 200
    }     // 300

    Hi,
    I instantiate it in this class. Does that change your opinion or the advice you gave me? Please help!
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class CardLayoutQuestionsv2 {
        public static void main(String[] arguments) {
            JFrame frame = new Interface();
            frame.show();
    }

  • Selection problem on ADRC Table.

    Dear Exparts.
    please see the Query:
    select country city1 from adrc
      into CORRESPONDING FIELDS OF wa_country
      where
    country = p_country
      and
    city1 = p_city.
      append wa_country to it_country.
      endselect.
    In this selection, when I send p_country = AE and p_city = Dubai I cannot get any data. But there have data In DB.
    But when I send p_country = DE and p_city = Berlin I can get porper data.
    Can anybody solve this problem.
    Your regards
    rayhan

    Just paste the below code and check either getting value or not
    DATA wa_country TYPE adrc.
    PARAMETERS: p_city TYPE adrc-city1 DEFAULT 'Dubai',
                p_countr TYPE adrc-country DEFAULT 'AE'.
    SELECT SINGLE * FROM adrc INTO wa_country WHERE country = p_countr
    AND city1 = p_city.
    IF sy-subrc = 0.
      WRITE : / wa_country-city1, / wa_country-country.
    ENDIF.
    Kanagaraja L

Maybe you are looking for

  • Test for file download complete

    Does anyone know an accurate way to test that a file download is complete? Reports are being brought down from a server and I want to know if the download is complete before I begin parsing the file. Anyone know how to do this? Is File.canWrite() an

  • Issue with Loading COMMENTS in HFM ICT Module from FDMEE

    Hi, We have a requirement wherein we can load all the HFM ICT Transactions from a Flat File using FDMEE. We are facing 2 issues:      a. Firstly FDMEE Target application allows us to map only COMMENT1 as a dimension for FDMEE. There is no Dimension/P

  • Why is my iMac 450/128 much, much faster than my Powerbook 333/512?

    Hey boys and girls, I'm sort of new to the Mac world, but I'm working hard to become clever. So, here's the story. I have a Powerbook Bronze 333MHz with 512MB of RAM and the Toshiba 6GB drive it was born with and 10.3.9. I have a Bumbleberry (I think

  • Photoshop CS5 v12.0 using Mavricks Mac 10.9 - says I have updates required on Bridge

    Photoshop CS5 v12.0 using Mavricks Mac 10.9 - says I have updates required on Bridge & Photoshop, starts downloading gets to 98 p/cent then quits says there is an error " try again later ???? Any one have ideas what's happening ???

  • Project Server Event Handler Installer

    Hi! I created my first Event Handler to the Project Server and my question is how can I create installer to this solution? I'm looking for the best way to install solution to other farm, but I'm new in Project Server. Please help! Thanks, Mykie