繁体   English   中英

GUI JFrame背景颜色更改

[英]GUI JFrame background color change

我已经重新审查了这篇文章。 我已经能够上传文本文件,创建GUI,并使用从文本文件标记的JRadioButton填充GUI ...

现在,当选择了JRadioButton时,我无法获得更改颜色的背景! 我知道它与ActionListener有关,但是如何解决呢? 需要从十六进制颜色代码实现颜色。

public class FP extends JFrame implements ActionListener {
TreeMap<String, String> buttonMap = new TreeMap <>();


// Constructor
@SuppressWarnings("empty-statement")
public FP() throws IOException {

JPanel panel = new JPanel();
add(panel, BorderLayout.CENTER);
panel.setBorder(new TitledBorder("Pick a Radio Button!"));

JRadioButton[] btnArray = new JRadioButton[20];
ButtonGroup btnGroup = new ButtonGroup();
BufferedReader reader;

    reader = new BufferedReader(new FileReader("src/colors.txt"));
    String currentLine = reader.readLine();

    while (currentLine != null) {        
        String[] pair = currentLine.split("\\s+");              
        buttonMap.put(pair[0],pair[1]);
        currentLine = reader.readLine(); 
    }  

//check retrieving values from the buttonMap
for(Map.Entry<String,String> entry : buttonMap.entrySet()) {
  String key = entry.getKey();
  String value = entry.getValue(); 

}
for (int i = 0; i<20; i++){
     for(Map.Entry<String, String> entry : buttonMap.entrySet()){
        JRadioButton rb = new JRadioButton(entry.getKey() + " " +     entry.getValue());            
        panel.add(rb);
        btnGroup.add(rb);
        rb.addActionListener(this);
}       
}
 //private final JRadioButton btnMale = new JRadioButton("Male")
 Collection bMapIt = buttonMap.entrySet();
 Iterator it = bMapIt.iterator();
 System.out.println("Colors and codes");
 while(it.hasNext())     
 System.out.println(it.next());





}   

@Override
public void actionPerformed(ActionEvent e) {

setBackground(Color.decode(buttonMap.get(e)));  
}

public static void main(String[] args) throws IOException {
FP frame = new FP();
frame.setVisible(true);
frame.setSize(350, 240);
frame.setTitle("Final Project");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

}
}
for(Map.Entry<String, String> entry : buttonMap.entrySet()){
        for (int i = 0; i<1; i++){     
            btnArray[i] = new JRadioButton(entry.getKey() + " " +     entry.getValue());            
            panel.add(btnArray[i]);
            btnGroup.add(btnArray[i]);

            btnArray[i].addActionListener((ActionEvent e) -> {
                String btnColor = buttonMap.get(((JRadioButton)    e.getSource()).getText());
                String hexColor = entry.getValue();
                System.out.println(hexColor);
                panel.setBackground(Color.decode("#"+hexColor));               
            });
        }           
    }

这加上班级。

 @Override
public void actionPerformed(ActionEvent e) {}

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM