【发布时间】:2018-12-11 23:54:27
【问题描述】:
这是我第一个使用 AWT/Swing 的项目。我正在尝试设计一个简单的元胞自动机。我在选择布局管理器时遇到了一些问题,现在我使用的是 GridLayout,因为它最接近我想要的。但是,当尝试在 JPanel 中放置一个单元格时,坐标无法按我的预期工作。也许我不应该从 JComponent 扩展并使用 fillRect()?或者也许 GridLayout 不是我需要的布局?主要问题是点 (0,0) 似乎在“移动”。 fillRect 是否与 GridLayout 冲突?
注意 1:我试过 GridBagLayout 但没有用(因为我不知道如何配置它)。我也尝试过 add(component, x, y) 方法,但没有成功。
注意 2:我没有发布有关单元格状态的代码,因为它不相关。
编辑:好的,我在单个公共类中写了一个示例,我认为我不能更简洁并重现相同的结果。
解决方案: https://docs.oracle.com/javase/tutorial/uiswing/painting/refining.html
这是我的代码:
public class Example{
class Cell extends JComponent{
private int x = 0; //Cell position ?
private int y = 0;
public Cell(int x, int y){
this.x = x;
this.y = y;
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
//draw cell
g.setColor(Color.white);
g.fillRect(x,y,15,15);
}
}
Example(){
JFrame frame = new JFrame("title");
frame.setBackground(Color.black);
frame.getContentPane().setPreferredSize(new Dimension(300,300));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
JPanel box = new JPanel(new GridLayout(20,20)){
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
setBackground(Color.black);
//draw grid
for(int i = 0; i <= this.getHeight(); i += 15){
g.drawLine(0,0+i,getWidth(),0+i);
}
for(int i = 0; i <= this.getWidth(); i += 15){
g.drawLine(0+i,0,0+i,getHeight());
}
}
};
/*box.add(new Cell(0,0)); //TEST 1
box.add(new Cell(0,0));
box.add(new Cell(0,0));
box.add(new Cell(0,0));*/
box.add(new Cell(0,0)); //TEST 2
box.add(new Cell(15,0));
box.add(new Cell(30,0));
box.add(new Cell(45,0));
frame.add(box);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args){
new Example();
}
}
这是对应于 TEST 1 和 TEST 2 的结果:
【问题讨论】:
-
“我没有发布有关单元格状态的代码,因为它不相关。” 好电话。也没有3个公共课程。将minimal reproducible example 作为edit 发布到问题中。
-
如果你正在做定制绘画,你应该阅读文档Painting in AWT and Swing,它包含了很多重要的信息。您在帖子标题中的问题可能在this section 中得到解答,但您应该阅读整个页面。我也同意 Andrew 的评论,如果您需要有关代码的特定帮助,您需要发布 MCVE。
标签: java swing layout awt coordinates