【问题标题】:how can I use JTextField and JLabel together?如何同时使用 JTextField 和 JLabel?
【发布时间】:2017-05-09 22:57:38
【问题描述】:

我需要一个标签上的文本字段,但是当我运行此代码时,屏幕上没有文本字段。我该如何解决它。

JFrame jf = new JFrame() ;

JPanel panel = new JPanel() ;

JLabel label = new JLabel() ;

JTextField tField = new JTextField("asd" , 10) ;

label.add( tField ) ;
panel.add( label ) ;

jf.setSize( 500,400 ) ;
jf.add( panel ) ;
jf.setVisible(true) ;

【问题讨论】:

    标签: java swing jpanel jlabel jtextfield


    【解决方案1】:

    JLabel 没有默认布局管理器,因此当您的 JTextField 被添加到 JLabel 时,它不会显示,因为标签不知道 如何 显示它。

    根据您要实现的目标,可以有多种方法来解决此问题:

    • 给 JLabel 一个布局管理器,然后将 JTextField 添加到它:但是 JTextField 覆盖 JLabel、它的文本(如果有的话)和它的图标(如果有的话) ,不好。
    • 创建一个 JPanel 来容纳两者,并为其提供适当的布局管理器:这可能是一个不错的选择。
    • 使用可以轻松将它们关联起来的布局管理器将它们添加到同一个 JPanel:另一个不错的选择。 GridBagLayout 非常适合这个。

    不要忘记调用 JLabel 的 setLabelFor(...) 方法以将其与 JTextField 紧密关联,根据 JLabel Tutorial

    例如:

    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.event.KeyEvent;
    import java.util.HashMap;
    import java.util.Map;
    import javax.swing.*;
    
    public class GridBagEg {
        private static void createAndShowGui() {
            PlayerEditorPanel playerEditorPane = new PlayerEditorPanel();
    
            int result = JOptionPane.showConfirmDialog(null, playerEditorPane, "Edit Player",
                    JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
            if (result == JOptionPane.OK_OPTION) {
                // TODO: do something with info
    
                for (PlayerEditorPanel.FieldTitle fieldTitle : PlayerEditorPanel.FieldTitle.values()) {
                    System.out.printf("%10s: %s%n", fieldTitle.getTitle(),
                            playerEditorPane.getFieldText(fieldTitle));
                }
            }
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGui();
                }
            });
        }
    }
    
    @SuppressWarnings("serial")
    class PlayerEditorPanel extends JPanel {
        enum FieldTitle {
            NAME("Name", KeyEvent.VK_N), SPEED("Speed", KeyEvent.VK_P), STRENGTH("Strength", KeyEvent.VK_T);
            private String title;
            private int mnemonic;
    
            private FieldTitle(String title, int mnemonic) {
                this.title = title;
                this.mnemonic = mnemonic;
            }
    
            public String getTitle() {
                return title;
            }
    
            public int getMnemonic() {
                return mnemonic;
            }
        };
    
        private static final Insets WEST_INSETS = new Insets(5, 0, 5, 5);
        private static final Insets EAST_INSETS = new Insets(5, 5, 5, 0);
        private Map<FieldTitle, JTextField> fieldMap = new HashMap<FieldTitle, JTextField>();
    
        public PlayerEditorPanel() {
            setLayout(new GridBagLayout());
            setBorder(BorderFactory.createCompoundBorder(
                    BorderFactory.createTitledBorder("Player Editor"),
                    BorderFactory.createEmptyBorder(5, 5, 5, 5)));
            GridBagConstraints gbc;
            for (int i = 0; i < FieldTitle.values().length; i++) {
                FieldTitle fieldTitle = FieldTitle.values()[i];
                JLabel label = new JLabel(fieldTitle.getTitle() + ":", JLabel.LEFT);
                JTextField textField = new JTextField(10);
                label.setDisplayedMnemonic(fieldTitle.getMnemonic());
                label.setLabelFor(textField);
                gbc = createGbc(0, i);
                add(label, gbc);
                gbc = createGbc(1, i);
                add(textField, gbc);
    
                fieldMap.put(fieldTitle, textField);
            }
        }
    
        private GridBagConstraints createGbc(int x, int y) {
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = x;
            gbc.gridy = y;
            gbc.gridwidth = 1;
            gbc.gridheight = 1;
    
            gbc.anchor = (x == 0) ? GridBagConstraints.WEST : GridBagConstraints.EAST;
            gbc.fill = (x == 0) ? GridBagConstraints.BOTH : GridBagConstraints.HORIZONTAL;
    
            gbc.insets = (x == 0) ? WEST_INSETS : EAST_INSETS;
            gbc.weightx = (x == 0) ? 0.1 : 1.0;
            gbc.weighty = 1.0;
            return gbc;
        }
    
        public String getFieldText(FieldTitle fieldTitle) {
            return fieldMap.get(fieldTitle).getText();
        }
    
    }
    

    显示为

    请注意,JLabel 在助记符上带有下划线,当在 alt 键组合中按下时,这些字符会将焦点带到 JLabel 通过 setLabelFor(...) 链接到的 JTextField 上,这是由以下代码引起的:

    FieldTitle fieldTitle = FieldTitle.values()[i]; // an enum that holds label texts
    JLabel label = new JLabel(fieldTitle.getTitle() + ":", JLabel.LEFT); // create JLabel
    JTextField textField = new JTextField(10);  // create JTextField
    
    // set the label's mnemonic -- brings focus to the linked text field
    label.setDisplayedMnemonic(fieldTitle.getMnemonic());   
    
    // *** here we *link* the JLabel with the JTextField
    label.setLabelFor(textField);  
    

    【讨论】:

      猜你喜欢
      • 2016-05-17
      • 2018-01-25
      • 2016-10-14
      • 1970-01-01
      • 2022-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多