Question

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

Était-ce utile?

La solution

As a workaround, in addition to using Java 1.5, add the field to the NORTH. Also, you may want to extend GraphicsProgram.

Modified 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;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top