Java如何将JLabel组件与JTextField关联?
在此示例中,我们将JLabel组件与关联JTextField并JPasswordField使用setLabelFor()。需要为该JLabel组件设置一个助记符,当我们按定义的键(ALT+U或ALT+P)时,将获得一个文本字段的焦点。
package org.nhooo.example.swing; import javax.swing.*; import java.awt.*; import java.awt.event.KeyEvent; public class JLabelSetForTextField extends JFrame { public JLabelSetForTextField() throws HeadlessException { initialize(); } private void initialize() { setSize(400, 200); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setLayout(new FlowLayout(FlowLayout.LEFT)); JLabel usernameLabel = new JLabel("Username: "); JLabel passwordLabel = new JLabel("Password: "); JTextField usernameField = new JTextField(20); JPasswordField passwordField = new JPasswordField(20); //在JLabel和JTextField之间建立关联,或者 //JPasswordField我们需要定义显示的助记符,然后 //调用JLabel的setLabelFor方法。 usernameLabel.setDisplayedMnemonic(KeyEvent.VK_U); usernameLabel.setLabelFor(usernameField); passwordLabel.setDisplayedMnemonic(KeyEvent.VK_P); passwordLabel.setLabelFor(passwordField); getContentPane().add(usernameLabel); getContentPane().add(usernameField); getContentPane().add(passwordLabel); getContentPane().add(passwordField); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new JLabelSetForTextField().setVisible(true); } }); } }