user3556256
user3556256

Reputation: 47

How to add JLabel to existing JTextField

I want to add Capslock label to the status JtextField. Status has got line and column values. I want to add capslock with line and column. I have tried adding updateStatus() method, but it does not work as expected.

Sample code:

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;                
}

I write StatusPanel class as shown below:

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.
        }
    }); 
}
}

Upvotes: 1

Views: 725

Answers (1)

camickr
camickr

Reputation: 324207

  1. In the "if" code you have a single statement. In the "else" statement you have 2 statements. Don't you think the code should be the same except for the text?

  2. Also, you should NOT be using a text field to display the text. Instead you should be using a panel with multiple labels. One label for the row/column position. Another label for the Caps Lock status. Then you only update the text for the label that changes.

.Caps lock enable/disable not update the all the opened Documents.

Then you have a couple of solutions:

  1. Your status bar should be common for the frame, not the Document. So the labels will be shared by all Documents. This means that whenever a Document gains focus you would need to update the caret position but the Caps Lock will still be correct from the last Document.

  2. Or, you could create the Caps Lock field as a non-editable JTextField. Then you can share the Document of the text field with all text field. This mean when you update the text field it will be reflected on all documents.

So you would need to pass in the shared text field Document any time you create a new document for your application. Then to create the text field you would use:

JTextField textField = new JTextField( sharedDocument );

Edit:

When you create the component for the frame you would have code something like:

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

Then in this custom class you add the components to display the data you want displayed. You also need to add methods like setRowColumn(...) and setCapsLock(...) to display the text you want to see for those components.

Then you need to create another custom class MyInternalFrame that extend JInternalFrame. Then when you create this class you use:

MyInternalFrame internal = new MyInternalFrame(status);

So now your custom internal frame has access to the status bar and you can update the status bar from any Document that your create.

Another Edit:

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();
            }
        });
    }
}

Upvotes: 1

Related Questions