gpt4 book ai didi

java - 矩形颜色选择器程序

转载 作者:行者123 更新时间:2023-11-30 03:21:34 25 4
gpt4 key购买 nike

我这里遇到两个问题。我正在制作一个简单的程序来测试,基本上当您单击按钮 JColorChooser 时,将会弹出,您可以选择您想要的矩形的颜色。第二个问题是我无法将按钮放置在 BorderLayout.SOUTHBorderLayout.NORTH 或任何地方。这些是我的代码

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

public class GUI extends JPanel {
private Color a = (Color.WHITE);
private Color b = (Color.WHITE);
private final JPanel panel;
private final JButton ab;
private final JButton bb;
private int x = 1;
private int y = 1;

public GUI() {
panel = new JPanel();
panel.setBackground(Color.WHITE);

ab = new JButton("Choose your first Rectangle color");
ab.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
a = JColorChooser.showDialog(null, "Pick a Color", a);
x = 2;
}
});
bb = new JButton("Choose your second Rectangle color");
bb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
b = JColorChooser.showDialog(null, "Pick a Color", b);
y = 2;
}
});
add(ab, BorderLayout.NORTH);
add(panel, BorderLayout.CENTER);
add(bb, BorderLayout.SOUTH);

}

@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
this.setBackground(Color.WHITE);
if (x == 2)
g.setColor(a);
g.fillRect(50, 50, 100, 20);
if (y == 2)
g.setColor(b);
g.fillRect(50, 200, 100, 20);
}
}

最佳答案

And the second problem is i cannot position my buttons at BorderLayout.SOUTH or BorderLayout.NORTH Or anywhere.

JPanel 默认使用 FlowLayout,在添加任何组件之前尝试添加 setLayout(new BorderLayout())

setLayout(new BorderLayout());
add(ab, BorderLayout.NORTH);
add(panel, BorderLayout.CENTER);
add(bb, BorderLayout.SOUTH);

I'm making a simple program to test, basically when you click the button jcolorchooser will pop up and you can choose what color you want your rectangle to be

好吧,我“猜测”一旦你选择了一种颜色,它就不会改变矩形的颜色。

更改颜色后,只需添加对 repaint 的调用即可

ab.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
a = JColorChooser.showDialog(null, "Pick a Color", a);
x = 2;
repaint();
}
}
);
bb = new JButton("Choose your second Rectangle color");
bb.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
b = JColorChooser.showDialog(null, "Pick a Color", b);
y = 2;
repaint();
}
}
);

关于java - 矩形颜色选择器程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31201696/

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