用三個按鈕編寫一個顯示窗口的程序。每個按鈕都有一個名稱,如「紅色」,「綠色」和「藍色」。在這個窗口中,還有一個標籤。該標籤包含一個圖標。此圖標必須是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