Java无法使TempListener工作

时间:2015-04-01 16:13:57

标签: java swing class graphics

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中的新值重绘它。我为它写了三节课。其中一个包含accessor,mutators,constructor。其中一个课程当然有主要方法,其中一个课程在上面。但TempListener无法正常工作。你能救我吗?

1 个答案:

答案 0 :(得分:1)

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

建议:

  • 让你的ActionListener更改myCircle对象的状态,你的代码不会这样做。
  • 然后打电话给repaint()
  • 从ActionListener中获取此myCircle.draw(g);,因为它不属于那里。
  • 阅读Swing图形教程:Lesson: Performing Custom Painting