简体   繁体   English

JFrame /面板未显示

[英]JFrame/Panel not showing up

I should be displaying a row of 2 buttons but that doesn't seem to be the case. 我应该显示一排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);

}

The constructor is not an actual constructor, it is being treated as a method, causing the classes default constructor to be used. 构造函数不是实际的构造函数,它被视为方法,从而导致使用类的默认构造函数。 Constructors do not specify a return type, even void . 构造函数没有指定返回类型,甚至没有void

Fixed Constructor 固定构造函数

public Studying(){

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

}

The function Studying() isn't a class, so Studying frame = new Studying(); 函数Studying()不是类,因此Studying frame = new Studying(); refers to public class Studying extends JFrame and public void Studying() is never called. 指的是public class Studying extends JFrame并且从不调用public void Studying() Move the creation of the buttons to the static main, and append them to the frame, and the buttons will be visible. 将按钮的创建移动到静态主体上,然后将其附加到框架,按钮将可见。

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

}
}

This should work: 这应该工作:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM