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

发布于 2024-12-06 01:51:23 字数 4265 浏览 2 评论 0原文

我在使用 Netbeans 设计 GUI 时遇到了一些问题(是的,我很懒:\)并手动尝试在 JFrame 上绘制三角形。 Swing 组件被“覆盖”,直到我按下 Tab 键并将焦点放在对象上。我已附上该问题的图片和代码。

所有自动生成的 GUI 代码都位于代码的 initComponents() 部分。 Triage 的生成位于 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
}

I am having a bit of an issue using Netbeans to design a GUI (Yeah im lazy :\ ) and manually trying to paint a triangle onto the JFrame. The Swing Components are 'covered up' until I press tab and put focus on the objects. Ive attached a picture and code below of the issue.

All of the auto generated code for the GUI is in the initComponents() portion of the code. And the Triage generating is in the override code for the JFrame Paint method.
What it looks like is happening is the initComponents code is run before the paint, since the object is created before setVisibile(true). Once setVisible(true) is called then the paint method paints over all of the generated objects initComponents created. Just looking for a solution so that nothing gets covered up.

Any help would be appreciated.

 $/*
  * 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
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

≈。彩虹 2024-12-13 01:51:23

一些快速建议:

  • 不要直接在 JFrame 中绘制。
  • 而是在 JComponent(例如 JPanel)中进行绘制。
  • 重写 JPanel 的paintComponent 方法,而不是paint 方法。
  • 调用 super.paintComponent(g),通常作为您的paintComponent方法的第一个方法调用,以允许您的JPanel进行内务处理并擦除旧图像。
  • 阅读一些有关 Swing 图形的教程,因为对于我们许多人(尤其是我)来说,它并不直观,您必须打破一些假设才能正确完成它。

Some quick recommendations:

  • Don't draw directly in the JFrame.
  • Draw instead in a JComponent such as a JPanel.
  • Override the paintComponent method of the JPanel, not the paint method.
  • Call super.paintComponent(g), usually as the first method call of your paintComponent method to allow your JPanel to do its housekeeping and to erase old images.
  • Read several tutorials on Swing graphics because for many of us (me especially), it's not intuitive and you'll have to break some assumptions to do it correctly.
反目相谮 2024-12-13 01:51:23

不要重写顶级容器(JFrame、JDialog...)的 Paint() 方法。

自定义绘制是通过重写 JPanel(或 JComponent)的 PaintCompnent() 方法来完成的。然后将该组件添加到框架的内容窗格中。不要忘记覆盖组件的 getPreferredSize() 方法,以便布局管理器能够正常工作。

阅读自定义绘画以获取更多信息和工作示例。

Don't override the paint() method of a Top Level Container (JFrame, JDialog...).

Custom painting is done by override the paintCompnent() method of a JPanel (or JComponent). Then you add the component to the content pane of the frame. Don't forget to also override the getPreferredSize() method of the component so the layout managers will work properly.

Read up on Custom Painting for more information and working examples.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文