我无法在 Jframe 上绘制两个项目(还会有更多),我正在尝试制作风景,但最后绘制的项目会覆盖它之前的任何内容。
主要:
import javax.swing.*;
import java.awt.*;
public class TheComponets extends JComponent {
public static void main(String[] args){
JFrame frame = new JFrame();
frame.setSize(600, 600);
frame.setTitle("A house on the water!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
House home = new House();
Sun sun = new Sun();
frame.setLayout(new GridLayout(2,3));
frame.add(home);
frame.add(sun);
}
}
房屋等级:
import javax.swing.*;
import java.awt.*;
import java.applet.*;
// Program to draw a house
public class House extends JComponent
{
public void paintComponent(Graphics g)
{
// Draw the roof
g.setColor(Color.red);
int xs[] = {100,160,220};
int ys[] = {100,50,100};
Polygon poly=new Polygon(xs,ys,3);
g.fillPolygon(poly);
// Draw the body of house
g.setColor(Color.blue);
g.fillRect(100,100,120,120);
// draw the door
g.setColor(Color.orange);
g.fillRect(145,160,30,60);
}
}
太阳课:
import javax.swing.*;
import java.awt.*;
public class Sun extends JComponent {
public void paintComponent(Graphics g)
{
// draw sun
g.setColor(Color.yellow);
g.fillOval(500, 0, 50, 50);
}
}
我希望房子和太阳显示在 Jframe 中,但目前它只会显示最后一个 frame.add() 对象。我才编程两个月,对Swing和awt不太了解。请在回答时牢记这一点。
最佳答案
这样做的原因是 JFrame
使用 BorderLayout默认情况下。当您frame.add(component)
没有任何约束时,组件将被添加到BorderLayout.CENTER
位置。因此,无论您在没有约束的情况下添加多少个组件,borderlayout 都会覆盖旧的组件,因为所有这些组件都被添加到 CENTER
。
解决方案是选择要添加组件的位置:
frame.add(home,BorderLayout.CENTER);
frame.add(sun,BorderLayout.LINE_START);
更改容器的布局(在您的情况下为 JFrame):
frame.setLayout(new FlowLayout());
frame.add(home);
frame.add(sun);
值得一读:A Visual Guide to Layout Managers
最后,不要使用 @Override
paint()
方法。而是使用 @Override
paintComponent()
方法。
关于java - 无法将两个项目绘制到 Jframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55956065/