Java 无法使 TempListener 工作

标签 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 中的新值重新绘制它。我为此写了三个类(class)。其中之一是包含访问器、修改器、构造器。其中一个类当然有 main 方法,并且其中一个类在上面。但 TempListener 不起作用。你能帮我吗?

最佳答案

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

建议:

  • 让您的 ActionListener 更改 myCircle 对象的状态,您的代码不会执行此操作。
  • 然后让它调用repaint()
  • 将这个 myCircle.draw(g); 从您的 ActionListener 中取出,因为它不属于那里。
  • 阅读 Swing 图形教程:Lesson: Performing Custom Painting

关于Java 无法使 TempListener 工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29395755/

相关文章:

java - 如何重构 Netbeans 生成的 GUI 代码?

java - System.getProperty ("gradle.user.home")返回 null

java - JDialog 位于屏幕中心,而不是 JApplet 所需的中心

java - 我正在寻找一个 switch 语句来根据用户按下的按钮添加不同的页面

Python 类不会执行我的函数

class - 如何从具有相同名称 IsTesting() 的类方法调用内置函数 IsTesting()?

java - Facelet VDL 官方规范在哪里?

java - 使用 Java 8 流的两个 int 数组的笛卡尔积

Java代码需要限制用户输入

c++ - 在函数内访问调用成员函数的对象