这是我到目前为止所做的:
DrawPanel.java
package drawpaneltest;
import java.awt.Graphics;
import javax.swing.JPanel;
public class DrawPanel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
int width = getWidth();
int height = getHeight();
int d = 0;
while (d < 301) {
g.drawLine(0, d, width, height);
d += 15;
}
}
}
DrawPanelTest.java
package drawpaneltest;
import javax.swing.JFrame;
public class DrawPanelTest {
public static void main(String[] args) {
DrawPanel panel = new DrawPanel();
JFrame application = new JFrame();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
application.add(panel); // add the panel to the frame
application.setSize(250, 250); // set the size of the frame
application.setVisible(true); // make the frame visible
}
}
上面的代码示例目前显示以下内容:
我错过了什么?我应该如何添加曲线和垂直线?
答案 0 :(得分:1)
这是我的方法:
package drawpaneltest;
import java.awt.Graphics;
import javax.swing.JPanel;
public class DrawPanel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
int width = getWidth();
int height = getHeight();
int x1 = 0, y1 = 0,
x2 = 0, y2 = height;
while (y1 < height) {
g.drawLine(x1, y1, x2, y2);
y1+=15; //You should modify this if
x2+=15; //it's not an equal square (like 250x250)
}
}
}
然而在JPanel中,坐标(0,0)从左上角开始, 像往常一样不在左下角。 它在(m×n)方格上仍然表现不佳,你必须做更多的事情。
答案 1 :(得分:0)
您还应该更改to
坐标(d
替换width
):
g.drawLine(0, d, d, height);