2014-11-25 5 views
-1

Tab의 이름을 변경하고 싶습니다. 작성된 문서를 저장 한 후 새 문서를 만들면 커서가 TextArea에 놓이거나 포커스가 지정되지 않습니다. 텍스트 영역을 클릭 한 다음에 만 포커스. 어떻게하면 Textarea에 자동 초점을 달성 할 수 있습니다. 내 응용 프로그램에서 새 문서를 만들 때 Doc 1/Doc 2/Doc 3의 탭 이름으로 빈 문서로 열립니다. ... 텍스트를 입력하면 "저장"메뉴 항목을 통해 저장하십시오. Doc 1을 주어진 파일 이름으로 대체하려고합니다. 모두 확인하십시오. 모두 감사합니다.JTabbedPane의 탭 이름을 변경하는 방법

내 코드 : 텍스트 필드를 사용 requestFocus에 초점을 얻기 위해

public class TabbedPaneFocus extends javax.swing.JFrame { 

JTextArea textArea; 
int i=0; 
JTabbedPane tabbedPane; 
public TabbedPaneFocus() { 

    initComponents(); 
    tabbedPane=new CloseButtonTabbedPane(); 
    add(tabbedPane); 
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); 
    getContentPane().setLayout(layout); 
    layout.setHorizontalGroup(
     layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
     .addComponent(tabbedPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 512, Short.MAX_VALUE) 
    ); 
    layout.setVerticalGroup(
     layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
     .addComponent(tabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 366, Short.MAX_VALUE) 
    ); 
} 

@SuppressWarnings("unchecked") 
// <editor-fold defaultstate="collapsed" desc="Generated Code">       
private void initComponents() { 

    jMenuBar1 = new javax.swing.JMenuBar(); 
    jMenu1 = new javax.swing.JMenu(); 
    create = new javax.swing.JMenuItem(); 
    save = new javax.swing.JMenuItem(); 

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); 

    jMenu1.setText("File"); 

    create.setText("Create"); 
    create.addActionListener(new java.awt.event.ActionListener() { 
     public void actionPerformed(java.awt.event.ActionEvent evt) { 
      createActionPerformed(evt); 
     } 
    }); 
    jMenu1.add(create); 

    save.setText("Save"); 
    save.addActionListener(new java.awt.event.ActionListener() { 
     public void actionPerformed(java.awt.event.ActionEvent evt) { 
      saveActionPerformed(evt); 
     } 
    }); 
    jMenu1.add(save); 

    jMenuBar1.add(jMenu1); 

    setJMenuBar(jMenuBar1); 

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); 
    getContentPane().setLayout(layout); 
    layout.setHorizontalGroup(
     layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
     .addGap(0, 512, Short.MAX_VALUE) 
    ); 
    layout.setVerticalGroup(
     layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
     .addGap(0, 366, Short.MAX_VALUE) 
    ); 

    pack(); 
}// </editor-fold>       

private void createActionPerformed(java.awt.event.ActionEvent evt) {          
    try{ 
     i++; 
     textArea = new JTextArea(); 
     textArea.setFont(new java.awt.Font("Miriam Fixed", 0, 13)); 
     JScrollPane scrollpane=new JScrollPane(textArea); 
     tabbedPane.add(scrollpane); 
     tabbedPane.addTab("Doc "+i, scrollpane); 
     tabbedPane.setSelectedIndex(i-1); 
     tabbedPane.setFocusable(true); 
    } 
    catch(ArrayIndexOutOfBoundsException aio){ 
    } 
}          

private void saveActionPerformed(java.awt.event.ActionEvent evt) {          
    int chooserStatus; 
    String filename = null; 
    int index=tabbedPane.getSelectedIndex(); 
    String name=tabbedPane.getTitleAt(index); 
     if(name.isEmpty() || name.startsWith("Doc ")){ 
      JFileChooser chooser = new JFileChooser(); 
      chooser.setPreferredSize(new Dimension(450, 400)); 
      chooserStatus = chooser.showSaveDialog(this); 
      if (chooserStatus == JFileChooser.APPROVE_OPTION) { 
       File selectedFile = chooser.getSelectedFile();    
       if (!selectedFile.getName().endsWith(".txt")) { 
        selectedFile = new File(selectedFile.getAbsolutePath() + ".txt"); 
       } 
       filename = selectedFile.getPath(); 
       tabbedPane.setTitleAt(index, selectedFile.getName()); 
      } 
      else{ 
       return; 
      } 
     }  
     boolean success; 
     String editorString; 
     FileWriter fwriter; 
     PrintWriter outputFile; 
     try { 
      DataOutputStream d = new DataOutputStream(new FileOutputStream(filename)); 
      String line = textArea.getText(); 
      BufferedReader br = new BufferedReader(new StringReader(line)); 
      while((line = br.readLine())!=null) { 
       d.writeBytes(line + "\r\n"); 
      } 
     } 
     catch (IOException e) {  
      success = false; 
     } 
     success = true; 
}          

public static void main(String args[]) { 
    try { 
     for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { 
      if ("Nimbus".equals(info.getName())) { 
       javax.swing.UIManager.setLookAndFeel(info.getClassName()); 
       break; 
      } 
     } 
    } catch (ClassNotFoundException ex) { 
     java.util.logging.Logger.getLogger(TabbedPaneFocus.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (InstantiationException ex) { 
     java.util.logging.Logger.getLogger(TabbedPaneFocus.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (IllegalAccessException ex) { 
     java.util.logging.Logger.getLogger(TabbedPaneFocus.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (javax.swing.UnsupportedLookAndFeelException ex) { 
     java.util.logging.Logger.getLogger(TabbedPaneFocus.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } 
    java.awt.EventQueue.invokeLater(new Runnable() { 
     @Override 
     public void run() { 
      new TabbedPaneFocus().setVisible(true); 
     } 
    }); 
} 

// Variables declaration - do not modify      
private javax.swing.JMenuItem create; 
private javax.swing.JMenu jMenu1; 
private javax.swing.JMenuBar jMenuBar1; 
private javax.swing.JMenuItem save; 
// End of variables declaration     

public class CloseButtonTabbedPane extends JTabbedPane { 
public CloseButtonTabbedPane() { 
} 
public void addTab(String title, Icon icon, Component component, String tip) { 
    super.addTab(title, icon, component, tip); 
    int count = this.getTabCount() - 1; 
    setTabComponentAt(count, new CloseButtonTab(component, title, icon)); 
} 
public void addTab(String title, Icon icon, Component component) { 
    addTab(title, icon, component, null); 
} 
public void addTab(String title, Component component) { 
    addTab(title, null, component); 
} 
public class CloseButtonTab extends JPanel { 
    private Component tab; 
    public CloseButtonTab(final Component tab, String title, Icon icon) { 
     this.tab = tab; 
     setOpaque(false); 
     FlowLayout flowLayout = new FlowLayout(FlowLayout.CENTER, 3, 3); 
     setLayout(flowLayout); 
     setVisible(true); 
     JLabel jLabel = new JLabel(title); 
     jLabel.setIcon(icon); 
     add(jLabel); 
     JButton button = new JButton(MetalIconFactory.getInternalFrameCloseIcon(16)); 
     button.setMargin(new Insets(0, 0, 0, 0)); 
     button.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 1)); 
     button.addMouseListener(new MouseListener() { 
         int index; 
      public void mouseClicked(MouseEvent e) { 
            tabbedPane.remove(tabbedPane.getSelectedIndex()); 
            i--; 
      } 
      public void mousePressed(MouseEvent e) { 
      } 
      public void mouseReleased(MouseEvent e) { 
      } 
      public void mouseEntered(MouseEvent e) { 
       JButton button = (JButton) e.getSource(); 
       button.setBorder(BorderFactory.createLineBorder(Color.RED, 1)); 
      } 
      public void mouseExited(MouseEvent e) { 
       JButton button = (JButton) e.getSource(); 
       button.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 1)); 
      } 
     }); 
     add(button); 
    } 
} 
} 
} 

In My SaveAction code I write the code to change the tab name with saved file name but not apply. 
tabbedPane.setTitleAt(index, selectedFile.getName()); 
+0

죄송합니다. 영어는 모든 사람이 모국어가 아니지만 실제로 어떤 질문을 받고 있는지 잘 모르겠습니다. 당신이 알고 싶은 것을 명확하게하려고 노력하십시오. – BarrySW19

+0

좋아요, 문제 없습니다. 작성 및 저장 메뉴 항목이 있습니다. 메뉴 작성을 클릭합니다. 항목 Doc 1이있는 문서를 엽니 다. 그런 다음 열린 문서에 텍스트를 쓰고 몇 가지 이름으로 내 문서를 저장합니다. 탭 이름 Doc 1을 주어진 파일/문서 이름으로 바꿉니다. – user3912886

답변

0

. 나중에 탭의 제목을 변경하려면 addTab과 함께 추가하는 탭의 JLabel에 대한 참조를 유지해야합니다. 따라서 탭 자체에 대한 참조를 유지해야합니다. 이런 식으로해볼 수 있습니다. 몇 줄을 수정하고 주석을 달아 쉽게 찾을 수 있습니다.

참고 : 간단한 확장 기능 만 수행 했으므로 어떻게 수행되는지 확인할 수 있습니다. 특히 탭 개별 삭제시 탭의 ArrayList 계좌를보다 신중하게 처리해야 할 수 있습니다. 몇 가지 검사를해야합니다. 또한 아직 생성 된 탭이 없을 때 저장을 클릭하면 사례를 처리해야합니다. 지금은 ArrayIndexOutOfBoundsException이됩니다.

public class TabbedPaneFocus extends javax.swing.JFrame 
{ 

    JTextArea textArea; 
    int i = 0; 
    CloseButtonTabbedPane tabbedPane; 

    public TabbedPaneFocus() 
    { 

     initComponents(); 
     tabbedPane = new CloseButtonTabbedPane(); 
     add(tabbedPane); 
     javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
       getContentPane()); 
     getContentPane().setLayout(layout); 
     layout.setHorizontalGroup(layout.createParallelGroup(
       javax.swing.GroupLayout.Alignment.LEADING).addComponent(
       tabbedPane, javax.swing.GroupLayout.Alignment.TRAILING, 
       javax.swing.GroupLayout.DEFAULT_SIZE, 512, Short.MAX_VALUE)); 
     layout.setVerticalGroup(layout.createParallelGroup(
       javax.swing.GroupLayout.Alignment.LEADING).addComponent(
       tabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 366, 
       Short.MAX_VALUE)); 
    } 

    @SuppressWarnings("unchecked") 
    // <editor-fold defaultstate="collapsed" desc="Generated Code"> 
    private void initComponents() 
    { 

     jMenuBar1 = new javax.swing.JMenuBar(); 
     jMenu1 = new javax.swing.JMenu(); 
     create = new javax.swing.JMenuItem(); 
     save = new javax.swing.JMenuItem(); 

     setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); 

     jMenu1.setText("File"); 

     create.setText("Create"); 
     create.addActionListener(new java.awt.event.ActionListener() 
     { 
      public void actionPerformed(java.awt.event.ActionEvent evt) 
      { 
       createActionPerformed(evt); 
      } 
     }); 
     jMenu1.add(create); 

     save.setText("Save"); 
     save.addActionListener(new java.awt.event.ActionListener() 
     { 
      public void actionPerformed(java.awt.event.ActionEvent evt) 
      { 
       saveActionPerformed(evt); 
      } 
     }); 
     jMenu1.add(save); 

     jMenuBar1.add(jMenu1); 

     setJMenuBar(jMenuBar1); 

     javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
       getContentPane()); 
     getContentPane().setLayout(layout); 
     layout.setHorizontalGroup(layout.createParallelGroup(
       javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 512, 
       Short.MAX_VALUE)); 
     layout.setVerticalGroup(layout.createParallelGroup(
       javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 366, 
       Short.MAX_VALUE)); 

     pack(); 
    }// </editor-fold> 

    private void createActionPerformed(java.awt.event.ActionEvent evt) 
    { 
     try 
     { 
      i++; 
      textArea = new JTextArea(); 
      textArea.setFont(new java.awt.Font("Miriam Fixed", 0, 13)); 
      JScrollPane scrollpane = new JScrollPane(textArea); 
      //tabbedPane.add(scrollpane); Remove this line. you only need the scroll pane in the tab 
      tabbedPane.addTab("Doc " + i, scrollpane); 
      tabbedPane.setSelectedIndex(i - 1); 
      tabbedPane.setFocusable(true); 
      textArea.requestFocus(); // Here you gain focus on text area of the new tab 
     } 
     catch (ArrayIndexOutOfBoundsException aio) 
     { 
     } 
    } 

    private void saveActionPerformed(java.awt.event.ActionEvent evt) 
    { 
     int chooserStatus; 
     String filename = null; 
     int index = tabbedPane.getSelectedIndex(); 
     String name = tabbedPane.getTitleAt(index); 
     if (name.isEmpty() || name.startsWith("Doc ")) 
     { 
      JFileChooser chooser = new JFileChooser(); 
      chooser.setPreferredSize(new Dimension(450, 400)); 
      chooserStatus = chooser.showSaveDialog(this); 
      if (chooserStatus == JFileChooser.APPROVE_OPTION) 
      { 
       File selectedFile = chooser.getSelectedFile(); 
       if (!selectedFile.getName().endsWith(".txt")) 
       { 
        selectedFile = new File(selectedFile.getAbsolutePath() 
          + ".txt"); 
       } 
       filename = selectedFile.getPath(); 
       // tabbedPane.setTitleAt(index, selectedFile.getName()); -> Replace this line 

       // Set a new title by accessing the tab and the title label 
       tabbedPane.tabs.get(index).tabTitle.setText(selectedFile.getName()); 
      } 
      else 
      { 
       return; 
      } 
     } 
     boolean success; 
     String editorString; 
     FileWriter fwriter; 
     PrintWriter outputFile; 
     try 
     { 
      DataOutputStream d = new DataOutputStream(new FileOutputStream(
        filename)); 
      String line = textArea.getText(); 
      BufferedReader br = new BufferedReader(new StringReader(line)); 
      while ((line = br.readLine()) != null) 
      { 
       d.writeBytes(line + "\r\n"); 
      } 
     } 
     catch (IOException e) 
     { 
      success = false; 
     } 
     success = true; 
    } 

    public static void main(String args[]) 
    { 
     try 
     { 
      for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager 
        .getInstalledLookAndFeels()) 
      { 
       if ("Nimbus".equals(info.getName())) 
       { 
        javax.swing.UIManager.setLookAndFeel(info.getClassName()); 
        break; 
       } 
      } 
     } 
     catch (ClassNotFoundException ex) 
     { 
      java.util.logging.Logger.getLogger(TabbedPaneFocus.class.getName()) 
        .log(java.util.logging.Level.SEVERE, null, ex); 
     } 
     catch (InstantiationException ex) 
     { 
      java.util.logging.Logger.getLogger(TabbedPaneFocus.class.getName()) 
        .log(java.util.logging.Level.SEVERE, null, ex); 
     } 
     catch (IllegalAccessException ex) 
     { 
      java.util.logging.Logger.getLogger(TabbedPaneFocus.class.getName()) 
        .log(java.util.logging.Level.SEVERE, null, ex); 
     } 
     catch (javax.swing.UnsupportedLookAndFeelException ex) 
     { 
      java.util.logging.Logger.getLogger(TabbedPaneFocus.class.getName()) 
        .log(java.util.logging.Level.SEVERE, null, ex); 
     } 
     java.awt.EventQueue.invokeLater(new Runnable() 
     { 
      @Override 
      public void run() 
      { 
       new TabbedPaneFocus().setVisible(true); 
      } 
     }); 
    } 

    // Variables declaration - do not modify 
    private javax.swing.JMenuItem create; 
    private javax.swing.JMenu jMenu1; 
    private javax.swing.JMenuBar jMenuBar1; 
    private javax.swing.JMenuItem save; 

    // End of variables declaration 

    public class CloseButtonTabbedPane extends JTabbedPane 
    { 
     public CloseButtonTabbedPane() 
     { 
     } 

     // ArrayList to keep track of all created tabs 
     ArrayList<CloseButtonTab> tabs = new ArrayList<CloseButtonTab>(); 

     public void addTab(String title, Icon icon, Component component, 
       String tip) 
     { 
      super.addTab(title, icon, component, tip); 
      int count = this.getTabCount() - 1; 
      CloseButtonTab tab = new CloseButtonTab(component, title, icon); 
      setTabComponentAt(count, tab); 
      tabs.add(tab); // Add the new tab to later modify the title 
     } 

     public void addTab(String title, Icon icon, Component component) 
     { 
      addTab(title, icon, component, null); 
     } 

     public void addTab(String title, Component component) 
     { 
      addTab(title, null, component); 
     } 

     public class CloseButtonTab extends JPanel 
     { 
      private Component tab; 
      JLabel tabTitle; // Saves the title, modify this label to set a new title 

      public CloseButtonTab(final Component tab, String title, Icon icon) 
      { 
       this.tab = tab; 
       setOpaque(false); 
       FlowLayout flowLayout = new FlowLayout(FlowLayout.CENTER, 3, 3); 
       setLayout(flowLayout); 
       setVisible(true); 
       tabTitle = new JLabel(title); // Set the tab title 
       tabTitle.setIcon(icon); 
       add(tabTitle); 
       JButton button = new JButton(
         MetalIconFactory.getInternalFrameCloseIcon(16)); 
       button.setMargin(new Insets(0, 0, 0, 0)); 
       button.setBorder(BorderFactory.createLineBorder(
         Color.LIGHT_GRAY, 1)); 
       button.addMouseListener(new MouseListener() 
       { 
        int index; 

        public void mouseClicked(MouseEvent e) 
        { 
         tabbedPane.remove(tabbedPane.getSelectedIndex()); 
         i--; 
        } 

        public void mousePressed(MouseEvent e) 
        { 
        } 

        public void mouseReleased(MouseEvent e) 
        { 
        } 

        public void mouseEntered(MouseEvent e) 
        { 
         JButton button = (JButton) e.getSource(); 
         button.setBorder(BorderFactory.createLineBorder(
           Color.RED, 1)); 
        } 

        public void mouseExited(MouseEvent e) 
        { 
         JButton button = (JButton) e.getSource(); 
         button.setBorder(BorderFactory.createLineBorder(
           Color.LIGHT_GRAY, 1)); 
        } 
       }); 
       add(button); 
      } 
     } 
    } 

} 
+0

고맙습니다. 작동 중입니다. – user3912886

+0

반갑습니다. – BluesSolo

관련 문제