2014-07-24 36 views
0

我希望所有打開的文檔的工作功能不是當前打開的僅文檔。我創建了一個swing應用程序。我打開了一個文檔。通過menuItem的剪切,複製,粘貼和selectAll操作適用於當前打開的文檔;不適用於以前打開的文檔。請幫幫我。如何在擺動中處理所有文檔的功能

這裏是我的代碼:

public class OpenDemo extends javax.swing.JFrame implements ChangeListener{ 
JTextPane textPane; 
JTextPane lnNum; 
JScrollPane scrollPane; 
int i=0; 
JTextField status; 
ArrayList<JTextPane> textPanes=new ArrayList<>(); 
public OpenDemo() { 
    initComponents(); 
    viewLineNumbers.setSelected(false); 
} 
@SuppressWarnings("unchecked") 
// <editor-fold defaultstate="collapsed" desc="Generated Code">       
private void initComponents() { 

    tp = new javax.swing.JTabbedPane(); 
    jMenuBar1 = new javax.swing.JMenuBar(); 
    jMenu1 = new javax.swing.JMenu(); 
    open = new javax.swing.JMenuItem(); 
    cut = new javax.swing.JMenuItem(); 
    selectAll = new javax.swing.JMenuItem(); 
    viewLineNumbers = new javax.swing.JCheckBoxMenuItem(); 

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); 

    jMenu1.setText("File"); 

    open.setText("Open"); 
    open.addActionListener(new java.awt.event.ActionListener() { 
     public void actionPerformed(java.awt.event.ActionEvent evt) { 
      openActionPerformed(evt); 
     } 
    }); 
    jMenu1.add(open); 

    cut.setText("Cut"); 
    cut.addActionListener(new java.awt.event.ActionListener() { 
     public void actionPerformed(java.awt.event.ActionEvent evt) { 
      cutActionPerformed(evt); 
     } 
    }); 
    jMenu1.add(cut); 

    selectAll.setText("SelectAll"); 
    selectAll.addActionListener(new java.awt.event.ActionListener() { 
     public void actionPerformed(java.awt.event.ActionEvent evt) { 
      selectAllActionPerformed(evt); 
     } 
    }); 
    jMenu1.add(selectAll); 

    viewLineNumbers.setSelected(true); 
    viewLineNumbers.setText("ViewLineNumbers"); 
    viewLineNumbers.addActionListener(new java.awt.event.ActionListener() { 
     public void actionPerformed(java.awt.event.ActionEvent evt) { 
      viewLineNumbersActionPerformed(evt); 
     } 
    }); 
    jMenu1.add(viewLineNumbers); 

    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) 
     .addComponent(tp, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE) 
    ); 
    layout.setVerticalGroup(
     layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
     .addComponent(tp, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE) 
    ); 

    pack(); 
}// </editor-fold>       
private void updateStatus(int linenumber, int columnnumber) { 
status.setText("Line: " + linenumber + " Column: " + columnnumber); 
}  
private void openActionPerformed(java.awt.event.ActionEvent evt) {          
    FileDialog fd = new FileDialog(OpenDemo.this, "Select File", FileDialog.LOAD); 
    fd.show(); 
    String title; 
    String sts; 
    File f; 
    if (fd.getFile() != null) { 
     sts = fd.getDirectory() + fd.getFile(); 
     title=fd.getFile(); 
     System.out.println(sts); 
     title=fd.getFile(); 
     BufferedReader br = null; 
     StringBuffer str = new StringBuffer(""); 
     try { 
      br = new BufferedReader(new FileReader(sts)); 
      String line; 
      try { 
       while ((line = br.readLine()) != null) { 
       str.append(line + "\n"); 
       } 
      } catch (IOException ex) { 
       Logger.getLogger(OpenDemo.class.getName()).log(Level.SEVERE, null, ex); 
      } 
     } catch (FileNotFoundException ex) { 
      Logger.getLogger(OpenDemo.class.getName()).log(Level.SEVERE, null, ex); 
     } 
     String t = str.toString(); 
     final JInternalFrame internalFrame = new JInternalFrame("",true,true); 
     textPane = new JTextPane(); 
     textPane.setFont(new java.awt.Font("Miriam Fixed", 0, 13)); 
     internalFrame.add(textPane); 
     i++; 
     internalFrame.setName("Doc "+i); 
     internalFrame.setTitle(title); 
     try { 
      internalFrame.setSelected(true); 
     } catch (PropertyVetoException ex) { 
      Logger.getLogger(OpenDemo.class.getName()).log(Level.SEVERE, null, ex); 
     } 
     textPane.addCaretListener(new CaretListener() { 
     @Override 
     public void caretUpdate(CaretEvent e) { 
      JTextPane editArea = (JTextPane)e.getSource(); 
      int linenum = 1; 
      int columnnum = 1; 
      try { 
       int caretpos = editArea.getCaretPosition(); 
       linenum=getLineAtCaret(editArea)-1; 
       columnnum=getColumnAtCaret(editArea); 
       linenum += 1; 
      } 
      catch(Exception ex) { } 
      updateStatus(linenum, columnnum); 
     } 
    }); 
     status=new JTextField(); 
     status.setBackground(Color.LIGHT_GRAY); 
     internalFrame.add(status,BorderLayout.SOUTH); 
     tp.add(internalFrame); 
     scrollPane=new JScrollPane(textPane); 
     tp.setSelectedIndex(i-1); 
     internalFrame.add(scrollPane); 
     internalFrame.setVisible(true); 
     textPane.setText(t); 
     tp.addChangeListener(this); 
     textPanes.add(textPane); 
     textPane.setCaretPosition(0); 
}  
}          

private void cutActionPerformed(java.awt.event.ActionEvent evt) {          
    textPane.cut(); 
}         

private void selectAllActionPerformed(java.awt.event.ActionEvent evt) {           
    textPane.selectAll(); 
}           

private void viewLineNumbersActionPerformed(java.awt.event.ActionEvent evt) {             
    AbstractButton button = (AbstractButton) evt.getSource(); 
        if(button.isSelected()){ 
        lnNum = new JTextPane(); 
        lnNum.setEditable(false); 
        lnNum.setSize(50,50); 
        lnNum.setFont(new java.awt.Font("Miriam Fixed", 0, 13)); 
        lnNum.setText(getText()); 
        textPane.getDocument().addDocumentListener(new DocumentListener(){ 
         @Override 
         public void changedUpdate(DocumentEvent de) { 
         lnNum.setText(getText()); 
        } 
        @Override 
        public void insertUpdate(DocumentEvent de) { 
        lnNum.setText(getText()); 
        } 
        @Override 
        public void removeUpdate(DocumentEvent de) { 
        lnNum.setText(getText()); 
        } 
        }); 
        scrollPane.getViewport().add(textPane); 
        scrollPane.setRowHeaderView(lnNum); 
        } 
        else{ 
         scrollPane.setRowHeaderView(null); 
        }   
}            
public String getText(){ 
    int caretPosition = textPane.getDocument().getLength(); 
    javax.swing.text.Element root = textPane.getDocument().getDefaultRootElement(); 
    String text = "1" + System.getProperty("line.separator"); 
    for(int i = 2; i <= root.getElementIndex(caretPosition) + 1; i++){ 
     text += i + System.getProperty("line.separator"); 
    } 
    return text; 
} 
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(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (InstantiationException ex) { 
     java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (IllegalAccessException ex) { 
     java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (javax.swing.UnsupportedLookAndFeelException ex) { 
     java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } 
    //</editor-fold> 
    java.awt.EventQueue.invokeLater(new Runnable() { 
     public void run() { 
      new OpenDemo().setVisible(true); 
     } 
    }); 
} 

// Variables declaration - do not modify      
private javax.swing.JMenuItem cut; 
private javax.swing.JMenu jMenu1; 
private javax.swing.JMenuBar jMenuBar1; 
private javax.swing.JMenuItem open; 
private javax.swing.JMenuItem selectAll; 
private javax.swing.JTabbedPane tp; 
private javax.swing.JCheckBoxMenuItem viewLineNumbers; 
// End of variables declaration     

@Override 
public void stateChanged(ChangeEvent ce) { 
    JTabbedPane sourceTabbedPane = (JTabbedPane) ce.getSource(); 
    int index = sourceTabbedPane.getSelectedIndex(); 
    try 
    { 
     textPane =textPanes.get(index); 
    } 
    catch(IndexOutOfBoundsException e1){ 
    } 
} 
public int getLineAtCaret(JTextComponent component) 
{ 
    int caretPosition = component.getCaretPosition(); 
    Element root = component.getDocument().getDefaultRootElement(); 
    return root.getElementIndex(caretPosition) + 1; 
} 
public int getColumnAtCaret(JTextComponent component) 
{ 
    FontMetrics fm = component.getFontMetrics(component.getFont()); 
    int characterWidth = fm.stringWidth("0"); 
    int column = 0; 
    try 
    { 
     Rectangle r = component.modelToView(component.getCaretPosition()); 
     int width = r.x - component.getInsets().left; 
     column = width/characterWidth; 
    } 
    catch(BadLocationException ble) {} 
    return column + 1; 
} 

}

+0

如何** Cut **操作應該適用於多個文檔?我無法想象剪貼板應該是什麼? – StanislavL

+0

你看過[內部幀](http://docs.oracle.com/javase/tutorial/uiswing/components/internalframe.html)嗎? –

+0

@Catalina島,哈我已經證明,但它不工作,請幫助我。 – user3709795

回答

0

我想,我成功地回答你所有的問題,但我需要創建另一個類我把它叫做「OInternalFrame」,所以我會給你們都爲這些班級編碼。告訴我,如果這就是你想達到:

OpenDemo:

import java.awt.FileDialog; 
import java.awt.FontMetrics; 
import java.awt.Rectangle; 
import java.beans.PropertyVetoException; 
import java.io.BufferedReader; 
import java.io.FileNotFoundException; 
import java.io.FileReader; 
import java.io.IOException; 
import java.util.ArrayList; 
import java.util.logging.Level; 
import java.util.logging.Logger; 

import javax.swing.AbstractButton; 
import javax.swing.JTabbedPane; 
import javax.swing.event.ChangeEvent; 
import javax.swing.event.ChangeListener; 
import javax.swing.event.InternalFrameAdapter; 
import javax.swing.event.InternalFrameEvent; 
import javax.swing.text.BadLocationException; 
import javax.swing.text.Element; 
import javax.swing.text.JTextComponent; 

public class OpenDemo extends javax.swing.JFrame implements ChangeListener{ 



private ArrayList<OInternalFrame> frames = new ArrayList<OInternalFrame>(); 
private OInternalFrame currentFrame; 
int i=0; 
public OpenDemo() { 
    initComponents(); 
    viewLineNumbers.setSelected(false); 
} 
@SuppressWarnings("unchecked") 
// <editor-fold defaultstate="collapsed" desc="Generated Code">       
private void initComponents() { 

    tp = new javax.swing.JTabbedPane(); 
    jMenuBar1 = new javax.swing.JMenuBar(); 
    jMenu1 = new javax.swing.JMenu(); 
    open = new javax.swing.JMenuItem(); 
    cut = new javax.swing.JMenuItem(); 
    selectAll = new javax.swing.JMenuItem(); 
    viewLineNumbers = new javax.swing.JCheckBoxMenuItem(); 

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); 

    jMenu1.setText("File"); 

    open.setText("Open"); 
    open.addActionListener(new java.awt.event.ActionListener() { 
     public void actionPerformed(java.awt.event.ActionEvent evt) { 
      openActionPerformed(evt); 
     } 
    }); 
    jMenu1.add(open); 

    cut.setText("Cut"); 
    cut.addActionListener(new java.awt.event.ActionListener() { 
     public void actionPerformed(java.awt.event.ActionEvent evt) { 
      cutActionPerformed(evt); 
     } 
    }); 
    jMenu1.add(cut); 

    selectAll.setText("SelectAll"); 
    selectAll.addActionListener(new java.awt.event.ActionListener() { 
     public void actionPerformed(java.awt.event.ActionEvent evt) { 
      selectAllActionPerformed(evt); 
     } 
    }); 
    jMenu1.add(selectAll); 

    viewLineNumbers.setSelected(true); 
    viewLineNumbers.setText("ViewLineNumbers"); 
    viewLineNumbers.addActionListener(new java.awt.event.ActionListener() { 
     public void actionPerformed(java.awt.event.ActionEvent evt) { 
      viewLineNumbersActionPerformed(evt); 
     } 
    }); 
    jMenu1.add(viewLineNumbers); 

    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) 
     .addComponent(tp, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE) 
    ); 
    layout.setVerticalGroup(
     layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
     .addComponent(tp, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE) 
    ); 

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

private void openActionPerformed(java.awt.event.ActionEvent evt) {          
    FileDialog fd = new FileDialog(OpenDemo.this, "Select File", FileDialog.LOAD); 
    fd.show(); 
    String title; 
    String sts; 

    if (fd.getFile() != null) { 
     sts = fd.getDirectory() + fd.getFile(); 
     title=fd.getFile(); 
     System.out.println(sts); 
     title=fd.getFile(); 
     BufferedReader br = null; 
     StringBuffer str = new StringBuffer(""); 
     try { 
      br = new BufferedReader(new FileReader(sts)); 
      String line; 
      try { 
       while ((line = br.readLine()) != null) { 
       str.append(line + "\n"); 
       } 
      } catch (IOException ex) { 
       Logger.getLogger(OpenDemo.class.getName()).log(Level.SEVERE, null, ex); 
      } 
     } catch (FileNotFoundException ex) { 
      Logger.getLogger(OpenDemo.class.getName()).log(Level.SEVERE, null, ex); 
     } 
     String t = str.toString(); 
     OInternalFrame internalFrame = new OInternalFrame("",true,true); 


     i++; 
     internalFrame.setName("Doc "+i); 
     internalFrame.setTitle(title); 
     try { 
      internalFrame.setSelected(true); 
     } catch (PropertyVetoException ex) { 
      Logger.getLogger(OpenDemo.class.getName()).log(Level.SEVERE, null, ex); 
     } 


     internalFrame.addInternalFrameListener(new InternalFrameAdapter() { 
      @Override 
      public void internalFrameClosing(InternalFrameEvent e) { 
       i--; 

       frames.remove(currentFrame); 
       tp.remove(currentFrame); 
       for(OInternalFrame frame : frames) 
       { 
        int index=frames.indexOf(frame); 

        tp.setTitleAt(index, "Doc "+(index+1)); 

       } 

      } 
     }); 
     tp.add(internalFrame); 
     tp.setSelectedIndex(i-1); 



     tp.addChangeListener(this); 
     frames.add(internalFrame); 
     currentFrame=internalFrame; 
     currentFrame.setText(t); 
     currentFrame.setVisible(true); 
     currentFrame.setLineViewer(viewLineNumbers.isSelected()); 

}  
}          

private void cutActionPerformed(java.awt.event.ActionEvent evt) {          
    currentFrame.cut(); 
}         

private void selectAllActionPerformed(java.awt.event.ActionEvent evt) {           
    currentFrame.selectAll(); 
}           

private void viewLineNumbersActionPerformed(java.awt.event.ActionEvent evt) {             
    AbstractButton button = (AbstractButton) evt.getSource(); 

         currentFrame.setLineViewer(viewLineNumbers.isSelected()); 

}            
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(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (InstantiationException ex) { 
     java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (IllegalAccessException ex) { 
     java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (javax.swing.UnsupportedLookAndFeelException ex) { 
     java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } 
    //</editor-fold> 
    java.awt.EventQueue.invokeLater(new Runnable() { 
     public void run() { 
      new OpenDemo().setVisible(true); 
     } 
    }); 
} 

// Variables declaration - do not modify      
private javax.swing.JMenuItem cut; 
private javax.swing.JMenu jMenu1; 
private javax.swing.JMenuBar jMenuBar1; 
private javax.swing.JMenuItem open; 
private javax.swing.JMenuItem selectAll; 
private javax.swing.JTabbedPane tp; 
private javax.swing.JCheckBoxMenuItem viewLineNumbers; 
// End of variables declaration     

@Override 
public void stateChanged(ChangeEvent ce) { 
    JTabbedPane sourceTabbedPane = (JTabbedPane) ce.getSource(); 
    int index = sourceTabbedPane.getSelectedIndex(); 
    try 
    { 
     currentFrame =frames.get(index); 
     currentFrame.setLineViewer(viewLineNumbers.isSelected()); 
    } 
    catch(IndexOutOfBoundsException e1){ 
    } 
} 
public int getLineAtCaret(JTextComponent component) 
{ 
    int caretPosition = component.getCaretPosition(); 
    Element root = component.getDocument().getDefaultRootElement(); 
    return root.getElementIndex(caretPosition) + 1; 
} 
public int getColumnAtCaret(JTextComponent component) 
{ 
    FontMetrics fm = component.getFontMetrics(component.getFont()); 
    int characterWidth = fm.stringWidth("0"); 
    int column = 0; 
    try 
    { 
     Rectangle r = component.modelToView(component.getCaretPosition()); 
     int width = r.x - component.getInsets().left; 
     column = width/characterWidth; 
    } 
    catch(BadLocationException ble) {} 
    return column + 1; 
} 
} 

OInternalFrame:

import java.awt.BorderLayout; 
import java.awt.Color; 
import java.awt.FontMetrics; 
import java.awt.Rectangle; 

import javax.swing.JInternalFrame; 
import javax.swing.JScrollPane; 
import javax.swing.JTextArea; 
import javax.swing.JTextField; 
import javax.swing.JTextPane; 
import javax.swing.event.CaretEvent; 
import javax.swing.event.CaretListener; 
import javax.swing.event.DocumentEvent; 
import javax.swing.event.DocumentListener; 
import javax.swing.text.BadLocationException; 
import javax.swing.text.Element; 
import javax.swing.text.JTextComponent; 


public class OInternalFrame extends JInternalFrame 
{ 
    private JTextArea textPane; 
    private JScrollPane scrollPane; 
    private JTextPane linePane; 
    private JTextField status; 
    private DocumentListener listen; 
    public OInternalFrame(String title,boolean resizable,boolean closable) 
    { 
     super(title,resizable,closable); 
     initComponents(); 
     initListeners(); 
    } 
    private void initComponents() 
    { 

     textPane = new JTextArea(); 
     linePane = new JTextPane(); 
     status = new JTextField(); 
     scrollPane = new JScrollPane(); 
     textPane.setFont(new java.awt.Font("Miriam Fixed", 0, 13)); 
     status.setBackground(Color.LIGHT_GRAY); 

     linePane.setEditable(false); 
     linePane.setSize(50,50); 
     linePane.setFont(new java.awt.Font("Miriam Fixed", 0, 13)); 
     status.setEditable(false); 
//  add(textPane); 

     add(scrollPane); 

     add(status,BorderLayout.SOUTH); 
     scrollPane.getViewport().add(textPane); 
     scrollPane.setRowHeaderView(linePane); 
     setVisible(true); 
     linePane.setVisible(false); 
     updateStatus(1,1); 
     scrollPane.setVisible(true); 

    } 
    private void initListeners() 
    { 
     textPane.addCaretListener(new CaretListener() { 
      @Override 
      public void caretUpdate(CaretEvent e) { 

       int linenum = 1; 
       int columnnum = 1; 
       try { 
        int caretpos = textPane.getCaretPosition(); 
        linenum=getLineAtCaret()-1; 
        columnnum=getColumnAtCaret(); 
        linenum += 1; 
       } 
       catch(Exception ex) { } 
       updateStatus(linenum, columnnum); 
      } 
     }); 
     listen = new DocumentListener(){ 
      @Override 
      public void changedUpdate(DocumentEvent de) { 
      linePane.setText(getText()); 
      } 
     @Override 
     public void insertUpdate(DocumentEvent de) { 
      linePane.setText(getText()); 
     } 
     @Override 
     public void removeUpdate(DocumentEvent de) { 
      linePane.setText(getText()); 
     } 
     }; 


     } 

    public int getLineAtCaret() 
    { 
     int line = 0; 
     int caretPosition = textPane.getCaretPosition(); 


     try { 
      line = textPane.getLineOfOffset(caretPosition); 

     } catch (BadLocationException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     return line+1; 
    } 

    public int getColumnAtCaret() 
    { 
     FontMetrics fm = textPane.getFontMetrics(textPane.getFont()); 
     int characterWidth = fm.stringWidth("0"); 
     int column = 0; 
     try 
     { 
      Rectangle r = textPane.modelToView(textPane.getCaretPosition()); 
      int width = r.x - textPane.getInsets().left; 
      column = width/characterWidth; 
     } 
     catch(BadLocationException ble) {} 
     return column + 1; 
    } 

    private void updateStatus(int linenumber, int columnnumber) 
    { 
     status.setText("Line: " + linenumber + " Column: " + columnnumber); 
    }  


    public void setText(String t) 
    { 
     System.out.println(t); 

     textPane.setText(t); 

     textPane.setCaretPosition(0); 
     textPane.setVisible(true); 
     textPane.repaint(); 
    } 
    public void setLineViewer(boolean enabled) 
    { 
     if(enabled) 
     { 
     linePane.setText(getText()); 
     linePane.setCaretPosition(0); 
     linePane.revalidate(); 
     linePane.repaint(); 

     textPane.getDocument().addDocumentListener(listen); 
     } 
     else 
     { 
      linePane.setText(""); 
      textPane.getDocument().removeDocumentListener(listen); 
     } 


     linePane.setVisible(enabled); 
    } 
    public void cut() 
    { 
     textPane.cut(); 
    } 
    public void selectAll() 
    { 
     textPane.selectAll(); 
    } 
    public String getText(){ 
     int caretPosition = textPane.getLineCount(); 

     String text = "1" + System.getProperty("line.separator"); 
     for(int i = 2; i <= caretPosition-1; i++){ 
      text += i + System.getProperty("line.separator"); 
     } 
     return text; 
    } 
} 
0

使用由DefaultEditorKit提供的操作。例如:

JMenuItem cut = new DefaultEditorKit.CutAction(); 

對於「全選」的行動,你將需要通過擴展TextAction創建自己:

class SelectAll extends TextAction 
{ 
    public SelectAll() 
    { 
     super("Select All"); 
    } 

    public void actionPerformed(ActionEvent e) 
    { 
     JTextComponent component = getFocusedComponent(); 
     component.selectAll(); 
    } 
} 

這些行動將是獲得焦點的最後文本組件上工作。

+0

@ user3709795,我給你提供了代碼。它的一行代碼來創建'Cut Action'。然後,將菜單項添加到菜單中。我不知道你需要什麼其他代碼。如果您使用默認操作,代碼工作正常。你需要擺脫所有舊代碼。這種方法實施和維護起來要容易得多。沒有必要管理「currentTextPane」,因爲這是由'TextAction'類處理的。不要重新發明輪子! – camickr

+0

我正在使用NetBeans IDE開發此項目。IDE是由IDE開發的。由IDE生成的代碼不可編輯。因此,當我創建菜單項時,我無法更改代碼。感謝您的回覆,以及如何我改變它。 – user3709795

+0

我不使用IDE,因此我不知道IDE如何工作。我花了我的時間學習Java,而不是學習IDE,因爲如果你移動到另一個IDE,那麼代碼是不可移植的。您始終可以使用JMenuItem的'setAction(...)'方法。 – camickr