如何使用swing在多个文档之间切换大写锁定

时间:2014-08-13 11:01:34

标签: java swing jpanel awt capslock

我已经为大写锁定编写了代码。当它在状态栏上启用它时,当它被禁用时它在状态栏上显示为OFF。问题是当我打开多个文档然后在Doc1中启用大写锁定时,在这种情况下Doc2未启用。我想显示启用/禁用所有已打开的文档。 在这里我写了两个班。 主要课程:

public class OpenDemNew extends javax.swing.JFrame implements ChangeListener{
private ArrayList<OInternalFrame> frames = new ArrayList<OInternalFrame>();
private OInternalFrame currentFrame;
int i=0;
public OpenDemNew() {
initComponents();
}
@SuppressWarnings("unchecked")                         
private void initComponents() {

tp = new javax.swing.JTabbedPane();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
open = new javax.swing.JMenuItem();
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);
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(OpenDemNew.this, "Select File", FileDialog.LOAD);
fd.setVisible(true);
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(OpenDemNew.class.getName()).log(Level.SEVERE, null, ex);
         }
   } catch (FileNotFoundException ex) {
        Logger.getLogger(OpenDemNew.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(OpenDemNew.class.getName()).log(Level.SEVERE, null, ex);
   }
   tp.add(internalFrame);
   tp.setSelectedIndex(i-1);  
   tp.addChangeListener(this);
   frames.add(internalFrame);
   currentFrame=internalFrame;
   currentFrame.setText(t);
   currentFrame.setVisible(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(OpenDemNew.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
    java.util.logging.Logger.getLogger(OpenDemNew.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
    java.util.logging.Logger.getLogger(OpenDemNew.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
    java.util.logging.Logger.getLogger(OpenDemNew.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
        new OpenDemNew().setVisible(true);
    }
});
}                   
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem open;
private javax.swing.JTabbedPane tp;                  

@Override
public void stateChanged(ChangeEvent ce) {
JTabbedPane sourceTabbedPane = (JTabbedPane) ce.getSource();
int index = sourceTabbedPane.getSelectedIndex();
try
{
  currentFrame =frames.get(index);
}
catch(IndexOutOfBoundsException e1){
}

} }

另一个程序是OInternalFrame.OinternalFrame具有状态栏和大写锁定逻辑。 代码是:

public class OInternalFrame extends JInternalFrame
{
private JTextArea textPane;
private JScrollPane scrollPane;
JPanel statusbarPanel;
JLabel statusLabel;
JLabel capsLabel;
private DocumentListener listen;
public OInternalFrame(String title,boolean resizable,boolean closable)
{
    super(title,resizable,closable);
    initComponents();
    initListeners();
}
private void initComponents()
{

    textPane = new JTextArea();
    statusbarPanel=new JPanel();
    statusLabel=new JLabel();
    capsLabel=new JLabel();
    scrollPane = new JScrollPane();
    textPane.setFont(new java.awt.Font("Miriam Fixed", 0, 13));
    add(scrollPane);
    statusbarPanel.add(statusLabel);
    statusbarPanel.add(capsLabel);
    add(statusbarPanel,BorderLayout.SOUTH);
    scrollPane.getViewport().add(textPane); 
    setVisible(true);
    updateStatus(1,1);
    if(Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK)){
        capsLabel.setText("ON");
    }
    else {
         capsLabel.setText("OFF");
    }
    scrollPane.setVisible(true);

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

            int linenum = 1;
            int columnnum = 1;
            try {
                linenum=getLineAtCaret()-1;
                columnnum=getColumnAtCaret();
                linenum += 1;
            }
            catch(Exception ex) { }
            updateStatus(linenum, columnnum);
        }
    });
    textPane.addKeyListener(new KeyListener() {

        @Override
        public void keyTyped(KeyEvent arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void keyReleased(KeyEvent arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void keyPressed(KeyEvent arg0) {
            if(Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK)){
                   capsLabel.setText("ON");
            }
            else{
                    capsLabel.setText("OFF");
            }

        }
    });
     }
public void setText(String t)
{
    textPane.setText(t);
    textPane.setCaretPosition(0);
    textPane.setVisible(true);
    textPane.repaint();
}

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) 
{
    statusLabel.setText("Line: " + linenumber + " Column: " + columnnumber);
}    

}

0 个答案:

没有答案