Java绘制三角形并尝试使用其他Swing对象

3
我在使用Netbeans设计GUI(是的,我很懒)并手动尝试将三角形绘制到JFrame时遇到了一些问题。Swing组件在未获得焦点时会被“覆盖”。下面附上图片和代码。
GUI的所有自动生成代码均位于initComponents()部分中。而绘图生成位于JFrame Paint方法的覆盖代码中。看起来发生的情况是initComponents代码在绘制之前运行,因为该对象在setVisibile(true)之前创建。一旦调用setVisible(true),paint方法将覆盖initComponents创建的所有生成对象。寻求解决方案,以防止任何内容被覆盖。感谢您提供的任何帮助。
 $/*
  * To change this template, choose Tools | Templates
  * and open the template in the editor.
  */

 /*
  * SimpleClient.java
  *
  * Created on Sep 22, 2011, 11:38:30 AM
  */
 package Assignment3;

 import java.awt.Graphics;

 /**
  *
  * @author Mark
  */
 public class SimpleClient extends javax.swing.JFrame {

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

public void paint(Graphics g) {
    int[] xPoints = {100, 100, 200};
    int[] yPoints = {100, 200, 200};
    g.drawPolygon(xPoints, yPoints, 3);
}

/** 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() {

    jTextField1 = new javax.swing.JTextField();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jTextField1.setText("jTextField1");

    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(103, 103, 103)
            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(238, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap(220, Short.MAX_VALUE)
            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(60, 60, 60))
    );

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

/**
 * @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(SimpleClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(SimpleClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(SimpleClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(SimpleClient.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 SimpleClient().setVisible(true);
        }
    });
}
// Variables declaration - do not modify
private javax.swing.JTextField jTextField1;
// End of variables declaration
}
2个回答

4

不要覆盖顶层容器(JFrame、JDialog 等)的 paint() 方法。

自定义绘制是通过覆盖 JPanel(或 JComponent)的 paintComponent() 方法来完成的。然后将该组件添加到帧的内容面板中。不要忘记还要覆盖组件的 getPreferredSize() 方法,以便布局管理器正常工作。

阅读 自定义绘制 获取更多信息和实际示例。


4

一些快速建议:

  • 不要直接在JFrame中绘制。
  • 相反,在JPanel等JComponent中进行绘制。
  • 重写JPanel的paintComponent方法,而不是paint方法。
  • 作为您的paintComponent方法的第一个方法调用通常调用super.paintComponent(g),以允许您的JPanel执行其日常工作并擦除旧图像。
  • 阅读几篇关于Swing图形的教程,因为对许多人(特别是我),它不是直观的,您将不得不打破一些假设来正确地完成它。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接