这是一项任务,很多事情(比如扩展 JFrame)都是愚蠢的做事方式,但我必须这样做。
我正在创建一个程序,该程序将“colours.txt”作为输入,其中包含格式中的 20 种颜色
white FFFFFF
yellow FFFF00
将创建一个具有颜色组合框和退出按钮的 GUI 窗口。组合框填充了颜色的单词表示,当单击它们时,GUI 窗口的背景将更改为该颜色,使用十六进制值更改颜色,而不是颜色名称。我必须使用一个集合来完成这个。我正在重新阅读所有这些材料,但我真的迷失了一些领域。使用以下代码,我可以创建一个窗口并填充组合框,如果我愿意,我可以将颜色名称打印到控制台,但我认为可以工作的代码不起作用。这是一个范围问题,我不知道如何设置它以便我可以编写该行
frame.setBackground(Color.decode(jcbColour.getSelectedItem().hex));
或类似的东西。
package cmis242fp;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.util.*;
import javax.swing.*;
public class Cmis242fp extends JFrame {
private JButton jbtExit = new JButton("Exit"); //action button
private static JComboBox jcbColour = new JComboBox(); //drop down of colors
public Cmis242fp() {
JPanel myPanel = new JPanel(new BorderLayout());
myPanel.add(new JLabel("Select a colour:"));
myPanel.add(jcbColour, BorderLayout.CENTER);
myPanel.add(jbtExit, BorderLayout.SOUTH);
myPanel.setBorder(BorderFactory.createEmptyBorder(100, 100, 100, 100));
myPanel.setMinimumSize(new Dimension(300,300));
myPanel.setMaximumSize(new Dimension(700,700));
jcbColour.setMaximumSize(new Dimension(30,30));
jcbColour.setMaximumSize(new Dimension(60,60));
add(myPanel);
jcbColour.addActionListener(new ComboBoxListener());
jbtExit.addActionListener(new ButtonListener());
}
private class ButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
private class ComboBoxListener implements ActionListener {
public void comboAction(Color color) {
frame.setBackground(color);
}
public void actionPerformed(ActionEvent e) {
//comboAction(Color.decode(jcbColour.getSelectedItem());
}
}
public static class Colour implements Comparable<Colour> {
private String name;
private String hex;
public Colour(String name, String hex) {
this.name = name;
this.hex = hex;
}
public String ntoString() {return name;}
public String htoString() {return hex;}
@Override
public int compareTo(Colour colour) {
return this.name.compareTo(colour.name);
}
public String toString(){
return name;
}
public String toHex() {
return hex;
}
}
public static void loadColours(String fileName) {
java.util.List<Colour> coloursList = new ArrayList<Colour>();
Scanner inFile = null;
try {
inFile = new Scanner(new File(fileName));
while (inFile.hasNext()) {
coloursList.add(new Colour(inFile.next(), inFile.next()));
}
}
catch (Exception other) {
System.out.println(other);
}
finally {
if (inFile != null) {
inFile.close();
}
}
for(int x = 0; x < coloursList.size(); x++) {
jcbColour.addItem(coloursList.get(x));
}
}
public static void main(String[] args) {
String filename = "colours.txt";
loadColours(filename);
Cmis242fp frame = new Cmis242fp();
frame.setSize(350,350);
frame.setMinimumSize(new Dimension(300,300));
frame.setMaximumSize(new Dimension(750,750));
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}