2013-05-11 48 views
0

我希望能夠動態添加新的60x80圖像,這些圖像將充當按鈕來打開新幀。但是,出於某種奇怪的原因,我的createFrame()方法無法將任何類型的組件添加到jpanel中。我一直試圖解決這個問題幾個小時,現在我不確定有什麼問題。我嘗試添加純色面板,標籤,按鈕......但沒有任何工作。我的主要JPanel將使用FlowLayout來處理所有圖像,而我的主JFrame使用BorderLayout,這樣我可以在後面的主要部分中定位另一個特定內容JPanel。難以從菜單中的圖像/面板/按鈕到JPanel

這裏是我的代碼(包括重新驗證()作爲我的編輯,其中固定它):

package testit; 

import java.awt.BorderLayout; 
import java.awt.Color; 
import java.awt.Dimension; 
import java.awt.FlowLayout; 
import java.awt.Toolkit; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.awt.event.KeyEvent; 
import javax.swing.ImageIcon; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JMenu; 
import javax.swing.JMenuBar; 
import javax.swing.JMenuItem; 
import javax.swing.JPanel; 
import javax.swing.KeyStroke; 
import javax.swing.border.LineBorder; 

class TestIt extends JFrame implements ActionListener { 
    //Main window frame and content panel 
    private JFrame main_frame; 
    private JPanel main_panel; 

    //Screen size variable 
    private Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); 

    public TestIt() {    
     //Set up the main frame 
     main_frame = new JFrame("Test Program"); 
     main_frame.setLayout(new BorderLayout()); 
     main_frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     main_frame.setIconImage(
      new ImageIcon("src/testit/resources/img/app_icon.gif").getImage()); 

     //Set up the inner content panel 
     main_panel = new JPanel(); 
     main_panel.setLayout(new FlowLayout()); 
     main_panel.setPreferredSize(
      new Dimension((screen.width/10) * 6,(screen.height/10) * 6)); 

     //Add the menu bar and the main panel to the main frame 
     main_frame.add(main_panel, BorderLayout.CENTER);  
     main_frame.setJMenuBar(createMenuBar()); 

     //Display the main GUI 
     main_frame.pack(); 
     main_frame.setLocationRelativeTo(null); 
     main_frame.setVisible(true); 

    } 

    //Create an instance of the program 
    private static void runIt() { 
     TestIt program = new TestIt(); 
    } 

    private JMenuBar createMenuBar() { 
     //Create the top menu bar 
     JMenuBar top_menu_bar = new JMenuBar(); 

     //Create the menu 
     JMenu main_menu = new JMenu ("Menu"); 
     main_menu.setMnemonic(KeyEvent.VK_M); 
     top_menu_bar.add(main_menu); 

     //Create the menu items and add them to the menu 
     JMenuItem menu_item; 

     menu_item = new JMenuItem("Add New"); 
     menu_item.setMnemonic(KeyEvent.VK_N); 
     menu_item.setAccelerator(
       KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.ALT_MASK)); 
     menu_item.setActionCommand("new"); 
     menu_item.addActionListener(this); 
     main_menu.add(menu_item); 

     menu_item = new JMenuItem("Save"); 
     menu_item.setMnemonic(KeyEvent.VK_S); 
     menu_item.setAccelerator(
       KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.ALT_MASK)); 
     menu_item.setActionCommand("save"); 
     menu_item.addActionListener(this); 
     main_menu.add(menu_item); 

     menu_item = new JMenuItem("Exit"); 
     menu_item.setMnemonic(KeyEvent.VK_X); 
     menu_item.setAccelerator(
       KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.ALT_MASK)); 
     menu_item.setActionCommand("exit"); 
     menu_item.addActionListener(this); 
     main_menu.add(menu_item); 

     //Return the assembled menu bar 
     return top_menu_bar; 
    } 

    public void actionPerformed(ActionEvent e) { 
     if("new".equals(e.getActionCommand())) { 
      createFrame(); 
     } else if("save".equals(e.getActionCommand())) { 
      //save(); 
     } else { 
      quit(); 
     } 
    } 

    private void createFrame() { 
     /* 
     ImageIcon image = new ImageIcon("src/testit/resources/img/test.gif"); 
     JLabel label = new JLabel("", image, JLabel.CENTER);   
     main_panel.add(label); 
     */ 

     JButton frame = new JButton("test"); 
     frame.setBorder(new LineBorder(Color.BLACK)); 
     frame.setPreferredSize(new Dimension(60, 80)); 
     frame.setVisible(true); 
     main_panel.add(frame); 
     main_frame.revalidate(); 

    } 

    private void quit() { 
     System.exit(0); 
    } 

    public static void main(String [] args) { 
     javax.swing.SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       runIt(); 
      } 
     }); 
    } 
} 

任何想法在我的代碼中的錯誤是什麼?

編輯:我能解決它通過使用main_frame.revalidate()...是最合適的方式?看起來使用validate()完成了同樣的事情,但不幸的是,即使在閱讀javadoc之後,我也不明白它們之間的區別。

+0

'重新驗證()'是一個異步方法。它允許告訴Swing:當你完成處理隊列中的事件(點擊,鼠標等)時,調用'validate()'。 'validate()'是同步的。它立即執行驗證操作。 – 2013-05-12 14:50:45

+0

@JB Nizet啊,很酷。謝謝,這是一個比javadoc更好的解釋。我很感激。 – 2013-05-12 17:31:29

回答

1

也許你可以澄清,但你已經說明class TestIt extends JFrame因此你沒有必要在你的構造函數中使用main_frame = new JFrame("Test Program");

它可以通過一些被替換:

public testIt() { 

    super("Test Program"); 
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    this.setSize(500, 500); 

    // whatever code goes here such as... 
    // this.add(somePanel); 
    // this.add(new JButton("Click Me!")); 
    // etc.. 

    this.setVisible(true); 
    this.pack(); 

} 

除非對框架的明確原因。另外,你沒有錯,你只是做不同的事情,但我提出的原因是因爲爲什麼子類JFrame,如果你不利用它?

+0

嗯,真的,它的工作原理。我對Java仍然很陌生,所以我不能100%確定擴展是如何工作的。謝謝。 ;) – 2013-05-12 17:30:03

0

創建動態的JButton用圖像和ActionListener的 - 的Java Swing

與圖像和動態ActionListener的JButton的創建。您將會在能夠在一個地方更改按鈕高度,寬度水平間隙和垂直間距的

enter image description here

我已創建虛擬數據庫類將返回主菜單項和子菜單items.You會看到你的JFrame主菜單項。如果您選擇的按鈕面板主要產品(食品),將負載從虛擬數據庫類子項目(食品子項)

you can find more details with images and source Code from here

private void addMainMenue() { 

    pnl_button.removeAll(); 
    repaint(); 

    Image img, sub; 
    ImageIcon icon; 
    String imagePath, imag = "/com/images/"; 

    ArrayList menue = new ArrayList(); 
    ArrayList itemName = new ArrayList(); 

    for (int size = 0; size < ItemDB.mainMenuCodes.length; size++) { 
     menue.add(ItemDB.mainMenuCodes[size]); 
     itemName.add(ItemDB.mainMenuDesc[size]); 
    } 

    JButton[] buttons = new JButton[menue.size()]; 

    for (int i = 0; i < buttons.length; i++) { 

     imagePath = imag + menue.get(i).toString() + ".jpeg"; 

     URL url = getClass().getResource(imagePath); 
     // System.out.println(imagePath +" Get Res : " 
     // +getClass().getResource(imagePath)); 

     if (url != null) { 
      img = Toolkit.getDefaultToolkit().getImage(url); 
      sub = img.getScaledInstance(button_width - 8, 
        button_height - 30, Image.SCALE_FAST); 
      icon = new ImageIcon(sub); 
     } else 
      icon = new ImageIcon(); 

     buttons[i] = new JButton(itemName.get(i).toString(), icon); 
     buttons[i].setVerticalTextPosition(AbstractButton.BOTTOM); 
     buttons[i].setHorizontalTextPosition(AbstractButton.CENTER); 

     buttons[i] 
       .setBorder(javax.swing.BorderFactory.createEtchedBorder()); 
     buttons[i].setFont(new java.awt.Font("Tahoma", 1, 13)); 
     buttons[i].setForeground(new java.awt.Color(0, 51, 255)); 

     buttons[i].setActionCommand(menue.get(i).toString()); 
     buttons[i].addActionListener(new ActionListener() { 

      public void actionPerformed(ActionEvent e) { 
       String choice = e.getActionCommand(); 
       addSubmenue(choice); 
      } 
     }); 
    } 

    int b = 0; 
    int vGap = verticalGap; 
    int hGap = horizontalGap; 
    int bLength = buttons.length; 
    int bRows = bLength/numberOfColumns + 1; 

    L1: for (int j = 0; j < bRows; j++) { 
     vGap = 10; 
     for (int k = 0; k < numberOfColumns; k++) { 

      pnl_button.add(buttons[b], 
        new org.netbeans.lib.awtextra.AbsoluteConstraints(vGap, 
          hGap, button_width, button_height)); 
      repaint(); 
      vGap += button_width + verticalGap; 
      b++; 
      if (b >= bLength) { 
       break L1; 
      } 
     } 
     hGap += button_height + horizontalGap; 
    } 
    pack(); 
} 

private void addSubmenue(String choice) { 
    pnl_button.removeAll(); 
    repaint(); 

    Image img, sub; 
    ImageIcon icon; 
    String imagePath, imag = "/com/images/"; 

    ArrayList menue = new ArrayList(); 
    ArrayList itemName = new ArrayList(); 

    ArrayList list = ItemDB.getSubMenu(choice); 
    String subCode[] = (String[]) list.get(0); 
    String subDesc[] = (String[]) list.get(1); 

    for (int size = 0; size < subCode.length; size++) { 
     menue.add(subCode[size]); 
     itemName.add(subDesc[size]); 
    } 

    JButton[] buttons = new JButton[menue.size()]; 

    for (int i = 0; i < buttons.length; i++) { 

     imagePath = imag + menue.get(i).toString() + ".jpeg"; 

     URL url = getClass().getResource(imagePath); 
     // System.out.println(imagePath +" Get Reso : " 
     // +getClass().getResource(imagePath)); 

     if (url != null) { 
      img = Toolkit.getDefaultToolkit().getImage(url); 
      sub = img.getScaledInstance(button_width - 8, 
        button_height - 30, Image.SCALE_FAST); 
      icon = new ImageIcon(sub); 
     } else 
      icon = new ImageIcon(); 

     buttons[i] = new JButton(itemName.get(i).toString(), icon); 
     buttons[i].setVerticalTextPosition(AbstractButton.BOTTOM); 
     buttons[i].setHorizontalTextPosition(AbstractButton.CENTER); 

     buttons[i] 
       .setBorder(javax.swing.BorderFactory.createEtchedBorder()); 
     buttons[i].setFont(new java.awt.Font("Tahoma", 1, 13)); 
     buttons[i].setForeground(new java.awt.Color(0, 51, 255)); 

     buttons[i].setActionCommand(menue.get(i).toString()); 
     buttons[i].addActionListener(new ActionListener() { 

      public void actionPerformed(ActionEvent e) { 
       String choice = e.getActionCommand(); 
       addItems(choice); 
      } 
     }); 
    } 
    int b = 0; 
    int vGap = verticalGap; 
    int hGap = horizontalGap; 
    int bLength = buttons.length; 
    int bRows = bLength/numberOfColumns + 1; 

    L1: for (int j = 0; j < bRows; j++) { 
     vGap = 10; 
     for (int k = 0; k < numberOfColumns; k++) { 

      pnl_button.add(buttons[b], 
        new org.netbeans.lib.awtextra.AbsoluteConstraints(vGap, 
          hGap, button_width, button_height)); 
      repaint(); 
      vGap += button_width + verticalGap; 
      b++; 
      if (b >= bLength) { 
       break L1; 
      } 
     } 
     hGap += button_height + horizontalGap; 
    } 
    pack(); 
} 

private void addItems(String choice) { 

    if (choice.equals("P")) 
     choice = "PIZZA"; 
    else if (choice.equals("B")) 
     choice = "BURGER"; 
    else if (choice.equals("FJ")) 
     choice = "FRUIT JUICE"; 
    else if (choice.equals("HB")) 
     choice = "HOT BEVERAGES"; 
    JOptionPane.showMessageDialog(this, "You have select " + choice); 
} 
+0

這將幫助你實現POS應用程序 – 2013-06-26 21:04:04