我現在有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