gpt4 book ai didi

java - 我如何让 ActionListener 监听按键?

转载 作者:行者123 更新时间:2023-12-01 09:12:08 26 4
gpt4 key购买 nike

我的代码只是显示一种随机颜色,并有一个按钮可以获取新的颜色,但我怎样才能使 ActionListener 也响应按 Enter 呢?

另外,如何使按钮不填充 JFrame 的整个宽度?

这是我的代码:

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

public class RandomColour {

public static JFrame frame;

public static Color[] colours = {Color.RED, Color.YELLOW, Color.ORANGE, Color.BLUE, Color.GREEN, Color.BLACK, Color.MAGENTA, Color.CYAN, Color.PINK,};

public static int random;

public static void main(String[] args) {


random = (int)(Math.random()*(9)+0);

JButton button = new JButton ("New Random Colour");

button.setSize(10, 10);

frame = new JFrame ("Random Colour");
JPanel panel = new JPanel(new GridLayout(6,6,6,6));

button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
frame.getContentPane().setBackground(colours[(int)(Math.random()*(9)+0)]);
}
});


panel.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.setSize(500, 500);
frame.setContentPane(panel);
frame.getContentPane().setBackground(colours[random]);
frame.setLocationRelativeTo(null);
}
}

最佳答案

该按钮已经应该对 Enter 按键使用react,但它需要设置为框架的默认按钮,并且需要具有焦点,因此将以下两行添加到您的代码将按照您的预期工作:

frame.getRootPane().setDefaultButton(button);
button.requestFocus();

更详细的说明如下:

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

public class RandomColour {
public static JFrame frame;

public static Color[] colours = {Color.RED, Color.YELLOW, Color.ORANGE, Color.BLUE, Color.GREEN, Color.BLACK, Color.MAGENTA, Color.CYAN, Color.PINK,};

public static int random;

public static void main(String[] args) {


random = (int)(Math.random()*(9)+0);

JButton button = new JButton ("New Random Colour");

button.setSize(10, 10);

frame = new JFrame ("Random Colour");
frame.setLayout(new GridLayout(3,2));

JPanel panel = new JPanel(new GridLayout(3,2));

button.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {
frame.getContentPane().setBackground(colours[(int)(Math.random()*(9)+0)]);
}
});

panel.add(button);

// The changes are the next two lines
frame.getRootPane().setDefaultButton(button);
button.requestFocus();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.setSize(500, 500);
frame.setContentPane(panel);
frame.getContentPane().setBackground(colours[random]);
frame.setLocationRelativeTo(null);
}
}

Swing 使用布局管理器来为您处理组件的呈现和排列,如果您想要更大的灵 active ,您应该考虑使用 GridBagLayout ( Example here ) 或者通过组合现有的设计更复杂的布局布局管理器(例如默认的 BorderLayoutManager 和 GridLayout)

关于java - 我如何让 ActionListener 监听按键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40853039/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com