我正在努力创造一个3人的莫里斯板,但框架上没有任何东西显示。尽管添加了我的JPanel,它仍然是空的。如果我使用board = new JPanel(new GridLayout()),一切都很好;并执行以下操作,但我无法绘制绘制板的线条。我已经看了好几次但似乎找不到问题。
public class Project5 extends JFrame {
public final static int FRAME_WIDTH = 600;
public final static int FRAME_HEIGHT = 600;
private JButton jb[] = new JButton[9];
private Board board = new Board();
Project5(){
for(int i = 0; i<9; i++){
jb[i] = new JButton();
board.add(jb[i]);
}
add(board);
}
public static void main(String[] args) {
JFrame frame = new Project5();
frame.setTitle("Three Man's Morris");
frame.setSize(Project5.FRAME_WIDTH,Project5.FRAME_HEIGHT);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class Board extends JPanel{
public Board(){
super();
setLayout(new GridLayout(3,0,Project5.FRAME_WIDTH,Project5.FRAME_HEIGHT));
}
@Override
public void paintComponents(Graphics g){
super.paintComponents(g);
g.drawLine(0, Project5.FRAME_WIDTH, 0, Project5.FRAME_HEIGHT);
g.drawLine(0, 0, 0, Project5.FRAME_HEIGHT);
g.drawLine(0,Project5.FRAME_WIDTH,0,0);
g.drawLine(0, Project5.FRAME_HEIGHT, Project5.FRAME_WIDTH, Project5.FRAME_HEIGHT);
g.drawLine(Project5.FRAME_WIDTH, 0, 0, Project5.FRAME_HEIGHT);
g.drawLine(Project5.FRAME_WIDTH,0,Project5.FRAME_WIDTH,Project5.FRAME_HEIGHT);
}
}
答案 0 :(得分:1)
问题出在您的GridLayout()
参数中:
GridLayout(rows,cols,horizontal_gap,vertical_gap)
在您的情况下,两个差距都是600(FRAME_WIDTH
,FRAME_HEIGHT
)!
显示按钮,但它们位于面板外,尝试缩小间隙,
即。 :setLayout(new GridLayout(3,0,0,0));
你应该看到按钮。