如何将JLabel添加到现有的JTextField

时间:2014-08-12 08:05:17

标签: java swing awt jlabel jtextfield

我想将Capslock标签添加到状态JtextField。状态有行和列值。我想添加带有行和列的大写字母。我尝试添加updateStatus()方法,但它无法按预期工作。

示例代码:

public class CapsLock extends javax.swing.JFrame {
    JTextField status;
    int i=0;
    JTextArea textArea;
    JLabel capsLock;
    public CapsLock() {
        initComponents();
        status=new JTextField();
        capsLock=new JLabel();
        updateStatus(1,1);
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        tabbedPane = new javax.swing.JTabbedPane();
        jMenuBar1 = new javax.swing.JMenuBar();
        file = new javax.swing.JMenu();
        newFile = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        file.setText("File");

        newFile.setText("NewFile");
        newFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newFileActionPerformed(evt);
            }
        });
        file.add(newFile);

        jMenuBar1.add(file);

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

        pack();
    }// </editor-fold>                        
    private void updateStatus(int linenumber, int columnnumber) {
        status.setText("ln: " + linenumber + " Col: " + columnnumber);
     }
    private void newFileActionPerformed(java.awt.event.ActionEvent evt) {                                        
        final JInternalFrame internalFrame = new JInternalFrame("");
        i++;
        internalFrame.setName("Doc "+i);
        internalFrame.setClosable(true);
        internalFrame.setAutoscrolls(true);
        textArea=new JTextArea();
        textArea.addKeyListener(new KeyListener() {
            @Override
            public void keyTyped(KeyEvent ke) {
            }

            @Override
            public void keyPressed(KeyEvent ke) {
              if(Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK)){
                   capsLock.setText("ON");
              }
              else{
                    capsLock.setText("OFF");
                    status.setText(capsLock.getText());
              }  
            }
            @Override
            public void keyReleased(KeyEvent ke) {
            }
        });
        textArea.addCaretListener(new CaretListener() {
        @Override
        public void caretUpdate(CaretEvent e) {
              JTextArea editArea = (JTextArea)e.getSource();
              int linenum = 1;
              int columnnum = 1;
               try {
                    int caretpos = editArea.getCaretPosition();
                    linenum = editArea.getLineOfOffset(caretpos);
                    columnnum = caretpos - editArea.getLineStartOffset(linenum);
                    linenum += 1;
                }
                catch(Exception ex) { }
                updateStatus(linenum, columnnum);
            }
        });

        status.setBackground(Color.LIGHT_GRAY);
        status.setEditable(false);
        internalFrame.add(textArea);
        internalFrame.add(status,BorderLayout.SOUTH);
        tabbedPane.add(internalFrame);
    }                                       

    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(CapsLock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CapsLock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CapsLock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CapsLock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new CapsLock().setVisible(true);
            }
        });
    }

    private javax.swing.JMenu file;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem newFile;
    private javax.swing.JTabbedPane tabbedPane;                
}

我写了StatusPanel类,如下所示:

public class StatusPanel extends JPanel{

InternalFrame currentFrame;
private JLabel statusLabel;
JLabel capsLabel;
public StatusPanel(){
    statusLabel=new JLabel();
    capsLabel=new JLabel();
    add(statusLabel);
    add(capsLabel);
    updateStatus(1,1);
}
public void setRowColumn(){
    currentFrame.textPane.addCaretListener(new CaretListener() {
        private KeyEvent KeyEvent;
        @Override
        public void caretUpdate(CaretEvent e) {

            int linenum = 1;
            int columnnum = 1;
            try {
                int caretpos = currentFrame.textPane.getCaretPosition();
                linenum=currentFrame.getLineAtCaret()-1;
                columnnum=currentFrame.getColumnAtCaret();
                linenum += 1;
            }
            catch(Exception ex) { }
            updateStatus(linenum, columnnum);
        }
    });      
}
private void updateStatus(int linenumber, int columnnumber) 
{
    statusLabel.setText("Line: " + linenumber +"  "+ " Column: " + columnnumber);
}
public void setCapslock(){
    currentFrame.textPane.addKeyListener(new KeyListener() {
        @Override
        public void keyTyped(KeyEvent ke) {
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

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

        @Override
        public void keyReleased(KeyEvent ke) {
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
    }); 
}
}

1 个答案:

答案 0 :(得分:1)

  1. 在“if”代码中,您只有一个语句。在“else”语句中,您有2个语句。除了文本之外,您认为代码应该是否相同?

  2. 此外,您不应使用文本字段来显示文本。相反,您应该使用具有多个标签的面板。行/列位置的一个标签。 Caps Lock状态的另一个标签。然后,您只更新更改标签的文本。

  3.   

    .Caps lock启用/禁用不更新所有打开的文档。

    然后你有几个解决方案:

    1. 您的状态栏对于框架而言应该是通用的,而不是文档。因此标签将由所有文档共享。这意味着只要文档获得焦点,您就需要更新插入符号位置,但Caps Lock在上一个文档中仍然是正确的。

    2. 或者,您可以将Caps Lock字段创建为不可编辑的JTextField。然后,您可以与所有文本字段共享文本字段的文档。这意味着当您更新文本字段时,它将反映在所有文档中。

    3. 因此,只要为应用程序创建新文档,就需要传入共享文本字段Document。然后创建您将使用的文本字段:

      JTextField textField = new JTextField( sharedDocument );
      

      编辑:

      为框架创建组件时,您将拥有类似以下代码:

      StatusPanel status = new StatusPanel();
      frame.add(status, ...);
      

      然后在此自定义类中添加组件以显示要显示的数据。您还需要添加setRowColumn(...)setCapsLock(...)等方法,以显示要为这些组件查看的文本。

      然后,您需要创建另一个扩展MyInternalFrame的自定义类JInternalFrame。然后,当您创建此类时,使用:

      MyInternalFrame internal = new MyInternalFrame(status);
      

      现在您的自定义内部框架可以访问状态栏,您可以从您创建的任何文档更新状态栏。

      另一个编辑:

      import java.awt.*;
      import java.awt.event.*;
      import javax.swing.*;
      import javax.swing.event.*;
      import javax.swing.text.*;
      
      public class Status extends JPanel
      {
          public Status()
          {
              setLayout( new BorderLayout() );
      
              StatusPanel status = new StatusPanel();
              add(status, BorderLayout.SOUTH);
      
              DocumentPanel document = new DocumentPanel( status );
              add(document, BorderLayout.CENTER);
          }
      
          class StatusPanel extends JPanel
          {
              JLabel caretStatus = new JLabel("Caret Offset: 0");
      
              public StatusPanel()
              {
                  add( caretStatus );
              }
      
              public void updateCaretStatus(String status)
              {
                  caretStatus.setText( status );
              }
          }
      
          class DocumentPanel extends JPanel
          {
              private StatusPanel status;
              private JTextArea textArea;
      
              public DocumentPanel(StatusPanel statusPanel)
              {
                  status = statusPanel;
      
                  textArea = new JTextArea(5, 30);
                  add( new JScrollPane( textArea ) );
      
                  textArea.addCaretListener( new CaretListener()
                  {
                      @Override
                      public void caretUpdate(CaretEvent e)
                      {
                          status.updateCaretStatus( "Caret Offset: " + textArea.getCaretPosition() );
                      }
                  });
              }
          }
      
          private static void createAndShowGUI()
          {
              JFrame frame = new JFrame("Status");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.add( new Status() );
              frame.setLocationByPlatform( true );
              frame.pack();
              frame.setVisible( true );
          }
      
          public static void main(String[] args)
          {
              EventQueue.invokeLater(new Runnable()
              {
                  public void run()
                  {
                      createAndShowGUI();
                  }
              });
          }
      }