0

こんにちは、「button1」が表示されない理由を知っている人はいますか? プログラムを実行すると、すべてが機能し、正常に実行されますが、このボタンは表示されません。どんな助けでも感謝します。

private Container c;
private JPanel gridPanel;
private JComboBox combo;
final JLabel label = new JLabel();
private JButton button1 = new JButton("Clear");
private JButton button2 = new JButton("Exit");

/**
 * Christopher Haddad - 559815X
 */
public Planets() {
    c = getContentPane();
    gridPanel = new JPanel();
    gridPanel.setLayout(new GridLayout(5, 0, 0, 0));

    label.setVisible(true);

    combo = new JComboBox(); 
    combo.setEditable(false);
    combo.addItem("No Planet Selected");
    combo.addItem("Mercury"); 
    combo.addItem("Venus"); 
    combo.addItem("Earth"); 
    gridPanel.add(combo);

    add(button1);
    add(button2);
    button1.addActionListener(this);
    button2.addActionListener(this);

    c.add(gridPanel, BorderLayout.NORTH);
    setTitle("Planet Diameter"); 
    setSize(700, 250);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);

    combo.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {

            JComboBox comboBox = (JComboBox) event.getSource();

            Object select = comboBox.getSelectedItem();

            if(select.toString().equals("No Planet Selected"))
                label.setText("");
            else if(select.toString().equals("Mercury"))
                label.setText("The planet Mercury is 3100kms in diameter");
            else if(select.toString().equals("Venus"))
                label.setText("The planet Venus is 7500kms in diameter");
            else if (select.toString().equals("Earth"))
                label.setText("The planet Earth is 8000kms in diameter");

        }
    });
    getContentPane().add(combo);
    getContentPane().add(label);
}

    // event handling method, implementing the actionPerformed method of ActionListener 
    public void actionPerformed(ActionEvent e) 
    { 
        // set the button label to number of times it has been clicked
        if(e.getSource() == button1) {
            label.setText(" ");
        }
        else if(e.getSource() == button2) {
            System.exit(0);
        }
    } 
4

1 に答える 1

3

確かなことはわかりませんが、コンテンツをトップレベルのコンテナに直接追加していると思います。JFrame

JFrameBorderLayoutデフォルトのレイアウトマネージャーとして を使用するため、

add(button1);
add(button2);

基本的に言うとadd button1、位置に、CENTER次に位置に。 単一のコンポーネントのみが特定の場所に存在することを許可します。add button2CENTERBorderLayout

最初に別のパネルにボタンを追加してみてください...

于 2013-07-11T01:46:22.517 に答える