3

我正在为我的计算机科学课程开发一个应用程序。任务是编写一个计算器,但不使用JTextFields 或JTextAreas。我想出了一个实现的想法,KeyListener在 appletviewer 中运行良好,JFrame但在 Google Chrome (可能还有其他浏览器)中根本不起作用。

这是我的代码片段。

//- BinaryCalc.java
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;

public class BinaryCalc extends JApplet implements KeyListener {

    private JPanel panel;

    public BinaryCalc() {
        super();

        panel = new JPanel();
        this.add(panel);

        panel.addKeyListener(this);
        panel.requestFocusInWindow();
    }

    @Override
    public void init() {
        JOptionPane.showMessageDialog(this, "applet");
        panel.setFocusable(true);
        panel.requestFocus();
    }

    public void keyPressed(KeyEvent e) {
        JOptionPane.showMessageDialog(this, (char) e.getKeyCode());
    }

    public void keyReleased(KeyEvent e) {}

    public void keyTyped(KeyEvent e) {}

    public JPanel getPanel() { return panel; }

    public static void main(String args[]) {
        JFrame frame = new JFrame("Binary Calculator");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setMinimumSize(new Dimension(320, 240));

        BinaryCalc kalkulator = new BinaryCalc();
        frame.add(kalkulator);

        frame.pack();
        frame.setVisible(true);
        kalkulator.getPanel().requestFocusInWindow();
    }

}

以及包含我的小程序的 HTML 文件。

<!doctype html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <link rel="stylesheet" type="text/css" href="style.css">
    <title>Kalkulator binarny</title>
</head>

<body>
    <div style="text-align: center; border-bottom: 1px solid black">
        <h1>Kalkulator Binarny</h1>
    </div>

    <br/>
    <object style="display: block; margin: auto;" type="application/x-java-applet" width="320" height="240">
    <param name="code" value="BinaryCalc.class" />
    <!--- <param name="archive" value="Liczba.jar" /> -->
        What a terrible failure: applet failed to load!
    </object>   
    <br/>
</body>

</html>

有任何想法吗?

4

2 回答 2

5

我冒昧地将@David 的有用示例转换为使用标签和数字键盘。

更新:这种混合适用于 Ubuntu/OpenJDK,它可以通过Java Web Start进行部署。

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.event.*;
import javax.swing.*;

/**
 * @see https://stackoverflow.com/a/13363349/230513
 */
public class BinaryCalc extends JApplet {

    private static BinaryCalc bc = new BinaryCalc();
    private JLabel label = new JLabel("0000000000");

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.setTitle("BinaryCalc");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                initContainer(frame);
                frame.pack();
                bc.label.setText("");
                frame.setVisible(true);
            }
        });
    }

    // Common initialization for either JApplet or JFrame
    private static void initContainer(Container container) {
        JPanel panel = new JPanel();
        bc.setKeyBindings(panel);
        panel.add(bc.label);
        container.add(panel, BorderLayout.CENTER);
        panel.requestFocusInWindow();
    }

    @Override
    public void init() {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                initContainer(BinaryCalc.this);
            }
        });
    }

    private void setKeyBindings(final JPanel panel) {
        panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
            .put(KeyStroke.getKeyStroke(KeyEvent.VK_0, 0), "0");
        panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
            .put(KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD0, 0), "0");
        panel.getActionMap().put("0", new AbstractAction() {

            @Override
            public void actionPerformed(ActionEvent ae) {
                String tmp = label.getText();
                label.setText(tmp + "0");
            }
        });
        panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
            .put(KeyStroke.getKeyStroke(KeyEvent.VK_1, 0), "1");
        panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
            .put(KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD1, 0), "1");
        panel.getActionMap().put("1", new AbstractAction() {

            @Override
            public void actionPerformed(ActionEvent ae) {
                String tmp = label.getText();
                label.setText(tmp + "1");
            }
        });
    }
}
于 2012-11-13T18:17:32.347 回答
5
  • 使用KeyBindings与不使用KeyListener

  • 不要创建自己JFrameJApplet简单调用getContentPane()小程序实例并在那里添加所有组件。

  • 所有组件都应该在覆盖在块中的JApplet覆盖init()方法中创建SwingUtilities#invokeAndWait(..)

  • JApplets 和Applets 没有main(..)方法(除了测试目的)

  • 使用requestFocusInWindow()代替requestFocus()

我强烈建议您阅读:

这是一个适合我的例子。它只是添加一个不可编辑JTextFieldJPanel,然后添加KeyBindings for KeyEvent.VK_0andKeyEvent.VK_1JPanel. 如果用户键入01,它将显示为 un-edtiable JTextField

在此处输入图像描述

import java.awt.BorderLayout;
import java.awt.event.*;
import java.lang.reflect.InvocationTargetException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;

public class BinaryCalc extends JApplet {

    private JTextField jtf;

    @Override
    public void init() {
        try {
            SwingUtilities.invokeAndWait(new Runnable() {
                @Override
                public void run() {

                    JPanel panel = new JPanel();
                    setKeyBindings(panel);
                    jtf = new JTextField(10);
                    //so we cant edited it without pressing a key
                    jtf.setEditable(false);

                    panel.add(jtf);
                    getContentPane().add(panel, BorderLayout.CENTER);
                    panel.requestFocusInWindow();//incase we lost focus
                }
            });
        } catch (InterruptedException ex) {
            Logger.getLogger(BinaryCalc.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvocationTargetException ex) {
            Logger.getLogger(BinaryCalc.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void setKeyBindings(final JPanel panel) {
        panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_0,0), "0");
        panel.getActionMap().put("0", new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                String tmp = jtf.getText();
                jtf.setText(tmp + "0");
            }
        });
        panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_1,0), "1");
        panel.getActionMap().put("1", new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                String tmp = jtf.getText();
                jtf.setText(tmp + "1");
            }
        });
    }
}
于 2012-11-13T15:16:02.850 回答