[英]JFrame/Panel not showing up
我应该显示一排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);
}
构造函数不是实际的构造函数,它被视为方法,从而导致使用类的默认构造函数。 构造函数没有指定返回类型,甚至没有void
。
固定构造函数
public Studying(){
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(1,2));
p1.add(button);
p1.add(button1);
add(p1);
}
函数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);
}
}
这应该工作:
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.