英文:
Weird BoxLayout painting
问题
我尝试按行显示一个对象,其中每一行都是一个对象。然后我使用了一个框布局,但这样做时只有顶部图层(也就是最后一个被调用的对象)被绘制,如何修复这个问题?
这是一个最小的示例:
import javax.swing.*;
import java.awt.*;
public class Main {
public static void main(String[] args) {
MainFrame frame = new MainFrame();
}
}
private class MainFrame extends JFrame {
public MainFrame(){
setSize(600,400);
setLocationRelativeTo(null);
setVisible(true);
setContentPane(new Container());
}
}
private class Container extends JPanel {
public Container(){
setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
for(int i =0;i<10;i++){
add(new Line());
}
}
}
private class Line extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.green);
g.fillRect(getX(),getY(),getWidth(),getHeight());
}
}
这是我得到的效果:
这是我期望的效果:
一些测试(在JBackPannel类的paint方法中的蓝色矩形)向我展示了某处正在绘制一个白色画布,但我不知道是在哪里以及为什么...
这是一个最小示例的链接。
英文:
I was trying to dysplay an object line by line where each line is an object. Then I use a box Layout but when I do so only the top layer (which is the last object called) is drawed how can I fiw this ?
here is a minimal exemple :
import javax.swing.*;
import java.awt.*;
public class Main {
public static void main(String[] args) {
MainFrame frame = new MainFrame();
}
}
private class MainFrame extends JFrame {
public MainFrame(){
setSize(600,400);
setLocationRelativeTo(null);
setVisible(true);
setContentPane(new Container());
}
}
private class Container extends JPanel {
public Container(){
setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
for(int i =0;i<10;i++){
add(new Line());
}
}
}
private class Line extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.green);
g.fillRect(getX(),getY(),getWidth(),getHeight());
}
}
here is what I've got :
and what I've expected :
Some test (the blue rectangle in the paint method of the JBackPannel class) showed me that somewhere something is drawing a white canvas, but I don't know where and why ...
here is a link to a minimal exemple
答案1
得分: 2
自定义绘制始终相对于组件而不是父面板中组件的位置进行。所以:
g.fillRect(getX(),getY(),getWidth(),getHeight());
应该是:
g.fillRect(0, 0, getWidth(), getHeight());
英文:
Custom painting is always done relative to the component, not the components location in the parent panel.
So:
g.fillRect(getX(),getY(),getWidth(),getHeight());
should be:
g.fillRect(0, 0, getWidth(), getHeight());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论