0

私は Java UI と Swing が初めてで、なぜこれが起こっているのか理解できません。

public class ZAsciiMapWindow extends JFrame implements KeyListener, Runnable {

    ...

    // SWING STUFF
    private JTextArea displayArea = null;
    private JTextField typingArea = null;

    public ZAsciiMapWindow(final ZMap map, final ZHuman player) {
        super("ZAsciiMapWindow");
        this.map = map;
        this.player = player;
    }

    ...

    public void show() {
        try {
            UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
        } catch (UnsupportedLookAndFeelException ex) {
            ex.printStackTrace();
        } catch (IllegalAccessException ex) {
            ex.printStackTrace();
        } catch (InstantiationException ex) {
            ex.printStackTrace();
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }
        /* Turn off metal's use of bold fonts */
        UIManager.put("swing.boldMetal", Boolean.FALSE);

        //Schedule a job for event dispatch thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(this);
    }

    private void addComponentsToPane() {

        this.typingArea = new JTextField(20);
        this.typingArea.addKeyListener(this);
        this.typingArea.setFocusTraversalKeysEnabled(false);

        this.displayArea = new JTextArea();
        this.displayArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(this.displayArea);
        scrollPane.setPreferredSize(new Dimension(375, 125));

        getContentPane().add(this.typingArea, BorderLayout.PAGE_START);
        getContentPane().add(scrollPane, BorderLayout.CENTER);
    }

    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private void createAndShowGUI() {
        //Create and set up the window.
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Set up the content pane.
        this.addComponentsToPane();

        //Display the window.
        this.pack();
        this.setVisible(true);
    }

    @Override
    public void run() {
        createAndShowGUI();
    }
}

new ZAsciiMapWindow(x, y).show()次に、から呼び出すとmain()、JFrameが表示されません。createAndShowGUI()そして、デバッグすると、無限に呼び出し続けていることがわかります。

なぜこうなった?前もって感謝します。

4

1 に答える 1

2

javax.swing.SwingUtilities.invokeLater(this);渡された Runnable の run メソッドを呼び出します。あなたのrun方法はcreateAndShowGUI();であり、これはを呼び出し、次に を呼び出すthis.setVisible(true);と仮定します。this.show()javax.swing.SwingUtilities.invokeLater(this);

したがって、この動作はそれほど驚くべきことではありません。

クラスが JFrame を拡張し、KeyListener と Runnable を実装することを避けることから始めます。

たとえば、JFrame を直接拡張するのではなく、クラス内に JFrame を配置することをお勧めします。

于 2013-02-17T11:57:20.887 に答える