2014 年 1 月 19 日更新(适用于遇到此类问题的人)
我在下面描述的问题源于我的圆类扩展了 JPanel。所以我从这个类创建的每个圆圈实际上都是它自己的面板。因此,通过添加布局,我可以看到两个圆圈。我现在了解到,拥有一个扩展 JPanel 的单独“板类”是更明智的做法,并且在本例中让圆圈不扩展任何内容。这样我就可以在circle类中实现drawMySelf方法并将它们绘制在我的板上。这样我就可以在同一个面板中拥有各种几何对象!
更新结束。
我正在执行一项任务,需要绘制两个圆圈。当我调整框架大小时,这些圆圈应该随机重新定位。并且需要在它们的中心之间有一条线来说明距离。我的圆圈课遇到了麻烦。当我将自定义圆圈添加到测试程序时,只出现其中一个。我不明白为什么。我认为我的代码中有一个错误,导致程序跳过其中的一些内容。因为我只出现一个圆圈。谁能看出这段代码有什么问题吗?
请记住,我应该使用迄今为止学到的工具。 JPanel、JFrame、重写paintComponent()。
圆类:
package oppgave4;
import javax.swing.*;
import java.awt.*;
public class Circle extends JPanel {
public static final int OVAL = 1;
public static final int ANOTHEROVAL = 2;
public int OVALCENTER = 0;
public int ANOTHEROVALCENTER = 0;
private int type = 1;
private boolean filled = false;
public Circle(){
}
public Circle(int type){
this.type = type;
}
public Circle(int type, boolean filled){
this.type = type;
this.filled = filled;
}
protected void paintComponent(Graphics g){
super.paintComponent(g);
int width = getWidth();
int height = getHeight();
int randomWidth = (int)(width * Math.random());
int randomHeight = (int)(height * Math.random());
switch (type){
case OVAL:
g.setColor(Color.BLUE);
if(filled)
g.fillOval(randomWidth, randomHeight, 30, 30);
else
g.drawOval(randomWidth, randomHeight, 30, 30);
case ANOTHEROVAL:
g.setColor(Color.RED);
if(filled)
g.fillOval(randomWidth, randomHeight, 30, 30);
else
g.drawOval(randomWidth, randomHeight, 30, 30);
break;
}
}
}
测试程序:当我运行这个程序时,只会出现红色圆圈。
package oppgave4;
import javax.swing.*;
import java.awt.*;
public class TestProgram extends JFrame {
public TestProgram(){
add(new Circle(Circle.OVAL));
add(new Circle(Circle.ANOTHEROVAL));
}
public static void main(String[] args) {
TestProgram sirkel = new TestProgram();
sirkel.setSize(400, 300);
sirkel.setLocationRelativeTo(null);
sirkel.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sirkel.setVisible(true);
}
}
最佳答案
尝试使用默认 BorderLayout 之外的布局管理器添加它们,看看会发生什么
import java.awt.*;
public TestProgram(){
setLayout(new GridLayout(1, 2);
add(new Circle(Circle.OVAL));
add(new Circle(Circle.ANOTHEROVAL));
}
另一个解决方案是使用 JFrame
的默认 BorderLayout
。当您只需.add(something)
时,它将自动添加到BorderLayout.CENTER
,除非您指定位置。一个 BorderLayout,每个位置只容纳一个组件。因此,当您尝试添加第二个时,只有第二个会出现在 CENTER
位置。
如果你这样做了
public TestProgram(){
setLayout(new GridLayout(1, 2);
add(new Circle(Circle.OVAL), BorderLayout.CENTER);
add(new Circle(Circle.ANOTHEROVAL), BorderLayout.SOUTH);
}
它也可以工作
关于java - 了解paintComponent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19877365/