更新14年1月19日(适用于遇到此类问题的人)
我描述的问题源于我的圈子类扩展了JPanel的事实。因此,我从此类创建的每个圈子实际上都是其自己的面板。因此,通过添加布局,我可以看到两个圆圈。现在,我们了解到,它的Wiser拥有一个扩展JPanel的单独的“板类”,在这种情况下,让圆圈不进行任何扩展。这样,我可以在circleclass中实现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));
}
另一种解决方案是使用
BorderLayout
的默认JFrame
。当您仅使用.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);
}
它也会工作