简体   繁体   English

为什么在运行 GUI 时 JLabel 或 JButton 不显示?

[英]Why won't the JLabels or JButtons show up when running the GUI?

I have been playing around with numerous solutions but none of them seems to work.我一直在尝试各种解决方案,但似乎都没有用。 in the constructor, there is a default initComponents() which I can not change.在构造函数中,有一个我无法更改的默认initComponents() So I created a second method called myComponents() .所以我创建了第二个方法myComponents() The class I am using extends JFrame so I do not need to create another frame in any initializer.我正在使用的 class 扩展JFrame ,所以我不需要在任何初始化程序中创建另一个框架。 I created a JPanel with a vertical Boxlayout , 2 labels, 1 text field, and 1 button.我创建了一个带有垂直Boxlayout 、2 个标签、1 个文本字段和 1 个按钮的JPanel I added the panel to the frame then I added all the components to the panel then packed everything.我将面板添加到框架,然后将所有组件添加到面板,然后打包所有内容。

I am unsure as to why nothing shows up besides the frame when it is run.我不确定为什么在运行时除了框架之外什么都没有显示。

import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

/**
 *
 * @author gpbli
 */
public class MAINFRAME extends javax.swing.JFrame {

    /**
     * Creates new form MAINFRAME
     */
    //MAINFRAME frame = new MAINFRAME();
    JPanel homescreen = new JPanel();

    JLabel numOfIngredLabel = new JLabel();
    JTextField numOfIngred = new JTextField();
    JButton okButton = new JButton();
    JLabel logo = new JLabel();

    ImageIcon img = new ImageIcon("logo_resized.png");
    public MAINFRAME() {
        initComponents();
        myComponents();
    }
    public void myComponents(){
        BoxLayout box = new BoxLayout(homescreen,BoxLayout.Y_AXIS);
        homescreen.setLayout(box);
    
    numOfIngredLabel.setText("How many Ingredients");
    numOfIngred.setText("");
    okButton.setText("OK");
    logo.setText(" ");
    logo.setIcon(img);
    
    add(homescreen);
    homescreen.add(logo);
    homescreen.add(numOfIngredLabel);
    homescreen.add(numOfIngred);
    homescreen.add(okButton);
    
    numOfIngredLabel.setVisible(true);
    numOfIngred.setVisible(true);
    okButton.setVisible(true);
    logo.setVisible(true);
    
    pack();
    revalidate();
    
    
}
/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    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)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 300, Short.MAX_VALUE)
    );

    pack();
}// </editor-fold>                        

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    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(MAINFRAME.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(MAINFRAME.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(MAINFRAME.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(MAINFRAME.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    
    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new MAINFRAME().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
// End of variables declaration                   
}

The appearance of initComponents() suggests the IDE is expecting the programmer to use the GUI builder, while the myComponents() is the programmer taking control of the GUI construction to code it by hand. initComponents()的出现表明 IDE 期望程序员使用 GUI 构建器,而myComponents()是程序员控制 GUI 构造以手动编码。

Use one or the other.使用一个或另一个。 I'd always use the latter, which does not require the JFrame to be extended.我总是使用后者,它不需要扩展JFrame In fact, creating the main view of the GUI in a JPanel and adding that single component to a JFrame is the way we would typically recommend.事实上,在JPanel中创建 GUI 的主视图并将该单个组件添加到JFrame是我们通常推荐的方式。

Note: See also the accepted answer to: Netbeans GUI editor generating its own incomprehensible code注意:另请参阅已接受的答案Netbeans GUI editor generating its own incomprehensible code

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM