0

嗨,我正在开始编程,我正在编写一个由网格组成的程序,当按下单个方块时会改变颜色。我想知道如何实现一个允许我输入数字的 JTextField,这反过来会创建一个该数字的方形网格(例如,如果我输入 10,我将得到一个 10x10 的网格......)

这些都是我的画布和画布面板类:

    import java.awt.*; 
    import javax.swing.*; 
    import java.awt.event.*;

    public class CanvasPanel extends JFrame implements ActionListener{ 
      private JPanel buttonPanel;           
      private JButton sizeButton, clearButton, keepButton, saveButton;
      private JTextField sizeText, saveText;
      private Canvas canvas;            
      Thread runningThread;                    
    /**
     * constructor - builds buttons and board (in an instance of NewCanvas)
     */
    public CanvasPanel() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("The Game of Life");
        //buttons
        buttonPanel=new JPanel();
        sizeText = new JTextField();
        sizeButton = new JButton("size");
        clearButton = new JButton("clear");
        keepButton = new JButton("keep");
        saveText = new JTextField();
        saveButton = new JButton("save");
        buttonPanel.setLayout(new GridLayout(1,4));
        buttonPanel.add(sizeText);
        buttonPanel.add(sizeButton);         
        buttonPanel.add(clearButton);
        buttonPanel.add(keepButton);
        buttonPanel.add(saveText);
        buttonPanel.add(saveButton);

        sizeButton.addActionListener(this);
        clearButton.addActionListener(this);
        keepButton.addActionListener(this);
        saveButton.addActionListener(this);
        setLayout(new BorderLayout());
        add(buttonPanel, BorderLayout.NORTH);
        //board
        canvas=new Canvas("click to give life to a square");
        canvas.setBorder(BorderFactory.createLineBorder(Color.black,6));
        add(canvas, BorderLayout.CENTER);
        //ready to go
        setSize(500,500);         setVisible(true);
    }

    /**
     * This object is its own Listener so respond to button presses
     */
    public void actionPerformed(ActionEvent e){
        if (e.getSource()==sizeButton)
            canvas.step();
        if (e.getSource()==clearButton)
            canvas.clear();
        if (e.getSource()==keepButton){
            runningThread=new Thread(canvas);//start LifeCanvas in own thread
            runningThread.start();         }
        if (e.getSource()==saveButton){
            canvas.stopit();          }            
    }
}

.

    import java.awt.*; import javax.swing.*; 


    import java.awt.event.*;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    /**
     * This class displays the game of Life using SWing
     */
    public class Canvas extends JPanel implements MouseListener,Runnable{
    private String status;
    private boolean keepGoing;
    private Grid board;
    private static final int ROWS = 10;
    private static final int COLUMNS = 10;  
    /**
     * constructor builds the LifeCanvas and creates Model
     */
    public Canvas(String initstring) {
        status=initstring;
        setBackground(Color.white);         
        board=new Grid(ROWS, COLUMNS); 
        this.addMouseListener(this);
    }


    /**
     * paints the Canvas - calls drawgris()
     */
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        drawgrid(g);          g.drawString(status,70, 20);
    }


    /**
     * the actual drawing 
     */
    public void drawgrid(Graphics g) {
        int i,j,starti=40,startj=40;
        g.setColor(Color.blue);
        for (i=0; i<ROWS; i++)
            for (j=0; j<COLUMNS; j++)
                if (!board.isAlive(i+1,j+1))
                    g.drawRect(starti+i*20,startj+j*20,18,18);
                else
                    g.fillRect(starti+i*20,startj+j*20,18,18);
    }     


    /**
     * this method could be improved a lot with a calculation
     */
    public void mouseClicked(MouseEvent e) {
        int i,j,starti=40,startj=40;
        int x=e.getX(); int y=e.getY();
        for (i=0; i<ROWS; i++)
            for (j=0; j<COLUMNS; j++)
                if ( x > starti+i*20 && x < starti+i*20+18 &&
                y > startj+j*20 && y < startj+j*20+18){
                    board.setValue(i+1, j+1, true);
        }
        this.repaint();
    }


    /**
     * one step
     */
    public void step()      {
        status="performed a step";
        board.calc();
        board.copy();
        repaint();
    }   


    /**
     * clears board
     */
    public void clear() {
        board.clear();
        repaint();
    }


    /**
     * keepsgoing until stopped
     */
    public void run(){
        int i=0;
        status="1 iteration" ;
        keepGoing=true;    
        try{
            while (keepGoing) {
                board.calc();
                if (!board.hasChanged())
                {status="stable in "+i+" moves"; repaint(); break;}
                if (i==100) 
                {status="100 generations and still changing";repaint();break;}
                board.copy();
                i++;
                status=i+" iterations";          //need slow down here
                Thread.sleep(200);
                repaint();
            }
        }
        catch (InterruptedException e) {}
    }


    /**
     * stop loop
     */
    public void stopit(){
        keepGoing=false;
        status="stopped";
    } 


    public void writeSerializable(String path) throws IOException {
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path));
        oos.writeObject(this);
        oos.close();        
    }

    public static Canvas readSerializable(String path) throws IOException{
        Canvas result = null;
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(path));
        try{
            result = (Canvas)ois.readObject();
        }
        catch(ClassNotFoundException cnf){
            throw new IOException ("problem loading serializable file "+path);
        }
        return result;
    }

    public void mouseReleased( MouseEvent e) { }


    public void mousePressed( MouseEvent e) {}


    public void mouseEntered( MouseEvent e) {}


    public void mouseExited( MouseEvent e){} 
 }
4

1 回答 1

0

这取决于您想要实现的目标,例如您想要文本字段的位置。

您可以创建一个 JTextField,然后使其不可见 (setVisible(false))。然后你可以移动它,让它随时随地可见。

或者,您可以弹出一个对话框,而不是使用 JTextField,如下所示:

userInput = JOptionPane.showInputDialog ( "Please type a number:" );

然后您将输入作为字符串返回。然后你可以检查它是否是一个有效的数字,如果不是,你可以再次弹出它。

于 2013-12-06T17:36:07.450 回答