在另一个组件内绘制组件

时间:2010-05-30 10:50:31

标签: java components paint

我有一个任务是用菜单按钮显示画出的“眼睛”,以改变它们的颜色和背景颜色。接下来动画他们。但是目前我仍然坚持绘画,在我的JFrame中使用sinc我创建了包含带有绘制眼睛和按钮的面板的JPanel。按钮被正确渲染但我的眼睛画布没有显示。我已经尝试将paint更改为paintComponent,设置contentPane的方式不同但仍无法正常工作。

import java.awt.*;
import javax.swing.*;

public class Main extends JFrame {

    public static void main(String[] args) {
        final JFrame frame = new JFrame("Eyes");
        frame.setPreferredSize(new Dimension(600, 450));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel players = new JPanel(new GridLayout(1, 3));
                players.add(new JButton("Eyes color"));
                players.add(new JButton("Eye pupil"));
                players.add(new JButton("Background color"));

        JPanel eyes = new JPanel();
        Eyes e = new Eyes();
        eyes.add(e);
        eyes.setPreferredSize(new Dimension(600, 400));

        JPanel content = new JPanel();
        content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
        frame.setContentPane(content);
        content.add(players);
        content.add(eyes);

//        frame.getContentPane().add(content);
        frame.pack();
    frame.setVisible(true);

    }
}

class Eyes extends JPanel {

    public Eyes(){     
    }

    public void paint(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
        BasicStroke bs = new BasicStroke(3.0f);
        g2d.setBackground(Color.green);
        g2d.setStroke(bs);
        g2d.setColor(Color.yellow);
        g2d.fillOval(50, 150, 200, 200);
        g2d.fillOval( 350, 150, 200, 200);
        g2d.setColor(Color.BLACK);
        g2d.drawOval(49, 149, 201, 201);
        g2d.drawOval(349, 149, 201, 201);
        g2d.fillOval(125, 225, 50, 50);
        g2d.fillOval(425, 225, 50, 50);
    }
}

这是我应该得到的: alt text http://img175.imageshack.us/img175/6420/eyes1.jpg 这就是我所拥有的: alt text http://img132.imageshack.us/img132/827/eyes2i.jpg

当我尝试在JFrame中直接绘制它时,它几乎完美无缺,除了背景没有设置。为什么setBackgroundColor不会以任何方式影响我的绘图?

2 个答案:

答案 0 :(得分:3)

Eyes类已经是一个小组。您不需要此附加面板:JPanel eyes = new JPanel();

像这样:

Eyes eyes = new Eyes();
eyes.setPreferredSize(new Dimension(600, 400));

JPanel content = new JPanel();
content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
frame.setContentPane(content);
content.add(players);
content.add(eyes);

您还可以将其与其他面板配合使用。只需设置e面板的首选大小。

JPanel eyes = new JPanel();
Eyes e = new Eyes();
eyes.add(e);
e.setPreferredSize(new Dimension(600, 400));
eyes.setPreferredSize(new Dimension(600, 400));

答案 1 :(得分:1)

“眼睛”面板中的绘画代码不正确:

 public void paint(Graphics g) { 
        super.paintComponent(g); 

应该是:

 public void paintComponent(Graphics g) { 
        super.paintComponent(g);