2016-01-31 185 views
-1

我正在嘗試創建一個可以添加名稱和地址的程序。 我正在嘗試使用GridLayout,但沒有顯示按鈕。 我在這裏做錯了什麼? 謝謝Java沒有按鈕顯示

你好。我試圖製作一個可以添加姓名和地址的程序。 我正在嘗試使用GridLayout,但沒有顯示按鈕。 我在這裏做錯了什麼? 感謝

import java.awt.Color; 
import java.awt.GridLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 


public class AddressBookProgram extends JFrame { 

    public AddressBookProgram() { 
     super("Test"); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     setContentPane(new GridPanel()); 
     setSize(300, 300); 
     setVisible(true); 
    } 

    private final class GridPanel extends JPanel { 
     private JPanel bookPanel; 
     private JPanel buttonPanel; 
     private JButton add; 
     private JButton delete; 
     private JButton search; 
     private JButton displayAll; 
     private JButton exit; 
     private ActionListener buttons = new ButtonListener(); 


     private GridPanel() { 
      setLayout(new GridLayout(2, 3)); 
      setBackground(Color.green); 

      bookPanel = new JPanel(); 
      bookPanel.setBackground(Color.white); 
      buttonPanel = new JPanel(); 
      buttonPanel.setBackground(Color.white); 

      add = new JButton("Add"); 
      delete = new JButton("Delete"); 
      search = new JButton("Search"); 
      displayAll = new JButton("Display All"); 
      exit = new JButton("Exit"); 

      add.addActionListener(buttons); 
      delete.addActionListener(buttons); 
      search.addActionListener(buttons); 
      displayAll.addActionListener(buttons); 
      exit.addActionListener(buttons); 

      buttonPanel.add(add); 
      buttonPanel.add(delete); 
      buttonPanel.add(search); 
      buttonPanel.add(displayAll); 
      buttonPanel.add(exit); 
     } 


     private class ButtonListener implements ActionListener { 

      /** 
      * <p>Updates the watchLabel label when button is pushed.</p> 
      * @param event a button is pushed 
      */ 
      public void actionPerformed(ActionEvent event) { 
       if (event.getSource() == add) { 
       } 

       if (event.getSource() == delete) { 
       } 

       if (event.getSource() == search) { 
       } 

       if (event.getSource() == displayAll) { 
       } 

       if (event.getSource() == exit) { 
       } 
      }   
     } 


    } 
    public static void main(String[] args) { 
     new AddressBookProgram(); 
    } 
} 

回答

1

這是因爲你創建buttonPanel但你不添加它。就在寫這行:

add(buttonPanel); 

這將使您的代碼:

buttonPanel.add(add); 
buttonPanel.add(delete); 
buttonPanel.add(search); 
buttonPanel.add(displayAll); 
buttonPanel.add(exit); 

add(buttonPanel); 
+0

啊!所以這就是爲什麼!謝謝! – whistle