如何通过按键盘上的左右箭头键来更改背景颜色?(不在钟内,在钟外) [英] How can I change the background color by pressing left and right arrow keys from keyboard? (Not inside the clock,outside the clock)

查看:31
本文介绍了如何通过按键盘上的左右箭头键来更改背景颜色?(不在钟内,在钟外)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Java 编程很陌生,我主要从互联网上找到了这段代码,但对其进行了一些编辑.我认为代码工作正常.它显示当前时间和它的指针正确变化.我想通过使用第二个类来更改背景颜色.

I'm quite new to java programming and I found this code mainly from the internet but edited it a bit. I think the code works fine. It displays the current time and its hands changing correctly. I want to change the background color by using a second class.

import java.awt.BasicStroke;
import java.awt.Color;  
import java.awt.Font;  
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;  
import java.util.Locale;  
import javax.swing.JFrame;  
import javax.swing.JPanel;

public class Clock extends JPanel implements Runnable  {  
 
Thread thread = null;   
  int xcenter = 175;
  int ycenter = 175;
 
 private void drawStructure(Graphics g) { 
      
    Graphics2D g2 = (Graphics2D) g;
    
        g.setFont(new Font("Italic", Font.ITALIC, 25)); 
        g.setColor(Color.LIGHT_GRAY);
        g2.setStroke(new BasicStroke(20));
        g.drawOval(xcenter- 150, ycenter - 150, 300, 300); 
        g.setColor(Color.BLACK);
        g.fillOval(xcenter-150,  ycenter-150,300, 300);
        
        g.setColor(Color.RED);
        g.drawString("9",xcenter- 145,  ycenter + 0);  
        g.drawString("3",xcenter + 135,  ycenter + 0);  
        g.drawString("12",xcenter - 10, ycenter - 130);  
        g.drawString("6", xcenter- 10, ycenter + 145);      
 }  
 public void paint(Graphics g)    {
  
  Graphics2D g2 = (Graphics2D) g;
  drawStructure(g);
  
    LocalDateTime now = LocalDateTime.now();
    
    int xksaniye =  now.getSecond();
    int yksaniye = now.getSecond();
    int xkdakika = now.getMinute();
    int ykdakika = now.getMinute(); 
    int xksaat =   now.getHour();
    int yksaat =   now.getHour();
    
    xksaniye = (int) (Math.cos(now.getSecond() * 3.14f / 30 - 3.14f / 2) * 120 +  xcenter); 
    yksaniye = (int)(Math.sin(now.getSecond() * 3.14f / 30 - 3.14f / 2) * 120 + ycenter);  
    xkdakika = (int)(Math.cos(now.getMinute() * 3.14f / 30 - 3.14f / 2) * 100 +  xcenter);  
    ykdakika = (int)(Math.sin(now.getMinute() * 3.14f / 30 - 3.14f / 2) * 100 + ycenter);  
    xksaat = (int)(Math.cos((now.getHour() * 30 + now.getMinute() / 2) * 3.14f / 180 - 3.14f / 2) * 80 +  xcenter);  
    yksaat = (int)(Math.sin(( now.getHour() * 30 + now.getMinute() / 2) * 3.14f / 180 - 3.14f / 2) * 80 + ycenter); 
 
         g.setColor(Color.magenta); 
         g2.setStroke(new BasicStroke(5));
         g.drawLine(xcenter, ycenter,xksaniye, yksaniye);  
  
         g.setColor(Color.red);
         g2.setStroke(new BasicStroke(5));
         g.drawLine(xcenter, ycenter - 1,xkdakika, ykdakika);  
         g.drawLine(xcenter - 1, ycenter, xkdakika,ykdakika);
  
         g.setColor(Color.green); 
         g2.setStroke(new BasicStroke(5));
         g.drawLine(xcenter, ycenter - 1, xksaat, yksaat);  
         g.drawLine(xcenter - 1, ycenter,xksaat,yksaat);      
 } 
 
 public void start()   {  
  if (thread == null)   {  
   thread = new Thread(this);  
   thread.start();  
   }  
 }  
 
 public void stop()   {  
  thread = null;  
 }  
 public void run()   {  
  while (thread != null) {  
   try  {  
    Thread.sleep(100);  
    }   
   catch (InterruptedException e) {}  
   repaint();  
   }  
  thread = null;  
 }  
 
 public void update(Graphics g){  
  paint(g);  
 } 
 
    public static void main(String[] args){
        
          JFrame f = new JFrame("Analog Saat Pojesi");
          
           f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           f.getContentPane().add(new Clock());
           f.setBounds(0, 0, 370, 400);
           Clock clock = new Clock();  
           f.add(clock); 
           f.setLocationRelativeTo(null);
           f.setVisible(true);
           clock.start();
           Clock saat = new Clock();    
    }
}

你看到的是我的第二节课.

And you see here my second class.

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

public class ChangeColor extends JPanel{
    
    public  ChangeColor(){
        addKeyListener(new DirectionListener());
        setFocusable(true);
        setBackground(Color.yellow);
    }

    private class DirectionListener implements KeyListener{

        @Override
        public void keyPressed(KeyEvent e) {
         
            int keyCode = e.getKeyCode();
            if (keyCode == KeyEvent.VK_LEFT){
                setBackground(Color.red);
            }
            repaint();
        }

        @Override
        public void keyReleased(KeyEvent e) {
            // TODO Auto-generated method stub
        }

        @Override
        public void keyTyped(KeyEvent e) {
            // TODO Auto-generated method stub
        }
    }
}

从现在开始感谢您的回答.正如我所说,我想改变背景,而不是时钟内部的颜色.

Thanks from now on for the answers. As I said I want to change the background, not the color of the inside of the clock.

推荐答案

我想通过使用第二个类来更改背景颜色.

I want to change the background color by using a second class.

这不是 Swing 的工作方式.KeyEvents 仅被分派到具有焦点的组件.

That is not how Swing works. KeyEvents are only dispatched to the component that has focus.

你打算用你的 ChangeColor 类做什么?你不能把它放到框架中,因为它什么都不做.

What do you plan to do with with your ChangeColor class? You can't it it to the frame since it doesn't do anything.

相反,您只需要 DirectionListener 类.它应该是您的 Clock 类的一部分.然后在 Clock 类的构造函数中创建一个 DirectionListener 类的实例,并将其作为 KeyListener 添加到 Clock 类中.

Instead all you need is the DirectionListener class. It should be part of your Clock class. Then in the constructor of your Clock class you create an instance of the DirectionListener class and add it as the KeyListener to the Clock class.

其他问题:

  1. 不要覆盖paint().相反,当使用 Swing 时,您覆盖了paintComponent(...).

  1. Don't override paint(). Instead when using Swing you override paintComponent(...).

不要覆盖 update().去掉那些用 AWT 完成的代码,在使用 Swing 时不是必需的

Don't override update(). Get rid of that code that is something that is done with AWT and is not necessary when using Swing

阅读 Swing 教程中关于自定义绘画 了解更多信息.

Read the section from the Swing tutorial on Custom Painting for more information.

首先进行上述更改以清理绘画逻辑.

First make the above change to clean up the painting logic.

然后您可以执行以下操作以更好地实施 Swing 编码实践:

Then you can do the following to better implement Swing coding practices:

  1. 不要使用线程.Swing 组件的更新应该在事件调度线程 (EDT) 上完成.相反,您应该使用 Swing Timer

不要使用 KeyListener.相反,您应该使用键绑定.

Don't use a KeyListener. Instead you should use Key Bindings.

我建议您将指向 Swing 教程的链接放在手边.我提供了 3 个部分的链接.您的大部分代码似乎都基于旧的 AWT 编码实践.使用 Swing 教程 作为 Swing 的参考.

I suggest you keep a link to the Swing tutorial handy. I have provided links to 3 sections. Most of your code seems to be based on old AWT coding practices. Use the Swing tutorial as your reference for Swing.

此外,您还有用于秒、分和小时值的变量.所以使用它们.不要继续调用该方法.它使您的代码变得混乱,因为人们会想知道您为什么创建变量而从不使用它.

Also, you have variables for each of the second, minute and hour values. So use them. Don't keep invoking the method. It makes your code comfusing as people will wonder why you create the variable and never use it.

事实上,为什么您甚至为上述每种方法都有多个变量.每个值应该只有一个变量.

In fact why do you even have multiple variables for each of the above methods. You should only have a single variable for each value.

作为提示,您可以使用:

As a tip you can use:

    Graphics2D g2 = (Graphics2D) g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

在您的绘画方法开始时.它会让你的圆圈更平滑.

at the start of your painting method. It will paint your circles smoother.

查看:拖动绘制的形状作为实施绘制建议的示例.在该示例中,它向面板添加了一个 MouseListener.你想从一个 KeyListener 开始,但是如何实现这个类的概念是一样的.

Check out: Drag a painted Shape as an example for implementing the painting suggestions. In that example it adds a MouseListener to the panel. You want to start with a KeyListener, but the concept of how to implement the class will be the same.

这篇关于如何通过按键盘上的左右箭头键来更改背景颜色?(不在钟内,在钟外)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆