【问题标题】:Trying to draw on Jpanel within GUI试图在 GUI 中绘制 Jpanel
【发布时间】:2023-03-24 05:51:01
【问题描述】:

我目前正在做一个练习,我们制作一个欢迎目标标志,所以在顶部它会说欢迎目标,然后会有目标标志,当你点击目标标志时,它会变成蓝色。

如何在JPanel 上画画?我需要画三个不同的圆圈,然后填充它们?我有一个框架TargetLogoUI 和两个面板,一个TargetMessagePanel 和一个TargetLogoPanel

我认为我的消息面板是正确的,只需要做徽标面板。

这是我的三个不同的课程。

目标LogoUI

public class TargetLogoUI extends javax.swing.JFrame {

/**
 * Creates new form TargetLogoUI
 */
public TargetLogoUI() {
    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")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    targetMessagePanel1 = new TargetMessagePanel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,     layout.createSequentialGroup()
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(targetMessagePanel1, javax.swing.GroupLayout.PREFERRED_SIZE,     699, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap())
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addComponent(targetMessagePanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(0, 369, Short.MAX_VALUE))
    );

    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(TargetLogoUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(TargetLogoUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(TargetLogoUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(TargetLogoUI.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 TargetLogoUI().setVisible(true);
        }
    });
}
// Variables declaration - do not modify                     
private TargetMessagePanel targetMessagePanel1;
// End of variables declaration                   
}

目标消息面板

import java.awt.Font;
import javax.swing.JComponent;



public class TargetMessagePanel extends javax.swing.JPanel {





/**
 * Creates new form TargetMessagePanel
 */
public TargetMessagePanel() {

    Font f = new Font("Helvetica", Font.BOLD,72);
    Font JComponent = null;
    setFont(JComponent);
    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")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jPanel1 = new javax.swing.JPanel();
    jTextField1 = new javax.swing.JTextField();

    jPanel1.setToolTipText("Welcome to Target");

    jTextField1.setBackground(new java.awt.Color(204, 204, 204));
    jTextField1.setFont(new java.awt.Font("Lucida Sans", 1, 72)); // NOI18N
    jTextField1.setText("Welcome to Target");
    jTextField1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jTextField1ActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE)
    );

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(0, 0, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    );
}// </editor-fold>                        

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

// Variables declaration - do not modify                     
private javax.swing.JPanel jPanel1;
private javax.swing.JTextField jTextField1;
// End of variables declaration                   
}

TargetLogoPanel

public class TargetLogoPanel extends javax.swing.JPanel {

/**
 * Creates new form TargetLogoPanel
 */
public TargetLogoPanel() {
    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")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 700, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 400, Short.MAX_VALUE)
    );
}// </editor-fold>                        
// Variables declaration - do not modify                     
// End of variables declaration                   
}

【问题讨论】:

  • 1) 为了尽快获得更好的帮助,请发布MCTaRE(经过测试和可读的最小完整示例)。 2) 不要无故扩展JPanelJFrame。这里唯一改变父类功能的组件是TargetLogoPanel,这是唯一应该扩展的组件。 3) 但是话虽如此,我会将这两组环绘制成两个图像,并将它们用作默认值,并为未装饰的JButton 按下图标。然后什么都不需要扩展,按钮将对键盘和鼠标输入做出反应。

标签: java swing user-interface netbeans


【解决方案1】:

只需要做标志面板。

阅读 Custom Painting 上的 Swing 教程部分。基本上你需要重写 paintComponent() 方法来进行自定义绘画。

我会从画最大的椭圆开始。更改颜色并绘制下一个最小的椭圆形,依此类推。将使用 setForeground(...) 方法设置红/蓝颜色。然后在绘画代码中可以使用getForeground()方法获取颜色。

当您单击面板时,您会更改前景色并在面板上调用 repaint()。

【讨论】:

    【解决方案2】:

    您必须覆盖 paintComponent(Graphics g) 方法才能在 JPanel 上绘图。

    注意:您可以使用以下代码更改圆的位置和大小:

    new Ellipse2D.Double(xcoord, ycoord, width, height)
    

    示例代码如下:

    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.event.MouseAdapter;
    import java.awt.geom.Ellipse2D;
    import java.awt.event.MouseEvent;
    import javax.swing.JPanel;
    

    final MyCustomJPanel panel = new MyCustomJPanel();
    panel.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            panel.setTarget(true);
            panel.repaint();
        }
    });
    

    class MyCustomJPanel extends JPanel {
        private boolean isTarget;
    
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
    
            Color c = null;
            if (isTarget) {
                c = Color.BLUE;
            } else {
                c = Color.RED;
            }
    
            g2.setColor(c);
            g2.fill(new Ellipse2D.Double(50, 50, 150, 150));
    
            g2.setColor(Color.WHITE);
            g2.fill(new Ellipse2D.Double(75, 75, 100, 100));
    
            g2.setColor(c);
            g2.fill(new Ellipse2D.Double(100, 100, 50, 50));
        }
    
        public boolean isTarget() {
            return isTarget;
        }
    
        public void setTarget(boolean isTarget) {
            this.isTarget = isTarget;
        }
    
    }
    

    【讨论】:

    • I'm currently doing an exercise - 他的功课做得很好。这个答案真的应该得到 -1 的答案,因为它不会覆盖面板的 getPreferredSize() 方法。所有 Swing 组件都应该确定自己的首选大小,以便布局管理器可以使用它们。尝试将面板添加到框架的北部。 Custom Painting 上的 Swing 教程在他们使用的示例中解释了所有这些。
    • 我没有将面板添加到框架的北部。默认情况下,只有JTextField 被添加到 NORTH,JPanel 被添加到 CENTER。抱歉,我没听懂。
    • 再看看代码。根据 OP 消息面板工作正常。在这里,我只为徽标部分提供解决方案。如果你愿意,我可以删除消息部分。
    • 我知道您默认将组件添加到 CENTER。尝试将组件添加到 SOUTH,看看会发生什么? Here I am giving solution for logo part only. If you want then I can remove message part. - 这就是我的观点。您正在做 OP 的工作,但您做错了,因此 OP 不会学习进行自定义绘画的正确方法。这就是为什么您应该将 OP 参考教程并让他自己学习(或犯错误)的原因。
    • frame.setSize(250, 275); 不要那样做,也不要传播不良做法。它对任何人都没有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-17
    • 1970-01-01
    • 2022-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-23
    相关资源
    最近更新 更多