[英]It won't draw the line
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Game4 extends JPanel {
public Game4() {
setVisible(true);
}
public void paint(Graphics g) {
Graphics2D twoD = (Graphics2D) g;
boxes(twoD);
}
public void boxes(Graphics2D twoD) {
twoD.drawLine(getWidth() / 3, 0, getWidth() / 3, getHeight());
}
}
For some reason, I can't get this code to draw out.出于某种原因,我无法提取此代码。 I'm not that good with
Graphics2D
so if I could get some help that would be great.我不太擅长
Graphics2D
,所以如果我能得到一些帮助那就太好了。
Start by taking a look at Painting in AWT and Swing and Performing Custom Painting for more details on how painting works in Swing.首先查看Painting in AWT 和 Swing以及Performing Custom Painting以了解有关绘画如何工作的更多详细信息 Swing。
paint
does a lot of really important work, like setting the default color of the Graphics
context based on the components foreground
color, filling the background, setting the clip, etc. paint
做了很多非常重要的工作,比如根据组件foreground
设置Graphics
上下文的默认颜色、填充背景、设置剪辑等。
Unless you're really willing to take over ALL the control, you're best to avoid it.除非你真的愿意接管所有的控制权,否则你最好避免它。 Instead, prefer using
paintComponent
.相反,更喜欢使用
paintComponent
。
You may also need to supply some basic sizing hints for the component and in order to be shown on the screen the component will need to be added to some kind of window (ie JFrame
)您可能还需要为组件提供一些基本的大小调整提示,并且为了在屏幕上显示组件需要添加到某种类型的 window(即
JFrame
)
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
boxes(g2d);
g2d.dispose();
}
protected void boxes(Graphics2D twoD) {
twoD.drawLine(getWidth() / 3, 0, getWidth() / 3, getHeight());
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.