gpt4 book ai didi

java - 如何使用frame.add方法创建多个可见对象

转载 作者:行者123 更新时间:2023-12-02 04:30:02 61 4
gpt4 key购买 nike

当我尝试添加电梯类的第二个实例时,第一个实例消失了。如何重新排列此代码才能看到这两个对象?

这是我的主要类(class):

public class MainClass extends JPanel implements ActionListener {
public static void main(String[] args) {
JFrame frame = new JFrame("title");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1000, 700);
frame.setLocationRelativeTo(null);
frame.setVisible(true);

Component component1 = frame.add(new elevator(0,0));
Component component2 = frame.add(new elevator(505,50));
}

@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}

这是电梯类:

public class elevator extends JPanel implements ActionListener {
Timer timer;
private double angle = 0;
private double scale = 1;
private double delta = 0.01;
private int x=0;
private int y=0;

Rectangle.Float r = new Rectangle.Float(0, 0, 3, 3);

public elevator(int input_x, int input_y) {
x=input_x;
y=input_y;
timer = new Timer(10, this);
timer.start();
}

public elevator() {
timer = new Timer(10, this);
timer.start();
}

public void paint(Graphics g) {
this.setSize(100,200);
this.setLocation(x, y);
int h = getHeight();
int w = getWidth();

super.paintComponent(g);

Graphics2D g2d = (Graphics2D) g;

g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

g2d.translate(w / 5, scale*140);
g2d.scale(20, 20);

g2d.fill(r);
}

public void actionPerformed(ActionEvent e) {
if (scale < 0.01 || scale > 0.99) {
delta = -delta;
}
scale += delta;
angle += 0.01;
repaint();
}
}

最佳答案

您将需要某种容器来放入这两个组件。您可以使用 JPanel,在这种情况下,您的代码将如下所示:

JPanel panel = new JPanel();
panel.add(new elevator(0,0));
panel.add(new elevator(505,50));
frame.add(panel);

为了让它们占据相同的区域(并且让 JPanel 填满它能容纳的所有空间),您可以将 GridLayout 传递给JPanel 构造函数:

JPanel panel = new JPanel(new GridLayout(2, 1)); // 2 rows, 1 column

JPanel panel = new JPanel(new GridLayout(1, 2)); // 1 row, 2 columns

关于java - 如何使用frame.add方法创建多个可见对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23830587/

61 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com