用三个按钮编写一个显示窗口的程序。每个按钮都有一个名称,如“红色”,“绿色”和“蓝色”。在这个窗口中,还有一个标签。该标签包含一个图标。此图标必须是CompositeIcon,其中开头为空。每按一次按钮,您都会看到一个带有按钮颜色的方块,例如“按蓝色按钮 - >窗口上出现蓝色方块”。 到目前为止,我有这个。我有他们的颜色名称的三个按钮。我每次按下其中一个按钮都不起作用。我需要做什么?我怎样才能让按钮变成方形的颜色?
代码:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ActionTester{
public static void main(String[] args){
JFrame frame = new JFrame();
final JTextField textField = new JTextField();
JButton RedButton = new JButton("Red");
RedButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SquareIcon red = new SquareIcon(20,Color.RED);
CompositeIcon ci = new CompositeIcon();
ci.addIcon(red);
}
});
JButton GreenButton = new JButton("Green");
GreenButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SquareIcon green = new SquareIcon(20,Color.GREEN);
CompositeIcon ci = new CompositeIcon();
ci.addIcon(green);
}
});
JButton BlueButton = new JButton("Blue");
BlueButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SquareIcon blue = new SquareIcon(20,Color.BLUE);
CompositeIcon ci = new CompositeIcon();
ci.addIcon(blue);
}
});
frame.setLayout(new FlowLayout());
frame.add(RedButton);
frame.add(GreenButton);
frame.add(BlueButton);
frame.add(textField);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
嘿,我不知道如果同样的运动,但对这个一看,最常见的进口打扰:HTTP:/ /stackoverflow.com/questions/19881700/buttons-and-icons-within-a-label-squareicon。这听起来与你的任务非常相似。 – endkugelfang