JFrame / Panel未显示

时间:2013-12-20 01:23:45

标签: java swing jframe jpanel

我应该显示一行2个按钮,但似乎并非如此。

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);

}

3 个答案:

答案 0 :(得分:5)

构造函数不是实际的构造函数,它被视为一个方法,导致使用类的默认构造函数。构造函数不指定返回类型,甚至void

已修复构造函数

public Studying(){

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

}

答案 1 :(得分:0)

函数Studying()不是一个类,因此Studying frame = new Studying();引用public class Studying extends JFrame并且永远不会调用public 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);

}
}

答案 2 :(得分: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);

}