我目前正在学习java,我理解除图形之外的概念,作为程序员,这对我来说是全新的。坦白说,它让我不知所措。理论上,我的示例应该在按下按钮时显示一个圆圈。
使用打印方法进行调试,我不断发现 Button 正确调用了所有方法并创建了一个新的 Circle c 对象,但在 newNode().drawCircle() 中,从未调用 repaint() ,因此未绘制新对象。这是为什么?有人可以帮我让这个该死的圆圈出现吗?有些人可能会注意到我使用这个示例来尝试帮助解决问题http://leepoint.net/notes-java/examples/graphics/circles/circles.html http://leepoint.net/notes-java/examples/graphics/circles/circles.html .
这本来是一个网络绘图程序的开始,我认为该程序很容易......除了在创建时显示节点......即圆圈!
这段代码现在可以工作了,所以我希望它可以帮助有类似问题的人,因为我知道这是一个常见的java作业:)
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
///////////////////////////////////////////////////////////////////////
public class NetGrapher
{
public static void main(String[] args){
final JFrame frame = new JFrame ("NetGrapher");
frame.getContentPane().add(new NewNode()); /////delete line
final NewNode newNode = new NewNode();
///// Revision after answer, add, frame.getContentPane().add(newNode); (erase the above frame.getContent)
JPanel buttonPanel = new JPanel();
JButton button = new JButton ("New Node");
button.addActionListener(new ActionListener( ){
public void actionPerformed( ActionEvent e) {
System.out.println( "Button Pressed");
newNode.drawCircle();
}
});
buttonPanel.add(button);
frame.add(buttonPanel, BorderLayout.SOUTH);
frame.setSize(600,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
//////////////////////////////////////////////////////////////////////
class NewNode extends JComponent
{
public ArrayList<Circle> _circles = new ArrayList<Circle>();
public void paintComponent(Graphics g){
g.setColor(Color.WHITE);
g.fillRect(0, 0, 600, 600);
System.out.println( "RePaint");
for ( Circle c : _circles){
System.out.println( "Each C");
g.setColor(Color.BLACK);
c.draw(g);
}
}
public void drawCircle(){
System.out.println( "drawCircle Implemented");
Circle c = new Circle(100, 100, 100, 100);
_circles.add(c);
repaint();
}
}
/////////////////////////////////////////////////////////////////////
class Circle
{
int x, y, z, a;
Circle (int _x, int _y, int _z, int _a){
this.x = _x;
this.y = _y;
this.z = _z;
this.a = _a;
}
public void draw(Graphics g){
System.out.println( "Called In Draw Method");
g.setColor(Color.BLACK);
g.fillOval(x, y, z, a);
}
}