我正在尝试将一个类的多个实例添加到java中的JFrame,但是当我尝试向JFrame添加两个不同的实例时,只显示最近添加的实例。
我看过这里显示的答案: How to add multiple components to a JFrame?和此处:Adding multiple classes to a Jframe
我的代码是以https://www.youtube.com/watch?v=I3usNR8JrEE&index=51&list=PL53A7C2BE1F8D780C为模型的 我正在使用Eclipse Java Oxygen 4.7.1a版 但没有什么对我有用。这是我的主要功能:
package BlockPack;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Block extends JPanel implements ActionListener {
@Override public Dimension getPreferredSize() {
return new Dimension(900, 900);
}
Timer tm = new Timer(50, this);
int blockWidth, blockHeight;
int x, y, velX = 2, velY = 0, gravity = 0;
String thisName;
boolean collidingGround = false;
public Block(String _name, int _x, int _y, int _width, int _height) {
thisName = _name;
x = _x;
y = _y;
blockWidth = _width;
blockHeight = _height;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.fillRect(x, y, blockWidth, blockHeight);
tm.start();
}
public void actionPerformed(ActionEvent e) {
performMovement();
repaint();
}
private void performMovement() {
y += 1;
}
public static void main(String[] args) {
Block b = new Block("block1", 10, 30, 50, 50);
Block bb = new Block("block2", 30, 60, 10, 60);
JFrame jf = new JFrame();
jf.setLayout(new FlowLayout());
jf.setTitle("Ball");
jf.setSize(600, 400);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = jf.getContentPane();
c.add(new Block("block1", 10, 30, 50, 50));
c.add(new Block("block2", 30, 60, 10, 60));
jf.setVisible(true);
}
}
答案 0 :(得分:0)
jf.setLayout(new FlowLayout());
已被注释掉,因此您将这两个组件添加到默认BorderLayout的中心位置,因此当然只会显示最后一个组件。getPreferredSize()
,因此会返回默认值(10 x 10),并且组件会超出此首选大小。