Java Swing Tutorial - Java JLabel .getHorizontalTextPosition ()








Syntax

JLabel.getHorizontalTextPosition() has the following syntax.

public int getHorizontalTextPosition()

Example

In the following code shows how to use JLabel.getHorizontalTextPosition() method.

import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
//from w  w w .j a  v a 2s .c om
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

public class Main {

  public static void main(final String args[]) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel userPanel = new JPanel(new BorderLayout());
    JLabel userLabel = new JLabel("Username: ");
    userLabel.setDisplayedMnemonic(KeyEvent.VK_U);
    JTextField userTextField = new JTextField();
    userLabel.setLabelFor(userTextField);
    userPanel.add(userLabel, BorderLayout.WEST);
    userPanel.add(userTextField, BorderLayout.CENTER);

    System.out.println(userLabel.getHorizontalTextPosition());
    
    JPanel passPanel = new JPanel(new BorderLayout());
    JLabel passLabel = new JLabel("Password: ");
    passLabel.setDisplayedMnemonic('p');
    JPasswordField passTextField = new JPasswordField();
    passLabel.setLabelFor(passTextField);
    passPanel.add(passLabel, BorderLayout.WEST);
    passPanel.add(passTextField, BorderLayout.CENTER);

    JPanel panel = new JPanel(new BorderLayout());
    panel.add(userPanel, BorderLayout.NORTH);
    panel.add(passPanel, BorderLayout.SOUTH);
    frame.add(panel, BorderLayout.NORTH);

    frame.setSize(250, 150);
    frame.setVisible(true);
  }

}