【发布时间】:2016-04-14 23:53:10
【问题描述】:
对于我正在做的一个项目,我必须创建 2 个类,其中一个创建一个 JFrame,另一个包含必须添加到 JFrame 的图像。
我的 JFrame 创建类名为 Driver,如下所示:
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Driver {
private JFrame win;
private Animals animals = new Animals();
private BirdButton nextBtn, enlargeBtn, shrinkBtn, moveToBtn;
private JTextField field;
public Driver() {
win = new JFrame("Angry Animal Name Game");
win.setBounds(100, 100, 600, 600);
win.setLayout(null);
win.setVisible(true);
nextBtn = new BirdButton( "NEXT", 10, 10, animals);
win.add(nextBtn, 0);
enlargeBtn = new BirdButton( "ENLARGE", 10, 60, animals);
win.add(enlargeBtn, 0);
shrinkBtn = new BirdButton( "SHRINK", 10, 110, animals);
win.add(shrinkBtn, 0);
field = new JTextField();
field.setBounds(10, 250, 100, 20);
win.add(field, 0);
moveToBtn = new BirdButton( "MOVETO", 10, 275, animals, field);
win.add(moveToBtn, 0);
win.add(animals, 0);
animals.recenter();
win.repaint();
}
}
然后我有一个单独的类 Animals,其中包含一些鸟类的图像。我想让这张图片出现在我的 JFrame 上,但我的代码似乎没有那么热。动物长这样:
public class Animals extends Image {
public Circle selector;
public Image birds;
public Animals(){
birds = new Image(225,200,150,200);
birds.setImage("AngryBirds.png");
selector = new Circle(70,70,birds.getX(),birds.getY());
selector.setThickness(5);
birds.add(selector,0);
}
public void recenter(){
birds.setLocation((600-birds.getWidth()/2),(600-birds.getHeight()/2));
}
}
既然 Animals extends Image 我可以使用这个命令来使 Animals 成为图像本身,或者我需要做什么?我不应该以任何方式修改驱动程序。
谢谢
经过一些回复后,我将我的 Animals 代码编辑为:
public class Animals extends Image {
public Circle selector;
public Animals(){
new Image(225,200,150,200);
setImage("AngryBirds.png");
selector = new Circle(70,70,this.getX(),this.getY());
selector.setThickness(5);
this.add(selector,0);
}
public void recenter(){
this.setLocation((600-this.getWidth()/2),(600-this.getHeight()/2));
}
}
【问题讨论】:
-
您的新 Animals 类仍然扩展 Image。你没有提到这个 Image 类的任何内容——它是你的类吗?是
java.awt.Image吗? -
win.setLayout(null);1) Java GUI 必须在不同的语言环境中使用不同的 PLAF 在不同的操作系统、屏幕尺寸、屏幕分辨率等上工作。因此,它们不利于像素完美布局。而是使用布局管理器,或combinations of them 以及white space 的布局填充和边框。 2) 为了尽快获得更好的帮助,请发帖minimal reproducible example 或Short, Self Contained, Correct Example。 -
很抱歉,图片是教授给我们上的一门课。我似乎自己解决了这些问题,但@HovercraftFullOfEels 你的想法给了我动力。谢谢
-
"..你的想法给了我动力。谢谢" 提示:添加@HovercraftFullOfEels(或任何重要的
@)到通知 新评论的人。