2015-04-01 69 views
0
import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 

public class CirclePanel extends JPanel { 
private JTextField xField, yField, diameterField; 
private JButton Redraw; 
private JLabel xLabel, yLabel, rLabel; 
Circle myCircle = new Circle (150, 150, 30, Color.red, Color.white); 
Graphics g; 
//Paint objects on panel 
public void paintComponent (Graphics page) { 
super.paintComponent(page); 
g = page; 
myCircle.draw(g); 
} 

public CirclePanel(){ 
    xLabel = new JLabel("X= "); 
    yLabel = new JLabel("Y= "); 
    rLabel = new JLabel("R= "); 

    xField = new JTextField(5); 
    xField.addActionListener(new TempListener()); 

    yField = new JTextField(5); 
    yField.addActionListener(new TempListener()); 

    diameterField = new JTextField(5); 
    diameterField.addActionListener(new TempListener()); 

    Redraw = new JButton("Redraw!"); 
    Redraw.addActionListener(new ButtonListener()); 

    add(xLabel); 
    add(xField); 
    add(yLabel); 
    add(yField); 
    add(rLabel); 
    add(diameterField); 
    add(Redraw); 

    setPreferredSize(new Dimension(500, 500)); 
    setBackground(Color.white); 
    } 
    private class ButtonListener implements ActionListener{ 

    public void actionPerformed (ActionEvent event) { 

     //Update page 
     myCircle.draw(g); 
     //repaint panel 
     repaint(); 
     } 
    private class TempListener implements ActionListener 
    { 
     public void actionPerformed(ActionEvent event) 
     { 
      int x, y, newbase, newhei; 

      String text = xField.getText(); 
      String text2 = yField.getText(); 

      x = Integer.parseInt (text); 
      y = Integer.parseInt (text2); 


      myCircle.draw(g); 

      repaint(); 





     } 

    } 
} 
} 

嗨,大家好,我正在做的Java应用程序,绘制一个圆圈,并用JTextField中的新值重新绘制它。我为它写了三堂课。其中之一是包含访问器,增变器,构造函数。其中一个课程具有课程的主要方法,其中一个课程在上面。但TempListener不起作用。你可以帮我吗?Java不能让TempListener工作

+0

请说明您的问题,因为如果我们不知道你想做什么。你说“TempListener不工作”,但它应该做什么?你似乎认为我们已经读完了你的整个任务并且能够阅读头脑。我们不能。 – 2015-04-01 16:15:49

+0

请勿在班级中使用图形字段。仅在paintComponent中使用本地Graphics对象。换句话说,除掉你的'g'变量,你的TempListener ActionListener不应该调用任何关闭g的方法,甚至不应该看到一个Graphics对象。它应该只是改变变量状态并调用repaint。阅读更多的图形教程。 [课程:执行自定义绘画](http://docs.oracle.com/javase/tutorial/uiswing/painting/index.html)。 – 2015-04-01 16:17:05

回答

1

您应该从程序中获取图形字段g。而是使用本地Graphics变量,即在paintComponent方法内调用page的变量,但不要在其他任何地方使用它。

建议:

  • 有你的ActionListener进行更改myCircle对象的状态,你的代码没有做到这一点。
  • 然后拨打电话repaint()
  • 从你的ActionListener中获取此,myCircle.draw(g);,因为它不属于那里。
  • 阅读摇摆图文教程:Lesson: Performing Custom Painting
+0

我复制并粘贴到Eclipse以帮助我比JCreator和ecplipse说CirclePanel.ButtonListener.TempListener类型从来没有在本地使用。所以我的问题结果我的程序不能找到templistener(我不知道如何以及为什么)你有什么想法吗? – Emre 2015-04-01 16:55:41