用Java在主窗口上画线

用Java在主窗口上画线,java,swing,Java,Swing,我试图在主窗口上画一条线,而不创建一个新窗口,因为在我发现的大多数示例中都是这样。我在NetBeans 8.1中创建了一个新项目,添加了新的JPanel,并在设计模式中添加了两个按钮。大概是这样的: public class NewJPanel extends javax.swing.JPanel { /** * Creates new form NewJPanel */ public NewJPanel() { initComponents

我试图在主窗口上画一条线,而不创建一个新窗口,因为在我发现的大多数示例中都是这样。我在NetBeans 8.1中创建了一个新项目,添加了新的JPanel,并在设计模式中添加了两个按钮。大概是这样的:

public class NewJPanel extends javax.swing.JPanel {

    /**
     * Creates new form NewJPanel
     */
    public NewJPanel() {
        initComponents();
    }

    /**
     * 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")
    . . . .
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
    }                                        

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
    }                                        


    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    // End of variables declaration                   
}
我想通过按下按钮M1来画线(10,10100100),并通过按下底部2来清洁它。我非常欣赏最简单的例子。
非常感谢

您可以使用paint方法在JPanel中绘制二维图形,以实现您的功能创建布尔变量drawLine,并将button1设置为true,button2设置为false,如下所示:

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        drawLine = true;
        repaint();
    }

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        drawLine = false;
        repaint();
    }

    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private boolean drawLine = false;
现在替代面板中的绘制方法,并将以下代码添加到显示线,如果drawLine为false,则将其清除:

@Override
    public void paint(Graphics arg0) {
        super.paint(arg0);
        Graphics2D gd = (Graphics2D) arg0;
        if(drawLine){
            gd.setColor(Color.RED);
            gd.drawLine(10, 10, 100, 100);
        }else{
            super.paint(arg0);
        }
    }

通过这种方式,您可以按按钮1画线,然后用按钮2将其清除。

为什么不使用绘制方法来画线?自定义绘制是通过覆盖组件的
paintComponent(…)
方法(而不是paint())来完成的。有关更多信息和工作示例,请阅读上的Swing教程。非常感谢您,Sandeep!这真是最简单的例子!