创建一个循环来绘制垂直线

时间:2014-02-03 10:37:15

标签: java swing loops

我试图在java中绘制一个国际象棋棋盘,为了做到这一点,我开始画垂直线。我已经完成了,但我没有写出每一行,而是想实现一个循环。我是初学者,所以一些建议真有帮助!先感谢您。

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

public class ChessBoard extends JFrame implements ActionListener
{
    private JButton button;
    private JPanel panel;

    public static void main(String[] args)
    {
        ChessBoard demo = new ChessBoard();
        demo.setSize(400,300);
        demo.createGUI();
        demo.setVisible(true);
    }

    private void createGUI()
    {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        Container window = getContentPane();
        window.setLayout(new FlowLayout());

        panel = new JPanel();
        panel.setPreferredSize(new Dimension(800,800));
        panel.setBackground(Color.white);
        window.add(panel);

        button = new JButton("start");
        window.add(button);
        button.addActionListener(this);
    }

    public void actionPerformed(ActionEvent event)
    {
        int xLeft;
        int yTop;
        Graphics paper = panel.getGraphics();
        paper.setColor(Color.black);
        paper.fillRect(0,0,800,800);
        paper.setColor(Color.white);
        xLeft = 0;
        paper.drawLine(100, 0, 100, 800); 
        paper.drawLine(200, 0, 200, 800); 
        paper.drawLine(300, 0, 300, 800); 
        paper.drawLine(400, 0, 400, 800); 
        paper.drawLine(500, 0, 500, 800); 
        paper.drawLine(600, 0, 600, 800); 
        paper.drawLine(700, 0, 700, 800); 
        paper.drawLine(800, 0, 800, 800); 

    }

}

3 个答案:

答案 0 :(得分:1)

用循环变量替换变量元素,例如

//you could probably also replace both instances of 800 here with a 'max' variable and the 100s with 'squareSize'
for (int i = 100; i<=800; i+=100)
{
  paper.drawLine(i, 0, i, 800); 
}

for循环的解释

 for ( A;  B;  C)

A:首次进入循环语句时执行此操作

B:检查是否属实,如果是,则执行循环

C:每次循环执行时,都要在之后执行。

因此,我们将i设置为100,执行循环并向i添加100。如果i超过800,请继续循环。


<强>另外

这不是绘制UI的好方法

Graphics paper = panel.getGraphics();

让您的面板@Override成为paint(Graphics g)方法,并使用其中传递的图形对象进行绘制,这意味着绘图仅在绘制面板时完成。如果您需要刷新,请致电repaint()

如果你搞乱了GUI,你应该把它放在EDT线程中,以避免多个线程进行图形操作(因为它们可以干扰)

java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
        //UI operations here
    }
} );

将其交给专用的UI更改线程队列。

答案 1 :(得分:1)

for (int x=100; x<=800; x+=100)
{
    paper.drawLine(x, 0, x, 800); 
}

但你不应该致电panel.getGraphics() - 这迟早会导致呈现错误。网络上有许多资源可以显示如何正确地执行此操作,例如: http://docs.oracle.com/javase/tutorial/uiswing/painting/

答案 2 :(得分:0)

int a = 100;   
for (int i = 0; i < 8; i++) {
    paper.drawLine(a, 0, a, 800);
    a += 100;
}