我试图在点击时将JPanel添加到我的JFrame,但我没有找到我的错误

时间:2016-08-22 19:54:37

标签: java swing jframe jpanel add

我正在努力获得一些Java技能,因为我在webdevelopment工作了很长时间。现在我只是创建一个主Jframe,其中有一个小菜单,一个类createSchueler扩展了JPanel。

所以如果你进入菜单我想做什么点击Neu>许勒尔

应创建一个新的Jpanel并将其添加到Window

主类

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

1 个答案:

答案 0 :(得分:4)

使用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());
    }
}