与java图形绘画混淆

时间:2013-12-01 14:47:14

标签: java swing netbeans

我非常喜欢java .i试图在jpanel中绘制一条线(使用netbean ide)..我读了一些文章。但问题是它是在没有调用它的情况下绘制thais线。我想通过按钮绘制线条单击..而不是在主窗体上但在面板中..我可以修改此代码 这是我的代码

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package graphic;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;

/**
 *
 * @author nisansala
 */
public class grapix extends javax.swing.JFrame {

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

    @Override
     public void paint(Graphics g) {
     Graphics2D ga = (Graphics2D)g;
     ga.setPaint(Color.red);
     ga.drawLine(200,100,200,300);


  }

    /**
     * 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">                          
    private void initComponents() {

        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("paint");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(153, 153, 153)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(153, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(108, 108, 108)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(149, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        Graphics gg = null;
        // TODO add your handling code here:
//       grap(gg);

    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(grapix.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(grapix.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(grapix.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(grapix.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new grapix().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    // End of variables declaration                   
}

3 个答案:

答案 0 :(得分:2)

以下是一个帮助您的示例:

enter image description here

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Line2D;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 *
 * @author David
 */
public class Test {

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("Frame");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        final LinePanel linePanel = new LinePanel();

        JPanel buttonPanel = new JPanel();
        JButton buttonDrawRandomLine = new JButton("Draw Random Line");

        final Random rand = new Random();
        buttonDrawRandomLine.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Line2D line = new Line2D.Double(rand.nextInt(200), rand.nextInt(200), rand.nextInt(200), rand.nextInt(200));
                linePanel.addLine(line);
            }
        });

        buttonPanel.add(buttonDrawRandomLine);

        frame.add(buttonPanel, BorderLayout.SOUTH);

        frame.add(linePanel, BorderLayout.CENTER);

        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

class LinePanel extends JPanel {

    ArrayList<Line2D> lines = new ArrayList<>();

    public void addLine(Line2D l) {
        lines.add(l);
        repaint();
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        for (Line2D l : lines) {
            g2d.draw(l);
        }

    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(300, 300);
    }
}

1)我不建议通过Netbeans Drag and Drop学习Swing,首先是手工操作,而不是使用拖放技术让你的生活更轻松,一旦你理解了它的运作方式。

2)不要扩展JFrame(对于OOP最佳实践)我们不扩展类,除非我们向他们添加他们尚未支持的功能

3)除非绝对必要,否则不要覆盖paint的{​​{1}},而是使用JFrame JComponent并覆盖JPanel

答案 1 :(得分:0)

问题:您的按钮事件处理程序中没有事件代码。

  1. 尝试在构造函数之前创建一个名为 boolean showLine 的状态变量。
  2. 在构造函数中将其初始化为 false
  3. 点击按钮修改状态变量。

    private void jButton1ActionPerformed(
                    java.awt.event.ActionEvent evt) {                                         
    Graphics gg = null;
    // TODO add your handling code here:
    showLine = (true) ? false : true;
    

    }

  4. 将条件检查添加到绘制方法。

    @覆盖 public void paint(Graphics g){     Graphics2D ga =(Graphics2D)g;

    if (showLine) {
        ga.setPaint(Color.red);
        ga.drawLine(200,100,200,300);
    }
    

    }

答案 2 :(得分:0)

请添加要从按钮侦听器调用的正确方法。还要添加要绘制线条的面板。这似乎是一个可能的重复: -

Drawing a line on a JFrame

相关问题