package Graph;
import java.awt.Graphics;
import java.awt.Polygon;
import javax.swing.JFrame;
import javax.swing.JPanel;
下面是我的类,它涵盖了所有其他类,并扩展了JFrame,这是我通过在Netbeans中选择"new> Java Frame"选项创建的。我在一个名为Graph的包中创建了它,这个文件名是GraphFrame.Java.
public class GraphFrame extends javax.swing.JFrame {
public GraphFrame() {
}
下面几行是我的JFrame自动创建代码。
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
下面这几行是我的主方法
public static void main(String args[]) {
/* Create and display the form */
//java.awt.EventQueue.invokeLater(new Runnable() {
//public void run() {
GraphFrame Frame=new GraphFrame();
Frame.setVisible(true);
Frame.setTitle("Functional Dependency");
Frame.setSize(500, 500);
//}
// });
}
这些行是我的DrawGraph类,我在GraphFrame类中创建的。除此之外,它扩展了我的JPanel,我通过拖动JPanel图标从Swing容器(对不起,如果这是错误的方式来添加JPanel)
class DrawGraph extends JPanel{
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawLine(10, 100, 380, 100);
g.drawLine(200, 30, 200, 190);
g.drawLine(380, 100, 370, 90);
g.drawLine(380, 100, 370, 110);
g.drawLine(200, 30, 190, 40);
g.drawLine(200, 30, 210, 40);
g.drawString("X", 360, 80);
g.drawString("Y", 220, 40);
}
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JPanel jPanel1;
// End of variables declaration
}
我的问题是,我编码的图形线没有出现。我在谷歌上搜索了stackoverflow,浏览了我的实验练习,但我似乎找不到解决方案。是的,这可能需要更多的阅读,但说实话,我不太明白哪里出了问题。
问题是您从未将JPanel添加到您创建的框架中。
这应该是你想要的。
public class GraphFrame extends JFrame {
private DrawGraph graph;
public GraphFrame(){
super();
graph = new DrawGraph();
this.add(graph);
}
class DrawGraph extends JPanel{
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawLine(10, 100, 380, 100);
g.drawLine(200, 30, 200, 190);
g.drawLine(380, 100, 370, 90);
g.drawLine(380, 100, 370, 110);
g.drawLine(200, 30, 190, 40);
g.drawLine(200, 30, 210, 40);
g.drawString("X", 360, 80);
g.drawString("Y", 220, 40);
}
}
}
注意这个.add(graph)可以被调用,因为GraphFrame
扩展了JFrame。.add()
方法是JFrame类的一部分,因此可以从GraphFrame
您还应该考虑为DrawGraph类创建一个新文件,因为如果您想向GraphFrame or DrawGraph
添加更多功能,它可能会变得混乱。
现在,当您调用对象Frame
的构造函数时,您正在构建GraphFrame
(顺便说一下,该对象应该是frame
)。然而,在这个构造函数中,您仍然需要"创建"JFrame
——这是在JFrame
类的构造函数中完成的。
调用JFrame
的超级构造函数所要做的就是将以下内容作为GraphFrame
的构造函数的第一行:
super();
另外,正如其他回答者所提到的,为了查看面板,您必须将其添加到JFrame
。因此,在主方法中(或者更好的是在GraphFrame
的构造函数中),添加
DrawGraph panel = new DrawGraph();
this.add(panel);