【问题标题】:I've trying to add a JPanel to my JFrame on click,but i dont find my error我试图在点击时将 JPanel 添加到我的 JFrame,但我没有找到我的错误
【发布时间】:2016-08-22 19:54:37
【问题描述】:

我正在努力恢复一些 Java 技能,因为我在 Web 开发领域工作了很长时间。现在我只是创建一个主 Jframe,其中有一个小菜单和一个类 createSchueler 扩展 JPanel。

如果你进入菜单点击 Neu > Schueler 我想做什么

应该创建一个新的 Jpanel 并将其添加到窗口中

主类

public class MainWindow {

private JFrame frame;


/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                MainWindow window = new MainWindow();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the application.
 */
public MainWindow() {
    initialize();
}

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 807, 541);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    JPanel createSchueler = new createSchueler();

    JMenuBar menuBar = new JMenuBar();
    frame.setJMenuBar(menuBar);

    JMenu mnNewMenu = new JMenu("Neu");
    mnNewMenu.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            createSchueler.setVisible(true);
            frame.getContentPane().add(createSchueler);

        }
    });
    menuBar.add(mnNewMenu);

    JMenuItem mntmSchler = new JMenuItem("Sch\u00FCler");
    mnNewMenu.add(mntmSchler);

    JMenu mnBearbeiten = new JMenu("Bearbeiten");
    menuBar.add(mnBearbeiten);

    JMenuItem mntmSchler_1 = new JMenuItem("Sch\u00FCler");
    mnBearbeiten.add(mntmSchler_1);


  }
}

createSchueler 类扩展了我想添加到框架中的 JPanel

public class createSchueler extends JPanel {
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;

/**
 * Create the panel.
 */
public createSchueler() {
    setLayout(null);

    JLabel lblNeuenSchuelerErstellen = new JLabel("Neuen Schueler erstellen");
    lblNeuenSchuelerErstellen.setFont(new Font("Tahoma", Font.PLAIN, 22));
    lblNeuenSchuelerErstellen.setBounds(29, 27, 268, 27);
    add(lblNeuenSchuelerErstellen);

    JLabel lblVorname = new JLabel("Vorname");
    lblVorname.setBounds(29, 102, 46, 14);
    add(lblVorname);

    textField = new JTextField();
    textField.setBounds(97, 99, 172, 20);
    add(textField);
    textField.setColumns(10);

    JLabel lblNachname = new JLabel("Nachname");
    lblNachname.setBounds(29, 133, 69, 14);
    add(lblNachname);

    textField_1 = new JTextField();
    textField_1.setBounds(97, 130, 172, 20);
    add(textField_1);
    textField_1.setColumns(10);

    JLabel lblGeburtstag = new JLabel("Geburtstag");
    lblGeburtstag.setBounds(29, 169, 69, 14);
    add(lblGeburtstag);

    textField_2 = new JTextField();
    textField_2.setBounds(97, 166, 172, 20);
    add(textField_2);
    textField_2.setColumns(10);

    ButtonGroup bg = new ButtonGroup();

    JRadioButton rdbtnMnnlich = new JRadioButton("M\u00E4nnlich");
    rdbtnMnnlich.setBounds(29, 206, 69, 23);
    bg.add(rdbtnMnnlich);

    JRadioButton rdbtnWeiblich = new JRadioButton("Weiblich");
    rdbtnWeiblich.setBounds(97, 206, 109, 23);
    bg.add(rdbtnWeiblich);



   }
 }

希望一切都很重要:D

【问题讨论】:

    标签: java swing jframe jpanel add


    【解决方案1】:

    使用 CardLayout 来交换 JPanel,而不是手动添加它们。如果您必须手动添加它们,请确保接收容器的布局管理器能够胜任任务并很好地处理添加。例如 BorderLayout 会很好,但 GroupLayout 不会。如果您确实手动添加或删除,请在这些更改后调用容器上的revalidate();repaint()

    另外,您在添加的 JPanel 和 contentPane 中使用了 null 布局,这将完全破坏它的 preferredSize 计算。永远不要使用这种布局。学习使用然后使用布局管理器。这是你的主要错误。

    有关更多信息,请阅读:Why is it frowned upon to use a null layout in Swing?

    例如:

    import java.awt.CardLayout;
    import java.awt.event.ActionEvent;
    import javax.swing.*;
    
    public class MainGui {
        public static final String SCHUELER_PANEL = "Schueler Panel";
        public static final String EMPTY = "Empty Panel";
        private JPanel mainPanel = new JPanel();
        private JMenuBar menuBar = new JMenuBar();
        private CardLayout cardLayout = new CardLayout();
        private SchuelerPanel schuelerPanel = new SchuelerPanel();
    
    
        public MainGui() {
            mainPanel.setLayout(cardLayout);
            mainPanel.add(new JLabel(), EMPTY); // empty label
            mainPanel.add(schuelerPanel, SCHUELER_PANEL);
    
            JMenu menu = new JMenu("Panel");
            menu.add(new JMenuItem(new SwapPanelAction(EMPTY)));
            menu.add(new JMenuItem(new SwapPanelAction(SCHUELER_PANEL)));
            menuBar.add(menu);
        }
    
        public JPanel getMainPanel() {
            return mainPanel;
        }
    
        public JMenuBar getMenuBar() {
            return menuBar;
        }
    
        @SuppressWarnings("serial")
        private class SwapPanelAction extends AbstractAction {
            public SwapPanelAction(String title) {
                super(title);
                int mnemonic = (int) title.charAt(0);
                putValue(MNEMONIC_KEY, mnemonic);
            }
    
            @Override
            public void actionPerformed(ActionEvent e) {
                cardLayout.show(mainPanel, (String) getValue(NAME));
            }
        }
    
        private static void createAndShowGui() {
            MainGui mainGui = new MainGui();
            JFrame frame = new JFrame("Main Gui");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().add(mainGui.getMainPanel());
            frame.setJMenuBar(mainGui.getMenuBar());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(() -> createAndShowGui());
        }
    }
    

    import java.awt.BorderLayout;
    import java.awt.Font;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.util.HashMap;
    import java.util.Map;
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class SchuelerPanel extends JPanel {
        private static final String TITLE_TEXT = "Lorem Ipsum Dolor Sit Amet";
        public static final String[] LABEL_STRINGS = {"Monday", "Tuesday", "Wednesday"};
        private Map<String, JTextField> labelFieldMap = new HashMap<>();
    
        public SchuelerPanel() {
            JLabel titleLabel = new JLabel(TITLE_TEXT, JLabel.CENTER);
            titleLabel.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 20));
    
            JPanel labelFieldPanel = new JPanel(new GridBagLayout());
            for (int i = 0; i < LABEL_STRINGS.length; i++) {
                addToPanel(labelFieldPanel, LABEL_STRINGS[i], i);
            }
    
            // Don't do what I'm doing here: avoid "magic" numbers!
            setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); 
            setLayout(new BorderLayout(10, 10));
            add(titleLabel, BorderLayout.PAGE_START);
            add(labelFieldPanel, BorderLayout.CENTER);
        }
    
        // get the text from the JTextField based on the JLabel associated with it
        public String getText(String labelText) {
            JTextField textField = labelFieldMap.get(labelText);
            if (textField == null) {
                throw new IllegalArgumentException("For labelText: " + labelText);
            }
            return textField.getText();
        }
    
        private void addToPanel(JPanel gblUsingPanel, String labelString, int row) {
            JLabel label = new JLabel(labelString);
            label.setFont(label.getFont().deriveFont(Font.BOLD));
            JTextField textField = new JTextField(10);
            labelFieldMap.put(labelString, textField);
    
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = 0;
            gbc.gridy = row;
            gbc.anchor = GridBagConstraints.WEST;
            gbc.fill = GridBagConstraints.BOTH;
            gbc.weightx = 0.0;
            gbc.weighty = 0.0;
            gbc.insets = new Insets(5, 5, 5, 5);
            gblUsingPanel.add(label, gbc);
    
            gbc.gridx = 1;
            gbc.anchor = GridBagConstraints.EAST;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gblUsingPanel.add(textField, gbc);
        }
    
        private static void createAndShowGui() {
            JFrame frame = new JFrame("SchuelerPanel");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().add(new SchuelerPanel());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(() -> createAndShowGui());
        }
    }
    

    【讨论】:

    • 好吧,我听说空布局也有一些不好的事情。但我只是使用它,因为它是一个简单的例子,但我会在未来提醒这一点。但我仍然不知道为什么我的框架没有显示 Jpanel,我正在搜索我的代码中的错误你知道吗?它不适用于重绘或重新验证:(
    • @KungFuKugelfisch:我已经告诉过你原因——你使用的是空布局。如果您使用适当的布局,问题就会消失。
    • @KungFuKugelfisch:您的 JPanel 的首选大小为 0,0,因为使用了空布局,并且因为您在 contentPane 中使用空布局,它甚至不会尊重首选大小,而是实际大小,两者均未设置。同样,只需使用布局管理器。咬紧牙关学习它们。
    • 啊,好的,谢谢,我知道了。我认为布局无关紧要,空布局将是一般提示。感谢您的快速回答,现在这很有意义
    • @KungFuKugelfisch:请查看示例代码以显示 CardLayout 和布局管理器在工作中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-30
    • 2013-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    相关资源
    最近更新 更多