简体   繁体   中英

JTabbedPane dynamically tabs

I am creating a kind of notepad who have a pane for line counter who tell me the position of line (it increments when I press Enter) and another pane for line and column counter (just like Notepad++ have). I wanted to add tabs, dynamically, so everytime I select "New" option, a new tab will be created. By default, my notepad starts with one tab opened, just like Notepad++ does. Lets call this tab, TAB1

  • If I press "New" it will create a new tab, lets call it TAB2. Now we have TAB1 and TAB2
  • If I press again "New" it will create a new tab, lets call it TAB3, so I will have 3 tabs now: TAB1, TAB2, TAB3.

Now if I want to select TAB2 to edit something in it, this is the point where my program is not working properly, because if I want to press enter to go on new line, it will not add a new line in TAB2, it will add a new line in TAB3. How can I fix this?

Here is the ActionListener , where I say what to happen if I press "New" from menubar. state() is the function where I do layout.

if(menuFileNew == e.getSource())
    {   
        state();        
            Action newline = new AbstractAction() 
            {
               public void actionPerformed(ActionEvent e) 
               {
                    thisTextArea.setText(thisTextArea.getText()+"\n");
                   counter++;
                thisLineCounterPane.setText(thisLineCounterPane.getText()+counter+"\n");            
               }
            }; 
        thisTextArea.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0), NEWLINE);
        thisTextArea.getActionMap().put(NEWLINE, newline);
    }
thisTextArea.setText(thisTextArea.getText()+"\n");

You "new line" Action is incorrect. You are hardcoding the text area variable you want to change.

Instead your Action should extend TextAction (not AbstractAction). Then you can use the getFocusedComponent() method of the TextAction to get the text area that currently has focus.

For a simple example check out: Clear current FocusOwner (jTextfield)

Also, that is not the way to add a new line character to a text field. Don't use the setText() method. Instead you should be using the append(...) method.

Although the real question is why are you creating this Action? Adding a newline to the text area is the default behaviour when you press the Enter key.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM