Изменить SelectedIndex при нажатии кнопки табуляции - PullRequest
0 голосов
/ 02 сентября 2018

У меня есть JTabbedPane с пользовательской вкладкой, которая отображает имя файла, за которым следует кнопка. Когда кнопка нажата, я хотел бы закрыть эту вкладку. Моей первой мыслью было (надеюсь), что когда я нажму на кнопку, она сначала переключится на эту вкладку, затем я смогу просто закрыть вкладку с этим индексом. Однако это не так. Я ищу способ получить индекс вкладки, на которой кнопка, затем я мог бы закрыть эту вкладку. Я попытался исследовать и придумал indexOfComponent, но я не уверен, как использовать его в моей ситуации. Мои вкладки создаются динамически, поэтому я храню вещи внутри вектора, который создает JPanels, а затем отображает текущую информацию на основе выбранного индекса. (вкладка 0 будет иметь все свои компоненты внутри vec [0], tab 1 = vec [1] и т. д.).

Мой класс TextEdit настроен так:

public class TextEdit extends JTabbedPane {
  private Vector<JTextArea> vec; // User can make and edit files
  private Vector<JPanel> tabPanel; // Panel that has a JLabel for fileName and JButton to close file
  private Vector<JLabel> absolutePath; // Path to which file will be saved

  public TextEdit() {
    // Sets up actionlisteners, initializes variables, etc
  }

  protected void AddTab(String fileName) {
    JPanel panel = new JPanel; // Where textarea will be
    panel.setLayout(new GridLayout(0,1));
    JTextArea ta = new JTextArea();
    JScrollPane sp = new JScrollPane(ta);
    panel.add(sp);

    JPanel tp = new JPanel(); // The tab panel
    tp.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 2));
    JLabel label = new JLabel(fileName);
    JButton button = new JButton("X");
    button.addActionListener(CloseOne); // My Action that will close the file
    tp.add(label);
    tp.add(button);

    this.addTab(fileName, panel); // Sets the text area into the tab
    this.setTabComponentAt(this.getSelectedIndex, tp); // Sets the tab to the fileName and button

    vec.add(ta); // Add textarea to vector for future use
    tabPanel.add(tp); // Add the tabpanel for future use. this is where the button is, I need to setSelectedIndex to the tab that the button resides onclick

}

TextEditor.java

Action CloseOne = new AbstractAction("CloseOne") {
  @Override
  public void actionPerformed(ActionEvent e) {
    // This is where I need to set the selected tab to the tab in which the button was pressed.
  }
};

Класс TextEditor - это то, что включает в себя все мои действия и содержит TextEdit (где находятся вкладки и т. Д.).

У моего textedit есть методы для установки и получения выбранного индекса.

Возвращаясь к indexOfComponent, мне нужно было бы указать, какой компонент я использую, однако мои компоненты добавляются динамически, и мне пришлось бы выяснить выбранный индекс, чтобы попасть в вектор или JPanels, чтобы даже использовать его. Или я что-то упустил? Есть предложения?

1 Ответ

0 голосов
/ 04 сентября 2018

В вашем методе AddTab установите actionCommand на кнопку закрытия в качестве индекса вновь добавленной вкладки, как показано ниже

JButton button = new JButton("X");
button.setActionCommand( "" + tabPanel.size() );
button.addActionListener(CloseOne);

Добавить метод removeTabComponentAtmethod в классе TextEdit

  public void removeTabComponentAt( int index ) {
       vec.removeElementAt(index );  
       tabPanel.removeElementAt(index );
       this.removeTabAt( index );

  }

В вашем действии Закрыть получить индекс нажатой кнопки

Action CloseOne = new AbstractAction("CloseOne") {

    public Component getTextEdit ( Component comp) {
         if( comp instanceof TextEdit ) {
            return ( TextEdit  ) comp;
         } 
         if( comp.getParent() != null ) {
              return getTextEdit ( comp.getParent() );
         }  else {
              return null;
         }
    }
   @Override
    public void actionPerformed(ActionEvent e) {

         String indexStr = e.getActionCommand();
         int index=-1; 
         try {
              index = Integer.parseInt( indexStr );

         } catch( NumberFormatException ex ) {
         }
         if( index > -1 ) {
            TextEdit textEdit = getTextEdit( ( Component ) e.getSource() ) ;
              if( textEdit  != null ) {
                 textEdit.removeTabComponentAt( index );
              }
         }
    }
};
...