我现在有9x9的按钮网格,我想在这些按钮之间绘制一些线条以将它们分开并制作3x3网格。在JFrame中绘制网格
我在另一个窗口的JPanel中尝试了我的方法,它工作正常,但我无法在我的JFrame中与我的按钮一起工作,因为它什么都没画。 每个按钮之间已经有一些空间,所以我们可以看到该线是否存在。
非常感谢您的未来帮助。
下面是代码:
import javax.swing.*;
import java.awt.*;
public class ButtonGrid extends JPanel{
JFrame frame=new JFrame();
int t = 9;
public ButtonGrid(){ //constructor
frame.setLayout(new GridLayout(t, t, 3, 3));
addButtons(frame, t);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
@Override public void paint(Graphics g) {
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.BLACK);
for (int i = 0; i <= 9; i++) {
if (i % 3 == 0) {
int coord = i * 58;
coord++;
g.drawLine(coord, 0, coord, 58*9);
g.drawLine(0, coord, 58*9, coord);
}
}
}
private void addButtons(JFrame frame, int t){
JButton grid;
for(int y=0; y<t; y++){
for(int x=0; x<t; x++){
grid=new JButton(x+","+y); //creates new button
grid.setPreferredSize(new Dimension(55,55));
frame.add(grid); //adds button to grid
}
}
}
public static void main(String[] args) {
new ButtonGrid();
}
}
非常感谢解释,现在我明白了。 – xZeasy