如何从类到小程序绘制形状?

时间:2013-12-19 09:30:17

标签: java swing applet draw shapes

总编程初学者在这里,试图在学校假期学习一些Java。一直在制作简单的东西,并开始使用Graphics查看GUI和绘制形状。我大部分都在关注这里发布的教程和大量答案。

我无法将Draw类中的形状绘制到DrawTest小程序中;如下

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

public class DrawTest extends Applet 
{
    Draw circle = new Draw();

public void init()  
    {
Panel mainPanel = new Panel();
mainPanel.setLayout(new GridLayout(0,2)); //a left and right panel

JPanel drawPanel = new JPanel();  //left panel to draw shapes into
drawPanel.setBackground(Color.BLACK);
JLabel headerLabel = new JLabel("Draw shapes from another class");
headerLabel.setForeground(Color.GREEN);
drawPanel.add(headerLabel);

drawPanel.add(circle);
circle.drawing();

JPanel textPanel = new JPanel(); //right panel for text
TextArea output = new TextArea("Circle and oval");
textPanel.add(output);

mainPanel.add(drawPanel);
mainPanel.add(textPanel);
add(mainPanel);
}
}

和Draw类

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

public class Draw extends JPanel 
{

    public void drawing()
    {
    repaint();
    }

    public void paintComponent(Graphics g) 
{
super.paintComponent(g);
g.setColor(Color.BLUE);

// a circle (int x, int y, int width, int height,int startAngle, int arcAngle);

g.fillArc(20,20,50,50,0,360);

//this will draw a oval of width 60 & height 40 at (10,30)
g.setColor(Color.RED);
    g.drawOval(10,30,60,40);        
}
}

提前感谢任何指示。

2 个答案:

答案 0 :(得分:1)

首先,你要混合awt和swing组件。请键入JTextArea和JPanel和JApplet,而不是TextArea,Applet和Panel。你也可以这样做:

JPanel drawPanel = new Draw();

但您的解决方案也应该有效。再次,我认为你的问题是因为混合了awt和swing组件而发生的。

此外,circle.drawing();是不必要的,因为小组在初始化时会调用paintComponent()

答案 1 :(得分:1)

你有这个问题,因为你一起使用swing和awt组件。仅使用摆动组件。

使用JApplet代替Applet

使用JPanel代替Panel

使用JTextArea代替TextArea

还使用JtextArea包裹JSrollPane,并且如dehlen所述,您不需要drawing()方法。

例如,更改下一个init()方法:

public void init() {
    JPanel mainPanel = new JPanel();
    mainPanel.setLayout(new GridLayout(0, 2)); // a left and right panel

    JPanel drawPanel = new JPanel(new BorderLayout());
    drawPanel.setBackground(Color.BLACK);
    JLabel headerLabel = new JLabel("Draw shapes from another class");
    headerLabel.setForeground(Color.GREEN);
    drawPanel.add(headerLabel,BorderLayout.EAST);
    circle.setBackground(Color.BLACK);
    drawPanel.add(circle);

    JPanel textPanel = new JPanel(new BorderLayout()); // right panel for text
    JTextArea output = new JTextArea("Circle and oval");
    textPanel.add(new JScrollPane(output));

    mainPanel.add(drawPanel);
    mainPanel.add(textPanel);
    add(mainPanel);
    setSize(600,200);
}

enter image description here