2013-04-25 62 views
0

所以即時自學Java並遇到了一些麻煩。對於其中一項練習,下面是我無法理解的說明。任何幫助解釋將不勝感激。這是我對我遇到麻煩的部分的嘗試。用於GUI應用程序的JPanel

import java.awt.Dimension; 
import java.awt.GridLayout; 
import javax.swing.JButton; 
import javax.swing.JPanel; 
import javax.swing.JScrollPane; 
import javax.swing.JTextArea; 

public class ButtonPanel extends JPanel { 


    public ButtonPanel(JButton[] buttons, JTextArea textArea) { 
     //TODO: Create a sub-panel with a 4 row, 3 column GridLayout 

     setLayout(new GridLayout(4,3)); //Layout of subPanel1 

     JButton b1 = new JButton ("A"); 
     JButton b2 = new JButton ("B"); 
     JButton b3 = new JButton ("C"); 
     JButton b4 = new JButton ("1"); 
     JButton b5 = new JButton ("2"); 
     JButton b6 = new JButton ("3"); 
     JButton b7 = new JButton ("X"); 
     JButton b8 = new JButton ("Y"); 
     JButton b9 = new JButton ("Z"); 

     add(b1); 
     add(b2); 
     add(b3); 
     add(b4); 
     add(b4); 
     add(b5); 

     //TODO: Populate the grid with buttons 

     //TODO: Add the grid panel to this panel 

     //TODO: Create a JScrollPane containing textArea 

     JButton cr = new JButton(); 

     //TODO: Set the preferred size of the scroll pane to 80x120 
     setPreferredSize (new Dimension(80, 120)); 

     //TODO: Add the scroll pane to this panel 

    } 


} 
+0

的研究5分鐘將清除所有的疑慮 – 2013-04-25 23:01:12

+0

有什麼問題的時候? – 2013-04-25 23:02:45

+0

創建JPanel的新實例,將按鈕添加到此面板,將此面板添加到父窗格 – MadProgrammer 2013-04-25 23:15:21

回答

1

這是一個基本的概念。

若要將組件添加到容器中,你需要

  1. 創建容器
  2. 應用佈局管理器到容器
  3. 添加組件到容器
  4. 容器添加到附着(以某種方式)到頂級容器的父容器

例如

public void ButtonPanel(JButton[] buttons, JTextArea textArea) { 
    //TODO: Create a sub-panel with a 4 row, 3 column GridLayout 

    JPanel buttonPanel = new JPanel(new GridLayout(4,3)); //Layout of subPanel1 

    JButton b1 = new JButton ("A"); 
    JButton b2 = new JButton ("B"); 
    JButton b3 = new JButton ("C"); 
    JButton b4 = new JButton ("1"); 
    JButton b5 = new JButton ("2"); 
    JButton b6 = new JButton ("3"); 
    JButton b7 = new JButton ("X"); 
    JButton b8 = new JButton ("Y"); 
    JButton b9 = new JButton ("Z"); 

    buttonPanel.add(b1); 
    buttonPanel.add(b2); 
    buttonPanel.add(b3); 
    buttonPanel.add(b4); 
    buttonPanel.add(b4); 
    buttonPanel.add(b5); 

    //TODO: Populate the grid with buttons 

    //TODO: Add the grid panel to this panel 

    //TODO: Create a JScrollPane containing textArea 

    JButton cr = new JButton(); 

    //TODO: Set the preferred size of the scroll pane to 80x120 
    // This is a bad idea 
    setPreferredSize (new Dimension(80, 120)); 

    //TODO: Add the scroll pane to this panel 

} 

花點時間通讀和理解Creating a UI with Swing