0
這是我的代碼。當用戶從列表中選擇一種顏色並按下「顯示顏色」按鈕時,「顯示顏色」按鈕的顏色應該按所選顏色改變。我想更改從列表中選擇的「colorButton」的顏色。 (顏色是用戶在列表中添加的)
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class A8 extends JFrame {
JList list;
JTextField inputField;
DefaultListModel model;
// String selected;
A8(){
model = new DefaultListModel();
model.addElement("RED");
list = new JList(model);
JButton addButton = new JButton("ADD");
addButton.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent ae)
{
String str = inputField.getText();
model.addElement(str);
}
}
);
JButton colorButton = new JButton("Show Color");
colorButton.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent ae)
{
String str = list.getSelectedValue().toString();
//JOptionPane.showMessageDialog(null, "It's "+ str);
// JOptionPane.setBackground(color.str);
colorButton.setBackground(Color.str);
}
}
);
inputField=new JTextField();
inputField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
}
);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JPanel inputPanel = new JPanel();
inputPanel.add(addButton);
inputPanel.add(colorButton);
colorButton.setBounds(20,50,100,20);
inputPanel.setLayout(new BoxLayout(inputPanel,BoxLayout.Y_AXIS));
inputField.setLayout(new FlowLayout());
inputField.setBounds(5, 5, 100, 100);
inputField.setPreferredSize(new Dimension(120,20));
JScrollPane scrollPane=new JScrollPane(list);
scrollPane.setPreferredSize(new Dimension(200,200));
Container container = getContentPane();
add(scrollPane);
container.add(inputPanel);
add(inputField);
container.setLayout(new FlowLayout());
//container.setBackground(Color.selected);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(500, 250);
setVisible(true);
}
public static void main(String args[])
{
new A8();
}
}
請建議我在哪裏更新代碼。