java - 无法让 JLabel 显示 JTextField 输入

标签 java swing jlabel jtextfield

我有我的 ProfileInput 类来存储来自对话框的 JTextField 输入。然后我将其转移到 setter 和 getter 方法。从那里我调用 AppFrame 类中的 setter 和 getter 方法。

我遇到的问题是,当我希望输入在 GUI 上显示为 JLabel 时,什么也没有显示。当我运行代码时也没有显示任何错误。关于我做错了什么的任何想法。

请注意,我是 Java 新手,正在努力学习。任何想法/有助于改进任何事情也很棒。

ProfileInput类

package GUI;

//Library imports
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;


public class ProfileInput extends Dialog {


    //array for the active drop down box
    String[] activeLabels = {"Select One", "Not Active", "Slightly Active", "Active", "Very Active"};

    public String firstNameString;


    //intilizing aspects used in the user profile dialog box
    JPanel Panel = new JPanel();
    JButton saveButton = new JButton("Save");
    JLabel firstName = new JLabel("First Name: ");
    JLabel lastName = new JLabel("Last Name: ");
    JLabel age = new JLabel("Age: ");
    JLabel weight = new JLabel("Weight: ");
    JLabel height = new JLabel("Height: ");
    JLabel weightGoal = new JLabel("Weight Goal: ");
    JLabel activeLevel = new JLabel("Active Level: ");
    JLabel completion = new JLabel("Completion By: ");
    JTextField firstNameInput = new JTextField();
    JTextField lastNameInput = new JTextField(); 
    JTextField ageInput = new JTextField();
    JTextField weightInput = new JTextField();
    JTextField heightInputFeet = new JTextField();
    JTextField heightInputInches = new JTextField();
    JTextField weightGoalInput = new JTextField();
    JComboBox activeCombo = new JComboBox(activeLabels);
    JTextField completionInput = new JTextField();


    //setup of the dialog panel
    public ProfileInput(Frame parent) {

        super(parent,true);
        userProfileInput();
        setSize(315, 380);
        setTitle("Profile Creator");
        setLocationRelativeTo(null);

    }

    public void userProfileInput() {

        //sets up the main panel for the dialog box (only panel to add to)
        Panel.setBorder(BorderFactory.createEmptyBorder(1,1,1,1));
        Panel.setLayout(null);


        //sets the location of the aspects inside the panel
        firstName.setBounds(35, 15, 150, 20);
        lastName.setBounds(35, 50, 150, 20);
        firstNameInput.setBounds(115, 15, 150, 20);
        lastNameInput.setBounds(115, 50, 150, 20);
        age.setBounds(35, 85, 120, 20);
        ageInput.setBounds(115, 85, 150, 20);
        weight.setBounds(35, 115, 150, 20 );
        weightInput.setBounds(115, 115, 150, 20);
        height.setBounds(35, 150, 150, 20);
        heightInputFeet.setBounds(115, 150, 72, 20);
        heightInputInches.setBounds(193, 150, 72, 20);
        weightGoal.setBounds(35, 185, 150, 20);
        weightGoalInput.setBounds(115, 185, 150, 20);
        activeLevel.setBounds(35, 220, 150, 20);
        activeCombo.setBounds(115,220, 150, 20);
        completion.setBounds(35, 255, 150, 20);
        completionInput.setBounds(130, 255, 120, 20);       
        saveButton.setBounds(135, 310, 65, 20);


        saveButton.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {

                //converts the inputs to a string
                firstNameString = firstNameInput.getText();


                System.out.println(firstNameString);

            }
        });



        //adds the items to the main panel on the dialog box
        Panel.add(firstName, null);
        Panel.add(lastName, null);
        Panel.add(firstNameInput, null);
        Panel.add(lastNameInput, null);
        Panel.add(age, null);
        Panel.add(ageInput, null);
        Panel.add(weight, null);
        Panel.add(weightInput, null);
        Panel.add(height, null);
        Panel.add(heightInputFeet, null);
        Panel.add(heightInputInches, null);
        Panel.add(weightGoal, null);
        Panel.add(weightGoalInput, null); 
        Panel.add(activeLevel, null);
        Panel.add(activeCombo, null);
        Panel.add(completion, null);
        Panel.add(completionInput, null);
        Panel.add(saveButton, null);


        //adds the panel to the dialog frame
        add(Panel);

    }//end of userProfileInput method


    public String getFirstName() {
        return this.firstNameString;
    }

    public void setFirstName(String firstNameString) {
        this.firstNameString = firstNameString;
    }

}

AppFrame类

 public class AppFrame extends JFrame {

        private static final long serialVersionUID = 1L;

        ProfileInput profileInput = new ProfileInput(null);
        String firstNameTest = profileInput.getFirstName();

        /**
         * Starts the frame from AppFrame method below.
         * 
         * @param args
         */
        public static void main(String[] args) {

            new AppFrame().setVisible(true);

        }//end of main Method


        /**
         * 
         * 
         */
        private AppFrame() {        

            //Initialization of panels and bars used in the main app
            JMenuBar menuBar = new JMenuBar();
            JPanel contentPane = new JPanel(new BorderLayout());
            JPanel rightPanel = new JPanel();
            JPanel profileInfo = new JPanel();

            //aspects used in the left toolbar panel
            JToolBar toolBarPanel = new JToolBar();
            JButton bloodPressureTool = new JButton();
            JButton heartRateTool = new JButton();
            JButton weightTool = new JButton();
            JButton bmiTool = new JButton();
            JButton medicationTool = new JButton();
            JButton appointmentTool = new JButton();
            JButton noteTool = new JButton();
            JButton profileTool = new JButton();
            Border etched = BorderFactory.createEtchedBorder();
            Icon bloodPIcon = new ImageIcon("/Users/BrandonGrow/git/Health-Application/src/Icons/BloodPressure.png");
            Icon heartRateIcon = new ImageIcon("/Users/BrandonGrow/git/Health-Application/src/Icons/HeartRate.png");
            Icon weightIcon = new ImageIcon("/Users/BrandonGrow/git/Health-Application/src/Icons/Weight.png");
            Icon bmiIcon = new ImageIcon("/Users/BrandonGrow/git/Health-Application/src/Icons/BMI.png");
            Icon medicationIcon = new ImageIcon("/Users/BrandonGrow/git/Health-Application/src/Icons/Medications.png");
            Icon appointmentIcon = new ImageIcon("/Users/BrandonGrow/git/Health-Application/src/Icons/DoctorAppointment.png");
            Icon noteIcon = new ImageIcon("/Users/BrandonGrow/git/Health-Application/src/Icons/Notes.png");
            Icon profileIcon = new ImageIcon("/Users/BrandonGrow/git/Health-Application/src/Icons/Profile.png");


            //aspects of the user profile panel 
            JLabel firstName = new JLabel("First Name: ");
            JLabel lastName = new JLabel("Last Name: ");
            JLabel height = new JLabel("Height: ");
            JLabel weight = new JLabel("Weight: ");
            JLabel age = new JLabel("Age: ");
            JLabel weightGoal = new JLabel("Weight Goal: ");
            JLabel activeLevel = new JLabel("Active Level: ");
            JLabel completion = new JLabel("Completion Date: ");


            //Menu Bar Headers
            JMenu file = new JMenu("File");
            JMenu go = new JMenu("Go");
            JMenu help = new JMenu("Help");


            //file drop down
            JMenuItem newEntry = new JMenuItem("Profile Creator");
            JMenuItem exportReport = new JMenuItem("Export Report");
            JMenuItem exportNotes = new JMenuItem("Export Notes");
            JMenuItem preferences = new JMenuItem("Preferences");
            JMenuItem exit = new JMenuItem("Exit");
            file.add(newEntry);
            file.addSeparator();
            file.add(exportReport);
            file.addSeparator();
            file.add(exportNotes);
            file.addSeparator();
            file.add(preferences);
            file.addSeparator();
            file.add(exit);


            //action used when the user presses the enter profile input button
            newEntry.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {

                    profileInput.setVisible(true);

                }
            });


            //allows for the program to exit when exit is clicked
            exit.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e) {

                        exitDialog();
                }
            });


            //go drop down
            JMenuItem bloodPressure = new JMenuItem("Blood Pressure");
            JMenuItem heartRate = new JMenuItem("Heart Rate");
            JMenuItem medication = new JMenuItem("Medication");
            JMenuItem weightDisplay = new JMenuItem("Weight");
            JMenuItem bmi = new JMenuItem("BMI");
            JMenuItem docAppoints = new JMenuItem("Doctor's Appointments");
            JMenuItem notes = new JMenuItem("Notes");
            JMenuItem resources = new JMenuItem("Profile");
            go.add(bloodPressure);
            go.addSeparator();
            go.add(heartRate);
            go.addSeparator();
            go.add(medication);
            go.addSeparator();
            go.add(weight);
            go.addSeparator();
            go.add(bmi);
            go.addSeparator();
            go.add(docAppoints);
            go.addSeparator();
            go.add(notes);
            go.addSeparator();
            go.add(resources);


            //help drop down
            JMenuItem usersGuide = new JMenuItem("Users Guide");
            JMenuItem about = new JMenuItem("About Personal Health Application");
            help.add(usersGuide);
            help.addSeparator();
            help.add(about);


            //adds Items to Frame
            menuBar.add(file);
            menuBar.add(go);
            menuBar.add(help);
            setJMenuBar(menuBar);


            //Panel that allows for all GUI to be ad added here
            contentPane.setBorder(BorderFactory.createEmptyBorder(1,1,1,1));
            contentPane.setBackground(Color.WHITE);
            contentPane.add(toolBarPanel, BorderLayout.WEST);
            contentPane.add(rightPanel);


            //stores the buttons for application (left)
            toolBarPanel.setOrientation(JToolBar.VERTICAL);
            toolBarPanel.setBackground(Color.white);
            toolBarPanel.setFloatable(false);;
            toolBarPanel.setBorder(etched);


            //sets the large panel on the right side of the frame.
            rightPanel.setBackground(Color.WHITE);
            rightPanel.setBorder(etched);
            rightPanel.setLayout(null);
            rightPanel.add(profileInfo, null);


            //adds the user profile info to the main screen
            profileInfo.setBounds(0, 0, 1104, 100);
            profileInfo.setBackground(Color.WHITE);
            profileInfo.setLayout(null);
            profileInfo.setBorder(etched);

            firstName.setBounds(80, 10, 80, 20);
            firstName.setFont(new java.awt.Font("Dialog", 1, 11));
            lastName.setBounds(80, 50, 80, 20);
            lastName.setFont(new java.awt.Font("Dialog", 1, 11));
            weightDisplay.setBounds(310, 10, 80, 20);
            weightDisplay.setFont(new java.awt.Font("Dialog", 1, 11));
            height.setBounds(330, 50, 80, 20);
            height.setFont(new java.awt.Font("Dialog", 1, 11));
            age.setBounds(550, 10, 80, 20);
            age.setFont(new java.awt.Font("Dialog", 1, 11));
            weightGoal.setBounds(550, 50, 80, 20);
            weightGoal.setFont(new java.awt.Font("Dialog", 1, 11));
            activeLevel.setBounds(780, 10, 80, 20);
            activeLevel.setFont(new java.awt.Font("Dialog", 1, 11));
            completion.setBounds(780, 50, 120, 20);
            completion.setFont(new java.awt.Font("Dialog", 1, 11));

            //test to see if first name displays
            JLabel firstNameInputTest = new JLabel(firstNameTest);
            firstNameInputTest.setBounds(160, 10, 80, 20);


            profileInfo.add(firstName);
            profileInfo.add(lastName);
            profileInfo.add(weightDisplay);
            profileInfo.add(height);
            profileInfo.add(age);
            profileInfo.add(weightGoal);
            profileInfo.add(completion);
            profileInfo.add(activeLevel);

//part of test to see of first name displays
            profileInfo.add(firstNameInputTest);


            //blood pressure button
            bloodPressureTool.setMaximumSize(new Dimension(90, 80));
            bloodPressureTool.setMinimumSize(new Dimension(30, 30));
            bloodPressureTool.setFont(new java.awt.Font("Dialog", 1, 10));
            bloodPressureTool.setPreferredSize(new Dimension(90, 50));
            bloodPressureTool.setBorderPainted(false);
            bloodPressureTool.setContentAreaFilled(false);
            bloodPressureTool.setVerticalTextPosition(SwingConstants.BOTTOM);
            bloodPressureTool.setHorizontalTextPosition(SwingConstants.CENTER);
            bloodPressureTool.setText("Blood Pressure");
            bloodPressureTool.setOpaque(false);
            bloodPressureTool.setMargin(new Insets(0, 0, 0, 0));
            bloodPressureTool.setSelected(true);
            bloodPressureTool.setIcon(bloodPIcon);


            //heart rate button
            heartRateTool.setMaximumSize(new Dimension(90, 80));
            heartRateTool.setMinimumSize(new Dimension(30, 30));
            heartRateTool.setFont(new java.awt.Font("Dialog", 1, 10));
            heartRateTool.setPreferredSize(new Dimension(90, 50));
            heartRateTool.setBorderPainted(false);
            heartRateTool.setContentAreaFilled(false);
            heartRateTool.setVerticalTextPosition(SwingConstants.BOTTOM);
            heartRateTool.setHorizontalTextPosition(SwingConstants.CENTER);
            heartRateTool.setText("Heart Rate");
            heartRateTool.setOpaque(false);
            heartRateTool.setMargin(new Insets(0, 0, 0, 0));
            heartRateTool.setSelected(true);
            heartRateTool.setIcon(heartRateIcon);


            //weight button
            weightTool.setMaximumSize(new Dimension(90, 80));
            weightTool.setMinimumSize(new Dimension(30, 30));
            weightTool.setFont(new java.awt.Font("Dialog", 1, 10));
            weightTool.setPreferredSize(new Dimension(90, 50));
            weightTool.setBorderPainted(false);
            weightTool.setContentAreaFilled(false);
            weightTool.setVerticalTextPosition(SwingConstants.BOTTOM);
            weightTool.setHorizontalTextPosition(SwingConstants.CENTER);
            weightTool.setText("Weight");
            weightTool.setOpaque(false);
            weightTool.setMargin(new Insets(0, 0, 0, 0));
            weightTool.setSelected(true);
            weightTool.setIcon(weightIcon);


            //BMI button
            bmiTool.setMaximumSize(new Dimension(90, 80));
            bmiTool.setMinimumSize(new Dimension(30, 30));
            bmiTool.setFont(new java.awt.Font("Dialog", 1, 10));
            bmiTool.setPreferredSize(new Dimension(90, 50));
            bmiTool.setBorderPainted(false);
            bmiTool.setContentAreaFilled(false);
            bmiTool.setVerticalTextPosition(SwingConstants.BOTTOM);
            bmiTool.setHorizontalTextPosition(SwingConstants.CENTER);
            bmiTool.setText("BMI");
            bmiTool.setOpaque(false);
            bmiTool.setMargin(new Insets(0, 0, 0, 0));
            bmiTool.setSelected(true);
            bmiTool.setIcon(bmiIcon);


            //medication button
            medicationTool.setMaximumSize(new Dimension(90, 80));
            medicationTool.setMinimumSize(new Dimension(30, 30));
            medicationTool.setFont(new java.awt.Font("Dialog", 1, 10));
            medicationTool.setPreferredSize(new Dimension(90, 50));
            medicationTool.setBorderPainted(false);
            medicationTool.setContentAreaFilled(false);
            medicationTool.setVerticalTextPosition(SwingConstants.BOTTOM);
            medicationTool.setHorizontalTextPosition(SwingConstants.CENTER);
            medicationTool.setText("Medication");
            medicationTool.setOpaque(false);
            medicationTool.setMargin(new Insets(0, 0, 0, 0));
            medicationTool.setSelected(true);
            medicationTool.setIcon(medicationIcon);


            //appointment button
            appointmentTool.setMaximumSize(new Dimension(90, 80));
            appointmentTool.setMinimumSize(new Dimension(30, 30));
            appointmentTool.setFont(new java.awt.Font("Dialog", 1, 10));
            appointmentTool.setPreferredSize(new Dimension(90, 50));
            appointmentTool.setBorderPainted(false);
            appointmentTool.setContentAreaFilled(false);
            appointmentTool.setVerticalTextPosition(SwingConstants.BOTTOM);
            appointmentTool.setHorizontalTextPosition(SwingConstants.CENTER);
            appointmentTool.setText("Appointments");
            appointmentTool.setOpaque(false);
            appointmentTool.setMargin(new Insets(0, 0, 0, 0));
            appointmentTool.setSelected(true);
            appointmentTool.setIcon(appointmentIcon);


            //note button
            noteTool.setMaximumSize(new Dimension(90, 80));
            noteTool.setMinimumSize(new Dimension(30, 30));
            noteTool.setFont(new java.awt.Font("Dialog", 1, 10));
            noteTool.setPreferredSize(new Dimension(90, 50));
            noteTool.setBorderPainted(false);
            noteTool.setContentAreaFilled(false);
            noteTool.setVerticalTextPosition(SwingConstants.BOTTOM);
            noteTool.setHorizontalTextPosition(SwingConstants.CENTER);
            noteTool.setText("Notes");
            noteTool.setOpaque(false);
            noteTool.setMargin(new Insets(0, 0, 0, 0));
            noteTool.setSelected(true);
            noteTool.setIcon(noteIcon);


            //profile button
            profileTool.setMaximumSize(new Dimension(90, 80));
            profileTool.setMinimumSize(new Dimension(30, 30));
            profileTool.setFont(new java.awt.Font("Dialog", 1, 10));
            profileTool.setPreferredSize(new Dimension(90, 50));
            profileTool.setBorderPainted(false);
            profileTool.setContentAreaFilled(false);
            profileTool.setVerticalTextPosition(SwingConstants.BOTTOM);
            profileTool.setHorizontalTextPosition(SwingConstants.CENTER);
            profileTool.setText("Profile");
            profileTool.setOpaque(false);
            profileTool.setMargin(new Insets(0, 0, 0, 0));
            profileTool.setSelected(true);
            profileTool.setIcon(profileIcon);


            //adding buttons to toolBarPanel
            toolBarPanel.add(bloodPressureTool);
            toolBarPanel.add(heartRateTool);
            toolBarPanel.add(weightTool);
            toolBarPanel.add(bmiTool);
            toolBarPanel.add(medicationTool);
            toolBarPanel.add(appointmentTool);
            toolBarPanel.add(noteTool);
            toolBarPanel.add(profileTool);


            //sets up the actual frame 
            setSize(1200,800);
            setResizable(false);
            setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
            add(contentPane);


            //allows for the program to shut down by using x and then using the dialog
            addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    exitDialog();
                }
            });

        }//end of appFrame Method

最佳答案

上面的代码有几个问题,但最重要的是,当您绝对需要使用模式对话框时,您正在使用非模式对话框。由于它是无模式的,因此当对话框可见时,调用代码中的程序流不会停止,因此您在对话框上立即调用 getFirstName()在关闭之前以及用户有机会输入任何信息之前打开。另一方面,模式对话框将卡住调用代码中的程序流,并且直到对话框不再可见时程序流才会恢复。

问题与建议:

  • 首先,确保对话框窗口是模态对话框。
  • 但在此之前,不要使用 Dialog、Panel 和其他 AWT 组件类,而是使用 Swing 类——JDialog、JPanel 等。
  • 您可以使用适当的构造函数将 JDialog 设置为模态,将 ModalityType.APPLICATION_MODAL 作为适当构造函数中的参数传递(请参阅 API),也可以通过方法进行设置.
  • 无论哪种方式,请确保在将对话框设置为可见之前进行设置。
  • 这样做,当您查询对话框的状态时,您可以确信在您尝试从对话框中提取信息之前,用户至少有机会与对话框进行交互。
  • 请务必在将对话框设置为可见后查询该对话框并分配结果。
<小时/>

编辑,我现在看到您甚至在将对话框设置为可见之前就调用了String firstNameTest = profileInput.getFirstName();,就好像firstNameTest String(在这个阶段显然为空)一样,一旦对话框被可视化和处理,就会神奇地更新,但抱歉,Java 中没有魔法,字段不会自行更新。再次强调,此时不要设置 firstNameTest 字段,而应仅在显示对话框并进行处理之后设置。

<小时/>

接下来我们需要讨论 null 布局和 setBounds。你真的不想走这条路,相信我。

<小时/> <小时/>

例如:

public class AppFrame extends JFrame {

    private static final long serialVersionUID = 1L;    
    // !! the JLabel needs to be a field so it can be set in the ActionListener
    private JLabel firstNameInputTest = new JLabel(""); 
    private ProfileInput profileInput = null;  //!! let this start out as null
    // !! worthless code, get rid of
    // String firstNameTest = profileInput.getFirstName();

    public static void main(String[] args) {
        // .... etc

以及我们创建/显示对话框的 ActionListener:

newEntry.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        //!! create JDialog in a lazy fashion
        if (profileInput == null) {
            // create dialog, passing in the JFrame
            profileInput = new ProfileInput(AppFrame.this);
        }
        profileInput.setVisible(true); // display the *modal* dialog

        // program flow is frozen here until JDialog is no longer visible

        // query dialog for its contents
        String firstNameTxt = profileInput.getFirstName();
        // and use in GUI
        firstNameInputTest.setText(firstNameTxt);
    }
});

我们不想在方法或构造函数中声明 JLabel,因为这样做的话,它在整个类中将不可见。所以...

private AppFrame() { // ??? private ???

    // ..... 


    // test to see if first name displays
    // !! JLabel firstNameInputTest = new JLabel(firstNameTest);  // No!!!

最后,一个非常简单的示例 JDialog 来演示我正在讨论的内容:

@SuppressWarnings("serial")
public class ProfileInput extends JDialog {
    private JTextField firstNameField = new JTextField(10);

    public ProfileInput(JFrame frame) {
        // make it modal!
        super(frame, "Profile Input", ModalityType.APPLICATION_MODAL);

        JPanel panel = new JPanel();
        panel.add(new JLabel("Enter First Name:"));
        panel.add(firstNameField);
        panel.add(new JButton(new SubmitAction("Submit", KeyEvent.VK_S)));

        add(panel);
        pack();
        setLocationRelativeTo(frame);
    }

    public String getFirstName() {
        return firstNameField.getText();
    }

    private class SubmitAction extends AbstractAction {
        public SubmitAction(String name, int mnemonic) {
            super(name);
            putValue(MNEMONIC_KEY, mnemonic);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            ProfileInput.this.dispose();
        }
    }
}    

关于java - 无法让 JLabel 显示 JTextField 输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37150697/

相关文章:

java - 在实时图中用不同的值更新 JLabel

Java JFrame 鼠标监听器

java - SQLite语法错误但语句完全正确

Java - 使用 Swing 框架和抽象类防止 Java 堆内存错误

java - 使用逻辑 AND 处理 hibernate 多个条件

java - 如何从 JTable 中获取数据?

swing - 在 JavaFX GUI 设计中利用观察者模式

java - 将 JLabel 放置在 JFrame 的左上角

Java AWT drawString() 不显示在窗口上

java - 无法使用 dll 注入(inject)和 JNI 通过 oracle 表单 GUI 对象附加