【问题标题】:Java cant make TempListener workJava 不能让 TempListener 工作
【发布时间】:2015-04-01 16:13:56
【问题描述】:
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();





        }

    }
}
}

大家好,我正在尝试制作绘制一个圆圈并使用 JTextField 中的新值重新绘制它的 Java 应用程序。我为它写了三堂课。其中之一是包含访问器、修改器、构造器。其中一个类当然有 main 方法,上面是一个类。但 TempListener 不工作。你能帮帮我吗?

【问题讨论】:

  • 请解释您的问题,就好像我们不知道您要做什么一样。你说“TempListener 不工作”但它应该做什么?您似乎在假设我们已经阅读了您的整个作业并且可以读心。我们不能。
  • 不要在课堂上使用图形字段。仅使用 paintComponent 内部的本地 Graphics 对象。换句话说,去掉你的g 变量,你的TempListener ActionListener 不应该调用g 的任何方法,甚至不应该看到一个Graphics 对象。它应该只改变变量状态并调用重绘。阅读图形教程以了解更多信息。 Lesson: Performing Custom Painting.

标签: java swing class graphics


【解决方案1】:

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

建议:

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

【讨论】:

  • 我复制并粘贴到 Eclipse 比 JCreator 和 ecplipse 更能帮助我说 CirclePanel.ButtonListener.TempListener 类型从未在本地使用。所以我的问题是我的程序找不到临时监听器(我不知道如何以及为什么)你知道吗?
猜你喜欢
  • 1970-01-01
  • 2017-02-18
  • 2014-11-30
  • 2014-04-05
  • 2012-09-23
  • 1970-01-01
  • 1970-01-01
  • 2020-05-24
  • 1970-01-01
相关资源
最近更新 更多