在JFrame中绘制网格

xZe*_*asy 3 java swing

我现在有一个9x9网格的按钮,我想在这些按钮之间绘制一些线来分隔它们并制作3x3网格.

我在另一个窗口的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();
}
Run Code Online (Sandbox Code Playgroud)

}

Hov*_*els 6

不要像你想要的那样直接在JFrame上绘图.如果您不知道自己在做什么(例如,您没有调用超级的绘画方法并且无意中以这种方式打破绘画链),则会带来很大的风险,并且绘制的图像将不会显示为由不透明的contentPane覆盖.

如果你需要绘制,那么在一个JPanel中进行绘制,然后在JFrame中显示,但是再次按照下面的例子,如果你想要的只是网格中的黑色直线,则无需绘制.

使用GridLayout,并在布局中设置一些间隙.理解GridLayout构造函数的第3和第4个参数将为您提供空白.然后给基础JPanel一个Color.BLACK背景,你去吧:行!例如,使用JTextFields:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class SudokuMCVE extends JPanel {
    private static final int CLUSTER = 3;
    private static final int MAX_ROWS = 9;
    private static final float FIELD_PTS = 32f;
    private static final int GAP = 3;
    private static final Color BG = Color.BLACK;
    private static final Color SOLVED_BG = Color.LIGHT_GRAY;
    public static final int TIMER_DELAY = 2 * 1000;
    private JTextField[][] fieldGrid = new JTextField[MAX_ROWS][MAX_ROWS];

    public SudokuMCVE() {
        JPanel mainPanel = new JPanel(new GridLayout(CLUSTER, CLUSTER));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
        mainPanel.setBackground(BG);
        JPanel[][] panels = new JPanel[CLUSTER][CLUSTER];
        for (int i = 0; i < panels.length; i++) {
            for (int j = 0; j < panels[i].length; j++) {
                panels[i][j] = new JPanel(new GridLayout(CLUSTER, CLUSTER, 1, 1));
                panels[i][j].setBackground(BG);
                panels[i][j].setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
                mainPanel.add(panels[i][j]);
            }
        }

        for (int row = 0; row < fieldGrid.length; row++) {
            for (int col = 0; col < fieldGrid[row].length; col++) {
                fieldGrid[row][col] = createField(row, col);
                int i = row / 3;
                int j = col / 3;
                panels[i][j].add(fieldGrid[row][col]);
            }
        }

        setLayout(new BorderLayout());
        add(mainPanel, BorderLayout.CENTER);
        add(new JButton(new SolveAction("Solve")), BorderLayout.PAGE_END);
    }

    private JTextField createField(int row, int col) {
        JTextField field = new JTextField(2);
        field.setHorizontalAlignment(JTextField.CENTER);
        field.setFont(field.getFont().deriveFont(Font.BOLD, FIELD_PTS));

        return field;
    }

    private class SolveAction extends AbstractAction {

        public SolveAction(String name) {
            super(name);
            int mnemonic = (int) name.charAt(0);
            putValue(MNEMONIC_KEY, mnemonic);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            new Timer(TIMER_DELAY, new ActionListener() {
                private int i = 0;
                private int j = 0;

                @Override
                public void actionPerformed(ActionEvent e) {
                    // MAX_ROWS is 9
                    if (i == MAX_ROWS) {
                        ((Timer) e.getSource()).stop();
                    }
                    if (j == MAX_ROWS) {
                        i++;
                        j = 0;
                    }
                    int number = (int) (MAX_ROWS * Math.random()) + 1;
                    fieldGrid[i][j].setBackground(SOLVED_BG);
                    fieldGrid[i][j].setText(String.valueOf(number));

                    j++;
                }
            }).start();
        }
    }

    private static void createAndShowGui() {
        SudokuMCVE mainPanel = new SudokuMCVE();

        JFrame frame = new JFrame("SudokuMCVE");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            createAndShowGui();
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

其中显示为:

在此输入图像描述

或者使用JButtons:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.*;

@SuppressWarnings("serial")
public class JPanelGrid extends JPanel {
    private static final int SML_SIDE = 3;
    private static final int SIDE = SML_SIDE * SML_SIDE;
    private static final int GAP = 3;
    private static final Color BG = Color.BLACK;
    private static final Dimension BTN_PREF_SIZE = new Dimension(80, 80);
    private JButton[][] buttons = new JButton[SIDE][SIDE];

    public JPanelGrid() {
        setBackground(BG);
        setLayout(new GridLayout(SML_SIDE, SML_SIDE, GAP, GAP));
        setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
        JPanel[][] smallPanels = new JPanel[SML_SIDE][SML_SIDE];
        for (int i = 0; i < smallPanels.length; i++) {
            for (int j = 0; j < smallPanels[i].length; j++) {
                smallPanels[i][j] = new JPanel(new GridLayout(SML_SIDE, SML_SIDE));
                add(smallPanels[i][j]);
            }
        }
        for (int i = 0; i < buttons.length; i++) {
            int panelI = i / SML_SIDE;
            for (int j = 0; j < buttons[i].length; j++) {
                int panelJ = j / SML_SIDE;
                String text = String.format("[%d, %d]", j, i);
                buttons[i][j] = new JButton(text);
                buttons[i][j].setPreferredSize(BTN_PREF_SIZE);
                smallPanels[panelI][panelJ].add(buttons[i][j]);
            }
        }
    }

    private static void createAndShowGui() {
        JPanelGrid mainPanel = new JPanelGrid();

        JFrame frame = new JFrame("JPanelGrid");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            createAndShowGui();
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

哪个显示:

在此输入图像描述