我是Java的先驱。我想创建一个扩展JFrame使用的Form类。一切正常,它的大小和中心在屏幕上很好。我只是不能添加组件。我错过了什么用Google搜索每一堂课,找不到任何东西。
Main.java:
package pongLib;
import pongUI.*;
public class Main {
public static void main(String[] args) {
Form frm = new Form(600,500,"Pong");
}
}
Form.java:
package pongUI;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Form extends JFrame {
private int width;
private int height;
private int posx;
private int posy;
private String title;
public Form(int width, int height, String title) {
//call parent constructor
super();
//set size
this.width=width;
this.height=height;
//set title
this.title=title;
//get position(x,y)
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
Double x = (screen.getWidth()-this.width)/2;
Double y = (screen.getHeight()-this.height)/2;
posx = x.intValue();
posy = y.intValue();
//add components
JLabel points1Label = new JLabel("The Rookie (aka You)");
this.addComponent(points1Label, 10, 50);
//set form properties
this.setLayout(null);
this.setSize(width, height);
this.setLocation(posx, posy);
this.setResizable(false);
this.setTitle(title);
this.setVisible(true);
public void addComponent(Component c, int posx, int posy) {
c.setLocation(posx, posy);
this.getContentPane().add(c,BorderLayout.CENTER);
}
}
答案 0 :(得分:2)
答案 1 :(得分:2)
我认为问题是你的
setLayout(null);
没有布局管理器来安排组件。
答案 2 :(得分:1)
您必须设置布局。
this.setLayout(new BorderLayout());
答案 3 :(得分:1)
您应该将布局设置为new BorderLayout()
而不是null
。否则,您的组件将无法获得大小> 0因此不会显示。
答案 4 :(得分:1)
您的组件没有尺寸。给它们一个宽度和高度,或者更好地使用布局管理器而不是空布局。
答案 5 :(得分:1)
就是这样:
package test;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Form extends JFrame {
private final int width;
private final int height;
private final int posx;
private final int posy;
private final String title;
public Form(int width, int height, String title) {
// call parent constructor
super();
// set size
this.width = width;
this.height = height;
// set title
this.title = title;
// get position(x,y)
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
Double x = (screen.getWidth() - this.width) / 2;
Double y = (screen.getHeight() - this.height) / 2;
posx = x.intValue();
posy = y.intValue();
// add components
JLabel points1Label = new JLabel("The Rookie (aka You)");
points1Label.setBounds(10, 50, points1Label.getPreferredSize().width,
points1Label.getPreferredSize().height);
this.getContentPane().add(points1Label);
// set form properties
this.setLayout(null);
this.setSize(width, height);
this.setLocation(posx, posy);
this.setResizable(false);
this.setTitle(title);
this.setVisible(true);
}
public void addComponent(Component c, int posx, int posy) {
c.setLocation(posx, posy);
this.getContentPane().add(c, BorderLayout.CENTER);
}
}