预订后更改按钮颜色

时间:2016-11-30 16:11:15

标签: java netbeans

在将按钮引用为字符串时尝试更改按钮的颜色时遇到问题?我希望在我的程序中进行预订时更改颜色,因为我正在从文件中读取(在缓冲读取器中)我正在考虑将按钮名称作为字符串传递

有没有办法做到这一点?

while (in.hasNext()){
        seat = in.nextLine();
        in.nextLine();
        in.nextLine();
        in.nextLine();
        in.nextLine();
        seatNum = "btn" + seat;

        seatNum.setBackground(new java.awt.Color(255, 51, 0));

    }

1 个答案:

答案 0 :(得分:0)

您可以使用以下两个功能:

public static void loadButtonAndUpdateColor(String filename) {
        BufferedReader br;
        try {
            br = new BufferedReader(new FileReader(new File(filename)));
            String[] color = br.readLine().split(",");
            int[] vals = new int[3];
            for (int i = 0; i < color.length; i++) {
                vals[i] = Integer.parseInt(color[i]);
            }
            Color c = new Color(vals[0],vals[1],vals[2]);
            btnNewButton.setBackground(c);
            repaint();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == btnNewButton) {
            FileWriter fos;
            try {
                fos = new FileWriter(new File("path to file"));
                Color c = new Color(251,51,0);
                fos.write("" + c.getRed() + "," + c.getGreen() + "," + c.getBlue());
                fos.flush();
                fos.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            loadButtonAndUpdateColor("path to file");
        }
    }

第一个是静态的,可以放在任何你想要的地方 第二个需要在你的JFrame类中。我将按钮命名为btnNewButton ...