Re: [問題] 一個 GridBagLayout 的問題

看板java作者 (sbr)時間16年前 (2009/07/04 20:38), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串5/6 (看更多)
※ 引述《Liszt04 (走路往下看都會怕)》之銘言: : private JPanel panel; : private JTextField textarea; : public GridBag() : { : super("gridbaglayout"); : layout = new GridBagLayout(); : setLayout(layout); : constraints = new GridBagConstraints(); : button1 = new JButton("Button1"); : button2 = new JButton("Button2"); : combobox1 = new JComboBox(list); : combobox2 = new JComboBox(list); : checkbox = new JCheckBox("filled"); : textarea = new JTextField("textfield", 50); : constraints.fill = GridBagConstraints.HORIZONTAL; : addComponent(button1, 0, 0, 1, 1); : addComponent(button2, 1, 0, 1, 1); : addComponent(combobox1, 2, 0, 1, 1); : addComponent(combobox2, 3, 0, 1, 1); : addComponent(checkbox, 4, 0, 1, 1); : constraints.fill = GridBagConstraints.BOTH; : addComponent(panel, 0, 1, 5, 1); : constraints.fill = GridBagConstraints.HORIZONTAL; : addComponent(textarea, 0, 2, 5, 1); : } : public void addComponent(Component component, int column, int row, int : width, int height) : { : constraints.gridx = column; : constraints.gridy = row; : constraints.gridwidth = width; : constraints.gridheight = height; : layout.setConstraints(component, constraints); : add(component); : } : } : 他跑出來的結果是: : exceptionx in thread "main" lava.lang.Nullpointerexception : at java.util.Hastable.put(Hashtable.java:399) : at java.awt.GridBagLayout.setConstraints(GridBagLayout.java:482) : at GridBag.addComponent(GridBag.java:61) : at GridBag.(init)(GridBag.java:48) : at GridBagTest.main(GridBagTest.java:8) : } : 要是紅色部分沒有打的話 輸出是正確的 : 加上去panel之後整個跑不出來 : add(panel) 換成add(button) 的話 排版竟然也是錯的 囧 : 請問一下是我哪邊寫錯了 還是我哪邊觀念不太正確 exception 是在綠色那一個 statement 產生的,原因很明顯 就是 panel 這個 field 的值是 null。 button1, button2 這些 field 你都會 assign JButon instance reference,那 panel 呢?! -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 218.173.139.26 ※ 編輯: sbrhsieh 來自: 218.173.139.26 (07/04 20:40)

07/04 20:44, , 1F
了解! 但是我打了panel = new JPanel()之後排版還是怪怪的
07/04 20:44, 1F
文章代碼(AID): #1AJqqi1r (java)
討論串 (同標題文章)
文章代碼(AID): #1AJqqi1r (java)