[英]How do I add a line in Java GUI?
I'm trying to add a line into my program, it runs however displays nothing, how do I fix this? 我正在尝试在程序中添加一行,它运行但没有显示任何内容,我该如何解决?
I've watched tutorials and I've come up with the following code, but it doesn't display anything. 我已经看过教程,并且想出了以下代码,但是没有显示任何内容。 How do I fix this?
我该如何解决?
public void paint(Graphics g)
{
g.drawLine(0, 0, 100, 100);
}
Here is my full program: 这是我的完整程序:
import java.awt.EventQueue;
import java.awt.Graphics;
import javax.swing.JFrame;
public class GuiLine {
private JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GuiLine window = new GuiLine();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public GuiLine() {
initialize();
}
public void paint(Graphics g)
{
g.drawLine(0, 0, 100, 100);
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Your class GuiLine
has the method paint(Graphics g)
, but it will never be called since the class isn't a component (nor is it added to the frame, so it wouldn't be visible). 您的类
GuiLine
具有paint(Graphics g)
,但由于该类不是组件(也不会添加到框架,因此它不会显示),因此永远不会调用它。
You can make the class extend JPanel
and in your initialize method call frame.add(this);
您可以使类扩展
JPanel
并在您的初始化方法中调用frame.add(this);
. 。 Then you can continue reading some more tutorials.
然后,您可以继续阅读更多教程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.