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无法正常工作。你能帮助我吗?

最佳答案

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

意见建议:


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

08-28 00:39