Java:GUI需要帮助才能做出正确的条件

时间:2014-11-30 19:04:12

标签: java loops user-interface conditional-statements

我想让线条看起来像下面的图片,我尝试了很多次,这是当前的代码,但它给了我一个不同的外观,所以在我的情况下有什么遗漏

import javax.swing.JFrame;

import java.awt.Graphics;

import javax.swing.JPanel;

public class MainClass extends JPanel {

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        for (int i = 2; i < 10; i++) {
            for (int x = 10; x > 1; x--) {
                g.drawLine(0, 0, getWidth() / i, getHeight() / x);
                g.drawLine(0, 0, getWidth() / x, getHeight() / i);
                break;
            }
        }
    }

    public static void main(String[] args) {
        JFrame myFrame = new JFrame();
        MainClass panel = new MainClass();
        myFrame.add(panel);
        myFrame.setSize(400, 400);
        myFrame.setLocation(100, 100);
        myFrame.setVisible(true);
    }
}

这是我的代码和图片的图片想要的形状:

enter image description here

2 个答案:

答案 0 :(得分:1)

你实际上并不需要一个嵌套循环。在&#34;预期&#34;图像,x和y彼此依赖。随着x的增长,y缩小。只用一个循环试试。

答案 1 :(得分:0)

使用变量来表示行之间的绘画距离,只有一个用于

import javax.swing.JPanel;

public class MainClass extends JPanel {

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);          
       //variable of the begin of point
        int pointIni=0;
        //variable for the distance between lines
        int distance=20;
        //variable for the space between lines
        int cntLines=20;
        for (int i = 0; i < cntLines; i++) 
        {
           g.drawLine(0, 0, pointIni, getHeight()-pointIni);         
           pointIni=pointIni+distance;
        }
    }

    public static void main(String[] args) {
        JFrame myFrame = new JFrame();
        MainClass panel = new MainClass();
        myFrame.add(panel);
        myFrame.setSize(400, 400);
        myFrame.setLocation(100, 100);
        myFrame.setVisible(true);
    }
}