试图在GUI中绘制Jpanel

时间:2014-03-21 22:41:24

标签: java swing user-interface netbeans

enter image description here

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

我如何在JPanel上画画?我需要绘制三个不同的圆圈,并填充它们?我有一个框架TargetLogoUI和两个面板,TargetMessagePanelTargetLogoPanel

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

以下是我的三个不同的课程。

TargetLogoUI

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                   
}

TargetMessagePanel

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                   
}

2 个答案:

答案 0 :(得分:1)

  

只需要做徽标面板。

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

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

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

答案 1 :(得分:0)

您必须覆盖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;
    }

}