2

I'm trying to make a very simple program with Swing and ACM interactors. It is taken directly from a class handout, but does not function on my computer. When I run it, it functions fine for about half a second, then briefly flashes, reloads, and then all button and text-field functionality is lost. Here's the code:

import acm.program.*;
import java.awt.event.*;
import javax.swing.*;

public class TextFieldExample extends ConsoleProgram {

public void init() {
    nameField = new JTextField(15);
    add(new JLabel("Name: "), SOUTH);
    add(nameField, SOUTH);
    nameField.addActionListener(this);
}

public void actionPerformed(ActionEvent e) {
    if (e.getSource() == nameField) {
        println("Hello, " + nameField.getText());
    }
}

private JTextField nameField;
}

If it helps, I'm using Java SE 1.6 with Eclipse Helios Service Release 2 on a mid-2010 Mac Pro running Mac OSX 10.8.4

4

1 回答 1

1

作为一种解决方法,除了使用 Java 1.5之外,将该字段添加到NORTH. 此外,您可能想要扩展GraphicsProgram.

修改后的 SSCCE:

import acm.program.*;
import java.awt.event.*;
import javax.swing.*;

public class TextFieldExample extends GraphicsProgram {

    @Override
    public void init() {
        nameField = new JTextField(15);
        add(new JLabel("Name: "), NORTH);
        add(nameField, NORTH);
        nameField.addActionListener(this);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == nameField) {
            println("Hello, " + nameField.getText());
        }
    }
    private JTextField nameField;
}
于 2013-07-26T09:29:44.010 回答