2013-12-20 121 views
1

我應該顯示一排2個按鈕,但似乎並非如此。JFrame /面板不顯示

import java.util.*; 
import javax.swing.*; 
import java.awt.event.*; 
import java.awt.*; 

public class Studying extends JFrame{ 

JButton button = new JButton("Word"); 
JButton button1 = new JButton("MoreWords"); 

public void Studying(){ 

JPanel p1 = new JPanel(); 
p1.setLayout(new GridLayout(1,2)); 
p1.add(button); 
p1.add(button1); 
add(p1); 

} 

public static void main(String[] args){ 
Studying frame = new Studying(); 
frame.setTitle("test"); 
frame.setSize(500,200); 
frame.setVisible(true); 
frame.setLocationRelativeTo(null); 
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

} 

回答

5

構造函數不是實際的構造函數,它被視爲一種方法,導致使用類的默認構造函數。構造函數不指定返回類型,即使void

固定構造

public Studying(){ 

    JPanel p1 = new JPanel(); 
    p1.setLayout(new GridLayout(1,2)); 
    p1.add(button); 
    p1.add(button1); 
    add(p1); 

} 
+0

哇...爲什麼我弄的,我做了GUI的很多,但是,它是無形的給我。 – Corjava

+0

@Corjava適合每個人。如果你需要它休息一下。當我累了時,我總是把'='和'=='混在一起。 –

+0

是的,總決賽周...只是爲它練習GUI。 – Corjava

0

函數學習()不是一個類,因此Studying frame = new Studying();public class Studying extends JFramepublic void Studying()和永遠不會調用。將按鈕的創建移動到靜態主體,並將它們附加到框架,並且按鈕將可見。

public class Studying extends JFrame { 

static JButton button = new JButton("Word"); 
static JButton button1 = new JButton("MoreWords"); 

public static void main(String[] args) { 
    Studying frame = new Studying(); 
    frame.setTitle("test"); 
    frame.setSize(500, 200); 
    frame.setLocationRelativeTo(null); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setLayout(new GridLayout(1, 2)); 
    frame.add(button); 
    frame.add(button1); 
    frame.setVisible(true); 

} 
} 
0

這應該工作:

import java.util.*; 
import javax.swing.*; 
import java.awt.event.*; 
import java.awt.*; 

public class Studying extends JFrame{ 

JButton button = new JButton("Word"); 
JButton button1 = new JButton("MoreWords"); 

public Studying(){ 

JPanel p1 = new JPanel(); 
p1.setLayout(new GridLayout(1,2)); 
p1.add(button); 
p1.add(button1); 
add(p1); 

} 

public static void main(String[] args){ 
Studying frame = new Studying(); 
frame.setTitle("test"); 
frame.setSize(500,200); 
frame.setLocationRelativeTo(null); 
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
frame.pack(); 
frame.setVisible(true); 

}