为数独求解器构建 GUI(包含 ASCII 示例)

.

概述,示例

大家好,

我创建了一个基本的数独求解器,可以相当快地解决大多数问题。我仍然有很多工作要做,即使是最困难的问题,但我想先尝试实现一个基本的JFrame GUI。

我过去曾使用过互联网小程序,但以前从未使用过JFrames。

我想创建类似于下图的东西(对于初学者):

-------------------------------------------------------------------------------------------------
! Sudoku Solver 1.0                                                                      - [] X !
-------------------------------------------------------------------------------------------------
!  _____________ _____________ _____________         _____________ _____________ _____________  !
! |  _   _   _  |  _   _   _  |  _   _   _  |       |  _   _   _  |  _   _   _  |  _   _   _  | !
! | !5! !_! !_! | !_! !_! !_! | !6! !_! !1! |       | !5! !7! !2! | !4! !9! !3! | !6! !8! !1! | !
! |  _   _   _  |  _   _   _  |  _   _   _  |       |  _   _   _  |  _   _   _  |  _   _   _  | !
! | !6! !_! !_! | !_! !_! !2! | !4! !_! !_! |       | !6! !1! !3! | !8! !5! !2! | !4! !7! !9! | !
! |  _   _   _  |  _   _   _  |  _   _   _  |       |  _   _   _  |  _   _   _  |  _   _   _  | !
! | !_! !_! !_! | !7! !_! !1! | !_! !_! !2! |       | !8! !4! !9! | !7! !6! !1! | !3! !5! !2! | !
! -_____________-_____________-_____________-       -_____________-_____________-_____________- !
! |  _   _   _  |  _   _   _  |  _   _   _  |       |  _   _   _  |  _   _   _  |  _   _   _  | !
! | !_! !_! !4! | !_! !2! !_! | !_! !3! !_! |       | !1! !6! !4! | !9! !2! !7! | !5! !3! !8! | !
! |  _   _   _  |  _   _   _  |  _   _   _  | .---. |  _   _   _  |  _   _   _  |  _   _   _  | !
! | !_! !3! !_! | !_! !_! !_! | !_! !9! !_! | | > | | !2! !3! !8! | !5! !1! !6! | !7! !9! !4! | !
! |  _   _   _  |  _   _   _  |  _   _   _  | '---' |  _   _   _  |  _   _   _  |  _   _   _  | !
! | !_! !_! !_! | !_! !4! !_! | !_! !_! !_! |       | !7! !9! !5! | !3! !4! !8! | !1! !2! !6! | !
! -_____________-_____________-_____________-       -_____________-_____________-_____________- !
! |  _   _   _  |  _   _   _  |  _   _   _  |       |  _   _   _  |  _   _   _  |  _   _   _  | !
! | !_! !2! !_! | !1! !_! !5! | !9! !_! !_! |       | !4! !2! !7! | !1! !8! !5! | !9! !6! !3! | !
! |  _   _   _  |  _   _   _  |  _   _   _  |       |  _   _   _  |  _   _   _  |  _   _   _  | !
! | !_! !_! !_! | !6! !_! !_! | !_! !_! !5! |       | !3! !8! !1! | !6! !7! !9! | !2! !4! !5! | !
! |  _   _   _  |  _   _   _  |  _   _   _  |       |  _   _   _  |  _   _   _  |  _   _   _  | !
! | !_! !_! !6! | !_! !3! !_! | !_! !_! !7! |       | !9! !5! !6! | !2! !3! !4! | !8! !1! !7! | !
! -_____________-_____________-_____________-       -_____________-_____________-_____________- !
!                                                                                               !
! .-------------------------------------------------------------------------------------------. !
! |                                                                                           | !
! |               Solved Puzzle in 9.096ms      |      Completely Solved: True                | !
! |                                                                                           | !
! '-------------------------------------------------------------------------------------------' !
!                                                                                               !
-------------------------------------------------------------------------------------------------

.

细节

: 左谜题

  • 9x9 部分应明确定义(中间的线条;单独的框)
  • 文本框应仅接受数字/仅允许输入一个数字(如果可能)

: 右谜题

  • 9x9 部分应明确定义(中间的线条;单独的框)
  • 如果框可以/不能编辑,只要它们可以显示结果,就无关紧要

:中央按钮

  • 应该运行 [SudokuPuzzle].solve();

:底部文本框

  • 不应可编辑

.

我要找什么

我从过去的经验中知道,这都可以在JFrame中完成,但是因为我自己从未构建过一个,所以我不太确定我需要使用哪些组件(内容项,面板,设置等)来满足我的规范。我还没有找到一种方法将文本框限制为数字,并防止用户一次插入多个值。文本框真的是最佳选择,还是我错过了更具体地满足我需求的东西?

我不仅需要知道我需要哪些类,还需要知道如何组织这些类,以便按钮舒适地保持在两个谜题之间,并且文本框位于下面。从我所读到的内容来看,MigLayout似乎是简化此过程的一种选择。

.

尾注

非常感谢任何提供帮助的人。如果这个问题的任何部分显得有点粗鲁或突兀,我很抱歉。我倾向于在晚上发布我的大部分问题,所以在我尝试所有回复之前,社区有几个小时的时间来考虑它(以及我大部分时间都在外面做事的事实)。

我将再清醒1-2个小时来回答任何问题。

再次感谢,

贾斯蒂安


答案 1

old source: http://i38.tinypic.com/5mieqa.png这应该足以让您入门。只需添加 getter 逻辑即可提取他们在文本字段中输入的值。

主要:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package sudoku;

import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 *
 * @author nicholasdunn
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        JFrame frame = new JFrame("");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel();

        panel.add(new Board());
        panel.add(new JButton(">"));
        panel.add(new Board());
        frame.add(panel);
        frame.pack();
        frame.setVisible(true);
    }
}

九方:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package sudoku;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

/**
 *
 * @author nicholasdunn
 */
public class NineSquare extends JPanel {

    // What direction in relation to the center square
    private JTextField nw,n,ne,e,se,s,sw,w,c;
    private JTextField[] fields = new JTextField[]{
        nw,n,ne,e,se,s,sw,w,c
    };
    private static final int BORDER_WIDTH = 5;

    public NineSquare(Color bgColor) {
        setLayout(new GridLayout(3,3));
        initGui();
        setBackground(bgColor);
    }

    private void initGui() {
        for (int i = 0; i < fields.length; i++) {
            fields[i] = new JTextField(1);
            fields[i].setDocument(new NumericalDocument());
            add(fields[i]);
        }
        setBorder(BorderFactory.createMatteBorder(BORDER_WIDTH,BORDER_WIDTH,BORDER_WIDTH,BORDER_WIDTH, Color.BLACK));
    }

    public Dimension getPreferredDimension() {
        return new Dimension(100,100);
    }

    public static class NumericalDocument extends PlainDocument {
        String numbers = "0123456789";
        @Override
        public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
            if (getLength() == 0 && str.length() == 1 && numbers.contains(str)) {
                super.insertString(offs, str, a);
            }
            else {
                Toolkit.getDefaultToolkit().beep();
            }
        }
    }
}

板:

package sudoku;

import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.JPanel;

/**
 *
 * @author nicholasdunn
 */
public class Board extends JPanel {
    private NineSquare[] gridSquares = new NineSquare[9];
    private Color[] bgs = {Color.blue.brighter(), Color.gray};
    public Board() {
        setLayout(new GridLayout(3,3));
        for (int i = 0; i < gridSquares.length; i++) {
            gridSquares[i] = new NineSquare(bgs[i%2]);
            add(gridSquares[i]);
        }
    }
}

答案 2

数独 GUI

好吧,我忍不住自己...这是我的尝试。一切尽在一个包中:

  • 包含所有符合规范的元素的 GUI(问题)
  • 灵活的布局
  • 无外部依赖关系 - 使用标准 Swing 布局
  • 输入验证(仅数字 0-9)
  • 模型视图控制器体系结构
  • 后台任务运行程序(您的 GUI 永远不会冻结)
  • 内置一些调试方法(数独输出为文本)
  • 虚拟实现 - 模拟长时间运行的计算,显示 GUI 响应能力

我尽力使代码尽可能可读。可能有相当不明确的部分。可能线程部分并不清晰,但如果有人发现这有什么用处,我很乐意更好地描述它。

所以我的目标是最简单的用法。如果你看一下接口,真的很难打破这些东西(冻结UI,获取Null Pointer Exc等)作为编写公共API的练习。这可能不是最好的实现,但它是我写的最好的实现之一。:)

希望它有帮助。

下面是它的外观:Running example

(注意:值是随机的)

用法

您所要做的就是实现接口:

public interface SudokuImplementation {

    void goButtonPressed(Integer[][] leftSudokuValues, SudokuController resultAcceptor);
}

只需在此方法中执行所有计算并存储结果resultAcceptor.setSudokuResult()

以下是实际显示 GUI 的方法:

    SudokuImplementation sudokuImplementation =
        new YourSuperSudoku(); // <- your implementation

    SudokuView sudokuView = new SudokuView();
    sudokuView.setSudokuImplementation(sudokuImplementation);
    sudokuView.setVisible(true);

仅此而已!

法典

所有类都在默认包中 - 根据需要重构。以下是它们的列表:

  1. 数独视图 - 主 GUI
  2. 数独跑 - 示例跑步者
  3. 数独控制器 - 允许以安全的方式控制视图
  4. 数独实现 - 数独实现接口
  5. DummySudoku Implementationation - 示例实现

1.数独查看:

import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.border.*;
/**
 * View which constructs every component and creates it's own controller.
 */
public class SudokuView extends JFrame {

    SudokuController controller;

    public void setSudokuImplementation(SudokuImplementation listener) {
        controller.setListener(listener);
    }

    /** Creates new form NewJFrame */
    public SudokuView() {
        controller = new SudokuController();
        setTitle("Sudoku Solver 1.0");
        getContentPane().add(createCenterPanel(), BorderLayout.CENTER);
        getContentPane().add(createBottomPanel(), BorderLayout.SOUTH);
        setMinimumSize(new Dimension(600, 300));
        pack();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    private JPanel createBottomPanel() {
        JPanel bottomPanel = new JPanel(new GridBagLayout());
        JLabel leftLabel = createLabel("left");
        JLabel rightLabel = createLabel("right");

        controller.bindLeftLabel(leftLabel);
        controller.bindRightLabel(rightLabel);

        bottomPanel.add(leftLabel, getWholeCellConstraints());
        bottomPanel.add(new JSeparator(JSeparator.VERTICAL));
        bottomPanel.add(rightLabel, getWholeCellConstraints());

        bottomPanel.setBorder(new BevelBorder(BevelBorder.LOWERED));
        return bottomPanel;
    }

    private JLabel createLabel(String text) {
        JLabel label = new JLabel(text);
        label.setHorizontalAlignment(JLabel.CENTER);
        return label;
    }

    private JPanel createCenterPanel() {
        JPanel centerPanel = new JPanel(new GridBagLayout());
        centerPanel.add(createLeftPanel(), getWholeCellConstraints());
        centerPanel.add(createCenterButton(), getPreferredSizeConstraint());
        centerPanel.add(createRightPanel(), getWholeCellConstraints());
        return centerPanel;
    }

    private GridBagConstraints getPreferredSizeConstraint() {
        // default will do
        return new GridBagConstraints();
    }

    private JButton createCenterButton() {
        JButton goButton = new JButton(">");
        controller.bindCenterButton(goButton);
        return goButton;
    }
    private static final Insets sixPixelInset = new Insets(6, 6, 6, 6);

    private JPanel createRightPanel() {
        JPanel rightPanel = create3x3Panel(6);
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                JPanel panel2 = create3x3Panel(2);
                fillPanelWithNonEditable(panel2, i, j);
                rightPanel.add(panel2);

            }
        }
        rightPanel.setBorder(new EmptyBorder(sixPixelInset));
        return rightPanel;
    }

    private JPanel createLeftPanel() {
        JPanel leftPanel = create3x3Panel(6);
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                JPanel panel2 = create3x3Panel(2);
                fillPanelWithEditable(panel2, i, j);
                leftPanel.add(panel2);

            }
        }
        leftPanel.setBorder(new EmptyBorder(sixPixelInset));
        return leftPanel;
    }

    private GridBagConstraints getWholeCellConstraints() {
        GridBagConstraints wholePanelCnstr = getPreferredSizeConstraint();
        wholePanelCnstr.fill = java.awt.GridBagConstraints.BOTH;
        wholePanelCnstr.weightx = 1.0;
        wholePanelCnstr.weighty = 1.0;
        return wholePanelCnstr;
    }

    private void fillPanelWithEditable(JPanel panel, int majorRow, int majorColumn) {
        for (int minorRow = 0; minorRow < 3; minorRow++) {
            for (int minorColumn = 0; minorColumn < 3; minorColumn++) {
                final JFormattedTextField editableField = createEditableField();
                int column = majorColumn * 3 + minorColumn;
                int row = majorRow * 3 + minorRow;
                controller.bindLeftSudokuCell(row, column, editableField);
                panel.add(editableField);
            }
        }
    }

    private void fillPanelWithNonEditable(JPanel panel, int majorRow, int majorColumn) {
        for (int minorRow = 0; minorRow < 3; minorRow++) {
            for (int minorColumn = 0; minorColumn < 3; minorColumn++) {
                final JFormattedTextField editableField = createNonEditableField();
                int column = majorColumn * 3 + minorColumn;
                int row = majorRow * 3 + minorRow;
                controller.bindRightSudokuCell(row, column, editableField);
                panel.add(editableField);
            }
        }
    }

    private JPanel create3x3Panel(int gap) {
        final GridLayout gridLayout = new GridLayout(3, 3, 1, 1);
        gridLayout.setHgap(gap);
        gridLayout.setVgap(gap);
        JPanel panel = new JPanel(gridLayout);
        return panel;
    }

    private JFormattedTextField createNonEditableField() {
        JFormattedTextField field = createEditableField();
        field.setEditable(false);
        field.setBackground(Color.WHITE); // otherwise non-editable gets gray
        return field;
    }

    private JFormattedTextField createEditableField() {
        JFormattedTextField field = new JFormattedTextField();
        // accept only one digit and nothing else
        try {
            field.setFormatterFactory(new DefaultFormatterFactory(new MaskFormatter("#")));
        } catch (java.text.ParseException ex) {
        }
        field.setPreferredSize(new Dimension(16, 30));
        field.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        field.setText(" ");
        field.setBorder(null);
        return field;
    }
}

2. 数独运行:

import java.awt.EventQueue;
import javax.swing.UIManager;

public class SudokuRun implements Runnable {

    public void run() {
        // ******************** here You can swap Your true implementation
        SudokuImplementation sudokuImplementation = new DummySudokuImplementation();
        // ***************************** *************** ********* **** ** *


        SudokuView sudokuView = new SudokuView();
        sudokuView.setSudokuImplementation(sudokuImplementation);
        sudokuView.setVisible(true);
    }

    public static void main(String args[]) {
        tryToSetSystemLookAndFeel();
        EventQueue.invokeLater(new SudokuRun());
    }

    private static void tryToSetSystemLookAndFeel() {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception ex) {
            System.out.println("Couldn't set LAF");
        }
    }
}

3. 数独控制器:

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;

public class SudokuController {

    JLabel leftLabel, rightLabel;
    JFormattedTextField[][] leftSudoku, rightSudoku;
    JButton goButton;

    public SudokuController() {
        leftSudoku = new JFormattedTextField[9][9]; // standard sudoku size
        rightSudoku = new JFormattedTextField[9][9];
    }

    void bindLeftLabel(JLabel label) {
        leftLabel = label;
    }

    void bindRightLabel(JLabel label) {
        rightLabel = label;
    }

    void bindLeftSudokuCell(final int row, final int column, JFormattedTextField field) {
        field.addPropertyChangeListener("value", new PropertyChangeListener() {

            // if user edits field than You could do something about it here
            public void propertyChange(PropertyChangeEvent evt) {
                if (evt.getNewValue() != null) {
                    String newValue = (String) evt.getNewValue();
                    userEditedValueAt(row, column, Integer.valueOf(newValue));
                }
            }
        });
        leftSudoku[row][column] = field;
    }

    void userEditedValueAt(int row, int column, int value) {
        System.out.println("Value changed at row:" + row + ", column:" + column + " to " + value);
    }

    void bindRightSudokuCell(int row, int column, JFormattedTextField field) {
        rightSudoku[row][column] = field;
    }

    void spitOutSudokus() {
        System.out.println("Left:");
        System.out.println(getPrettyPrinted(leftSudoku));
        System.out.println("Right:");
        System.out.println(getPrettyPrinted(rightSudoku));
    }

    private String getPrettyPrinted(JFormattedTextField[][] sudoku) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 9; i++) {
            sb.append("|");
            for (int j = 0; j < 9; j++) {
                if (sudoku[i][j] != null) {
                    sb.append(sudoku[i][j].getText());
                } else {
                    sb.append("-");
                }
                sb.append(" ");
            }
            sb.append("|\n");
        }
        return sb.toString();
    }

    void bindCenterButton(JButton goButton) {
        this.goButton = goButton;
        goButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                goButtonPressed();
            }
        });
    }
    SudokuImplementation listener;

    public void setListener(SudokuImplementation listener) {
        this.listener = listener;
    }
    Thread backGroundThread;

    private void goButtonPressed() {
        if (listener != null) {
            if (backGroundThread == null || (backGroundThread != null && !backGroundThread.isAlive())) {
                backGroundThread = new Thread() {

                    @Override
                    public void run() {
                        listener.goButtonPressed(getLeftValues(), SudokuController.this);
                    }
                };
                backGroundThread.start();
            }
        }
    }

    private Integer[][] getLeftValues() {
        Integer[][] values = new Integer[9][9];
        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                if (!leftSudoku[i][j].getText().equals(" ")) {
                    values[i][j] = Integer.valueOf(leftSudoku[i][j].getText());
                }
            }
        }
        return values;
    }

    public void setSudokuResult(final Integer[][] result) {
        // Any GUI interaction must be done on EDT
        // We don't want to block computation so we choose invokeLater
        // as opposed to invokeAndWait.
        EventQueue.invokeLater(new Runnable() {

            public void run() {
                for (int i = 0; i < 9; i++) {
                    for (int j = 0; j < 9; j++) {
                        rightSudoku[i][j].setValue(String.valueOf(result[i][j]));
                    }
                }
            }
        });
    }

    public void setSudokuTime(final String time) {
        EventQueue.invokeLater(new Runnable() {

            public void run() {
                leftLabel.setText("<html>Running time: <b>" + time);
            }
        });
    }

    public void setSudokuCompleted(final boolean completed) {
        EventQueue.invokeLater(new Runnable() {

            public void run() {

                rightLabel.setText("<html>Completely Solved: <b>" + completed);
                if (completed) {
                    spitOutSudokus();
                }

            }
        });
    }
}

4. 数独实施:

public interface SudokuImplementation {

    void goButtonPressed(Integer[][] leftSudokuValues, SudokuController resultAcceptor);
}

5. 假人二德实现:

import java.util.concurrent.TimeUnit;

/**
 * Simulates Sudoku solver. Demonstrates how to update GUI. The whole
 * implementation is constructed so GUI never freezes.
 */
class DummySudokuImplementation implements SudokuImplementation {

    public DummySudokuImplementation() {
    }

    public void goButtonPressed(Integer[][] leftSudokuValues, SudokuController resultAcceptor) {
        System.out.println("Long running computation simulation...");
        for (int i = 0; i < 50; i++) {
            resultAcceptor.setSudokuCompleted(false);
            resultAcceptor.setSudokuTime(String.valueOf(i * 50) + "ms");
            resultAcceptor.setSudokuResult(getRandomResult());
            waitSomeTime();
        }
        resultAcceptor.setSudokuResult(leftSudokuValues);
        resultAcceptor.setSudokuCompleted(true);
        waitSomeTime();
        System.out.println("Done!");
    }

    private void waitSomeTime() {
        try {
            TimeUnit.MILLISECONDS.sleep(50);
        } catch (InterruptedException ex) {
        }
    }

    private Integer[][] getRandomResult() {
        Integer[][] randomResult = new Integer[9][9];
        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                randomResult[i][j] = (int) (Math.random() * 9);
            }
        }
        return randomResult;
    }
}

解释

我不认为我的方式是最好的。我很想看到其他答案,比方说,所有视图都用MigLayout完成。这将是非常有启发性的。我正在学习Swing GUI时,Sun的实现只有一个,所以它在我的风格中占了上风。也就是说,我建议咨询Sun的Swing GUI短期课程。它还包括一个简单的研究案例。读完后,数独View的几乎整个部分都应该很清楚。

我确实将代码分开,使其更具可读性。这就是为什么控制器是另一个类,而不是视图的一部分。该视图仅用于构建小部件和布局,但为了使其简单(而不是创建更多的类),我还在其中初始化控制器。

真正的工作是在控制器中。它包含最毛茸茸的细节...线程也在那里,所以它实际上的作用并不那么明显。我从头开始实现了一个 Thread 类。还有另一种选择:使用SwingWorker。这可能是一个陈词滥调,但要明确一点:我使用线程来使GUI随时响应。如果没有适当的线程,整个GUI将在计算发生时冻结。我决定从数独的实现角度让它尽可能简单,比如非阻塞增量更新。

至于线程,了解哪些代码在哪个线程中运行至关重要。GUI 组件触发的每个操作都在 EDT(事件调度线程)上运行。如果在其上执行任何长时间运行的任务,GUI 将无法响应。所以我只是创建另一个线程(参见 的实现)并启动它。之后,EDT 可以处理任何其他事件而不会阻塞。goButtonPressed()

所以你的数独在一个特殊的后台线程中运行。它可以做任何它想做的事情,除非它必须更新GUI。几乎可以肯定它会,因为这是部分更新的地方。这里有一个问题:如果你直接调用任何GUI组件(设置一些值),那么GUI就会冻结。这是一个称为 EDT 调度冲突的条件。与 Swing 的所有交互都应在 EDT 上进行,以避免任何冻结。怎么办?EDT为此提供了特殊的事件队列。在队列上发布更新事件。在EDT上,代码不断监视传入事件并相应地更新GUI。所以基本上,它是后台线程和EDT之间的通信。要在队列上发布事件,您可以使用专门为此设计的特殊实用程序方法:.看看方法:EventQueue.invokeLater(new Runnable() { /* here goes your GUI interaction */ });SudokuController

  • setSudokuResult()
  • public void setSudokuTime()
  • setSudokuCompleted()

那是发布GUI更新事件。


推荐