Пример #1
0
  public KeyboardViewer() {
    canvas.setMinimumSize(new Dimension(1, 1));
    canvas.setFocusable(true);
    canvas.addFocusListener(
        new FocusListener() {
          @Override
          public void focusLost(FocusEvent e) {
            focus = false;
            FocusManager.get().lostFocus(KeyboardViewer.this);
          }

          @Override
          public void focusGained(FocusEvent e) {
            focus = true;
            FocusManager.get().gainedFocus(KeyboardViewer.this);
          }
        });
    Thread t =
        new Thread() {
          public void run() {
            try {
              canvas.requestFocus();
              while (keepAlive) {
                if (canvas.isDisplayable()) {
                  if (canvas.getWidth() > 0 && canvas.getHeight() > 0) {
                    BufferedImage img = new BufferedImage(canvas.getWidth(), canvas.getHeight(), 2);
                    Graphics2D g2 = (Graphics2D) img.getGraphics();
                    String draw = focus ? "ACTIVE" : "Inactive";
                    g2.setFont(font);
                    g2.setBackground(BACKGROUND_COLOR);
                    g2.setColor(FOREGROUND_COLOR);
                    Rectangle2D bounds = g2.getFontMetrics().getStringBounds(draw, g2);
                    g2.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
                    g2.drawString(
                        draw,
                        (int) (canvas.getWidth() / 2d - bounds.getCenterX()),
                        (int) (canvas.getHeight() / 2d - bounds.getCenterY()));
                    g2.dispose();
                    Graphics2D g = (Graphics2D) canvas.getGraphics();
                    if (g != null) {
                      g.drawImage(img, 0, 0, img.getWidth(), img.getHeight(), null);
                      g.dispose();
                    }
                  }
                }
                Thread.sleep(16L);
              }
            } catch (Exception e) {
              e.printStackTrace();
              try {
                Thread.sleep(16L);
              } catch (InterruptedException e1) {
                e1.printStackTrace();
              }
            }
          }
        };
    t.start();
  }
  private void createFrame() {
    frame = new JFrame(title);
    frame.setSize(dimension);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.setResizable(false);
    frame.setFocusable(true);
    frame.setVisible(true);

    canvas = new Canvas();
    canvas.setPreferredSize(dimension);
    canvas.setMaximumSize(dimension);
    canvas.setMinimumSize(dimension);
    canvas.setFocusable(false);

    frame.add(canvas);
    frame.pack();
  }