简体   繁体   English

单击按钮时移动卡住

[英]Movement stuck when clicking buttons

Created a Program similar to paint where there is a rectangle whose movement inside the screen can be controlled by "w,a,s,d" keys and its size increased or decreased using the scroller on the mouse.创建了一个类似于绘图的程序,其中有一个矩形,其在屏幕内的移动可以通过“w、a、s、d”键控制,并且可以使用鼠标上的滚动器增加或减小其大小。 There are also several buttons of various colours which when pressed fills the rectangular shape with the respective colours.还有几个不同颜色的按钮,按下时会用各自的颜色填充矩形。 Now the problem is after clicking any colour button the movement is stopped ie.现在的问题是在单击任何颜色按钮后停止移动,即。 the rectangle doesn't move.矩形不动。 You can increase and decrease its size but you can't move with "w,a,s,d" keys.您可以增加和减少它的大小,但不能使用“w,a,s,d”键移动。 Please do help me with that.请帮帮我。

And also as an optional request, I'm also trying to paint with this rectangle ie.而且作为一个可选请求,我也在尝试用这个矩形进行绘画,即。 when I press the space bar I want to fill the colour which is selected at the specified area.当我按下空格键时,我想填充在指定区域选择的颜色。 Now even though I can do that.现在即使我能做到。 The next action I do ie.我做的下一个动作,即。 either pressing "w,a,s,d" keys or the scroller, the colour disappears.按“w、a、s、d”键或滚动条,颜色会消失。 Now I know that the colour or fillRect() has to be saved somehow so that the next action doesn't affect it, but I've tried several ways but it isn't happening.现在我知道颜色或 fillRect() 必须以某种方式保存,以便下一个操作不会影响它,但我尝试了几种方法但它没有发生。 I've commented the code for the painting below.我已经评论了下面这幅画的代码。

My first request is my main request, the second one if you are unable to understand what I mean or don't know the solution just leave it.我的第一个请求是我的主要请求,如果您无法理解我的意思或不知道解决方案,请留下第二个请求。

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

public class Animation extends Frame implements KeyListener,MouseWheelListener,ActionListener {
    int x,y,a,b;
    char choice1;
    int draw=1;
    int n=0;
    int color1,color2,color3;
    Button button1,button2,button3,button4,button5,button6,button7,button8,button9,button10;

    Animation() {
        setSize(1000, 1000);
        setVisible(true);
        x = 500;
        y = 500;
        a = 20;
        b = 50;
        addKeyListener(this);
        addMouseWheelListener(this);

         JFrame frame = new JFrame();

        frame.getContentPane().setLayout(null);

        button1 = new Button("Black");
        button2 = new Button("Blue");
        button3 = new Button("Green");
        button4 = new Button("Orange");
        button5 = new Button("Red");
        button6 = new Button("Yellow");
        button7 = new Button("Gray");
        button8 = new Button("Cyan");
        button9 = new Button("Magenta");
        button10 = new Button("Pink");

        add(button1);add(button2);add(button3);add(button4);add(button5);
        add(button6);add(button7);add(button8);add(button9);add(button10);

        button1.setBounds(50,680,50,20); button2.setBounds(120,680,50,20);
        button3.setBounds(190,680,50,20); button4.setBounds(260,680,50,20);
        button5.setBounds(330,680,50,20); button6.setBounds(400,680,50,20);
        button7.setBounds(470,680,50,20); button8.setBounds(540,680,50,20);
        button9.setBounds(610,680,50,20); button10.setBounds(680,680,50,20);

        button1.addActionListener(this);button2.addActionListener(this);
        button3.addActionListener(this);button4.addActionListener(this);
        button5.addActionListener(this);button6.addActionListener(this);
        button7.addActionListener(this);button8.addActionListener(this);
        button9.addActionListener(this);button10.addActionListener(this);
        addWindowListener(new WindowListener() {
            @Override
            public void windowOpened(WindowEvent e) {
            }

            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }

            @Override
            public void windowClosed(WindowEvent e) {
            }

            @Override
            public void windowIconified(WindowEvent e) {
            }

            @Override
            public void windowDeiconified(WindowEvent e) {
            }

            @Override
            public void windowActivated(WindowEvent e) {
            }

            @Override
            public void windowDeactivated(WindowEvent e) {
            }
        });
    }

    @Override
    public void keyTyped(KeyEvent e) {
    }
    @Override
    public void keyPressed(KeyEvent e) {
    }
    @Override
    public void keyReleased(KeyEvent e) {
        choice1 = e.getKeyChar();
        if (choice1 == 'w') {
            y = y - 10;
        }
        if (choice1 == 's') {
            y = y + 10;
        }
        if (choice1 == 'a') {
            x = x - 10;
        }
        if (choice1 == 'd') {
            x = x + 10;
        }
        if(choice1 == ' '){
            draw=2;
        }
        repaint();
    }

    @Override
    public void mouseWheelMoved(MouseWheelEvent e) {
        double p = e.getPreciseWheelRotation();
        if(p>0){
            a=a+5;
            b=b+5;
        } else{
            a=a-5;
            b=b-5;
        }
        repaint();
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getActionCommand().equals("Black")){
            color1 = 0;
            color2 = 0;
            color3 = 0;
        }
        if(e.getActionCommand().equals("Blue")){
            color1 = 0;
            color2 = 0;
            color3 = 255;
        }
        if(e.getActionCommand().equals("Green")){
            color1 = 0;
            color2 = 255;
            color3 = 0;
        }
        if(e.getActionCommand().equals("Orange")){
            color1 = 255;
            color2 = 165;
            color3 = 0;
        }
        if(e.getActionCommand().equals("Red")){
            color1 = 255;
            color2 = 0;
            color3 = 0;
        }
        if(e.getActionCommand().equals("Yellow")){
            color1 = 255;
            color2 = 255;
            color3 = 0;
        }
        if(e.getActionCommand().equals("Gray")){
            color1 = 169;
            color2 = 169;
            color3 = 169;
       }
        if(e.getActionCommand().equals("Cyan")){
            color1 = 0;
            color2 = 255;
            color3 = 255;
        }
        if(e.getActionCommand().equals("Magenta")){
            color1 = 255;
            color2 = 0;
            color3 = 255;
        }
        if(e.getActionCommand().equals("Pink")){
            color1 = 255;
            color2 = 192;
            color3 = 203;
        }
        repaint();

    }
    public void paint(Graphics g) {
        if(draw==1) {

            g.drawRect(x, y, a, b);
            g.setColor(new Color(color1,color2,color3));
            g.fillRect(x,y,a,b);

        }
//        if(draw==2){
//            fillColor(g);
//            draw=1;
//        }
    }

//    public void fillColor(Graphics g){
//        g.setColor(Color.red);
//        int[] temp1 = new int[50];
//        temp1[n] = x;
//        int[] temp2 = new int[50];
//        temp2[n] = y;
//        int[] temp3 = new int[50];
//        temp3[n] = a;
//        int[] temp4 = new int[50];
//        temp4[n] = b;
//
//
//        n++;
//        for (int i=0;i<n;i++){
//            System.out.println("abcd");
//            g.fillRect(temp1[n],temp2[n],temp3[n],temp4[n]);
//        }
//
//    }

    public static void main(String[] args) {
        Animation animation = new Animation();

    }

}

First of all there are basic design issues:首先是基本的设计问题:

  1. Don't extend Frame.不要扩展框架。 There is no need to extend any class.无需扩展任何 class。

  2. Don't use AWT components in a Swing application.不要在 Swing 应用程序中使用 AWT 组件。 JFrame is Swing. JFrame是 Swing。 "Button" is AWT. “按钮”是 AWT。 For Swing your should be using JButton .对于 Swing 您应该使用JButton

  3. Don't use a null layout for the entire frame.不要对整个框架使用 null 布局。 Keep the default BorderLayout.保留默认的 BorderLayout。 Read the section from the Swing tutorial on How to Use BorderLayout .阅读 Swing 教程中有关如何使用 BorderLayout的部分。

  4. For the buttons you should create a JPanel (which by default uses a FlowLayout) and add your buttons to this panel.对于按钮,您应该创建一个 JPanel(默认情况下使用 FlowLayout)并将您的按钮添加到此面板。

Then you add this panel to your frame using:然后使用以下方法将此面板添加到框架中:

frame.add(buttonPanel, BorderLayout.PAGE_END);
  1. Custom painting is done by extending JPanel and then you override the paintComponent(...) method.自定义绘画是通过扩展JPanel来完成的,然后覆盖paintComponent(...)方法。 So you need to create a DrawingPanel to paint your rectangle.所以你需要创建一个DrawingPanel来绘制你的矩形。 Read the Swing tutorial on Custom Painting for working examples to help you structure your code better.阅读有关自定义绘画的 Swing 教程以获取工作示例,以帮助您更好地构建代码。

Then you add the drawing panel to the frame using:然后使用以下命令将绘图面板添加到框架:

frame.add(drawingPanel, BorderLayout.CENTER):
  1. Don't use a WindowListener to close the frame.不要使用 WindowListener 来关闭框架。

When you create the frame you can set the close property:创建框架时,您可以设置 close 属性:

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  1. Using multiple nested if statements, like you do in the ActionListner is poor design.使用多个嵌套的 if 语句,就像您在 ActionListner 中所做的那样是糟糕的设计。 As you continue to support more colors the code just grows and grows.随着您继续支持更多 colors,代码只会不断增长。 An alternative approach might be:另一种方法可能是:

a) create a HashMap as an instance variable to contain the buttons and colors: a) 创建一个 HashMap 作为实例变量以包含按钮和 colors:

private HashMap<JButton, Color> buttonColors = new HashMap<>();
private Color rectangleColor = Color.BLACK;

b) now when you create each button you can update the hash map: b) 现在,当您创建每个按钮时,您可以更新 hash map:

buttonColors.put(button1, Color.BLACK);

c) now the code in your ActionListener becomes: c) 现在您的 ActionListener 中的代码变为:

JButton button = (JButton)e.getSource();
Color color = buttonColors.get(button);
rectangleColor = color;
repaint();

d) and the code in your paintComponent() method becomes: d) 并且您的 paintComponent() 方法中的代码变为:

//g.setColor(new Color(color1,color2,color3));
g.setColor( rectangleColor );
  1. Don't create your buttons by brute force.不要通过蛮力创建按钮。 Create a method.创建一个方法。

Code to invoke method调用方法的代码

buttonsPanel.add( createButton("Black", Color.BLACK) );
buttonsPanel.add( createButton("Blue", Color.BLUE) );

and the createButton(..) method would look something like:并且createButton(..)方法看起来像:

public JButton (String text, Color color)
{
    JButton button = new JButton( text );
    button.addActionListener(this);
    buttonColors.put(button, color);

    return button;
}

A lot of suggestions here.这里有很多建议。 The code is posted without testing, so understand each concept and make a change one at a time and test to make sure you implement each step correctly.代码在未经测试的情况下发布,因此请了解每个概念并一次更改一个并进行测试以确保您正确实施每个步骤。

Now the problem is after clicking any colour button the movement is stopped ie.现在的问题是在单击任何颜色按钮后停止移动,即。 the rectangle doesn't move.矩形不动。

A KeyEvent is only passed to the component with focus. KeyEvent 仅传递给具有焦点的组件。 When you click on a button the painting panel loses focus and no longer responds to events.当您单击按钮时,绘画面板失去焦点并且不再响应事件。

The better solution is to use Key Bindings .更好的解决方案是使用Key Bindings Key bindings will work even when a component doesn't have focus.即使组件没有焦点,键绑定也会起作用。 See: Motion Using the Keyboard for more information and working examples.有关更多信息和工作示例,请参阅: 使用键盘进行运动

Short answer for the first.第一个的简短回答。 Add:添加:

 button1.setFocusable(false);
    button2.setFocusable(false);
    button3.setFocusable(false);
    button4.setFocusable(false);
    button5.setFocusable(false);
    button6.setFocusable(false);
    button7.setFocusable(false);
    button8.setFocusable(false);
    button9.setFocusable(false);
    button10.setFocusable(false);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 单击不同的按钮时创建类似的对话框 - Create similar Dialog when clicking different buttons 摇摆点击两个按钮 - swing clicking two buttons 单击屏幕时如何暂停圆的运动? - How to pause the movement of the circle upon clicking the screen? 仅限将GridLayout上的移动限制到相邻的网格按钮 - Movement restriction on GridLayout to only adjacent grid buttons Selenium和Java的麻烦单击按钮 - Trouble Clicking Buttons with Selenium and Java 点击按钮 Selenium WebDriver Java - Clicking buttons with Selenium WebDriver Java 单击Android Studio中的图像按钮时,如何在横向屏幕的上部随机放置几个按钮? - How to position a few buttons at random at the upper part of landscape screen when clicking an image button in Android Studio? 反复单击按钮时出现错误。 我该如何解决? - I get an error when clicking the buttons repeatedly. How can I fix it? 单选按钮计数不起作用,单击按钮时自动重定向到第一个活动 - Count of radio buttons not working, redirected to first activity automatically when clicking on button 在JDatePicker的文本字段中用于检测移动/单击的适当侦听器是什么? - What is the appropriate listener to use for detecting movement/clicking in the text field of JDatePicker?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM