Skip to content
Advertisement

How to display the color of a button last clicked in java?

It is necessary that when the application is restarted, the last color that was displayed is displayed.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io. *;

public class The extends JFrame {
    private JButton st1=new JButton("26");

    public The() {
        JPanel panel=new JPanel();
        panel.add(st1);
        st1.addActionListener(new Ac());
        add(panel);
    }

    class Ac implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            Object source = e.getSource();
            if (((Component)source).getBackground().equals(Color.red)){
                ((Component)source).setBackground(null); //the color changing
            } else {
                ((Component)source).setBackground(Color.red);
            }
            try { //Here I threw the state of the button into color1.txt. The color of the button
                FileOutputStream f = new FileOutputStream("color1.txt");
                ObjectOutputStream out = new ObjectOutputStream(f);
                out.writeObject(st1);
                System.out.println("File has been writen");
                out.close();
            } catch (IOException o) {
        }
    }

    public static void main(String[] args) throws IOException {
        The window = new The();
        window.setVisible(true);
        window.setSize(400,600);
        FileInputStream fileInputStream = new FileInputStream("color1.txt");
        ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
    }
}

Now you need to display the color that was before closing when you restart the window. That is, if the color of the button was red to display red. If the color of the button is normal, the normal color is displayed.

Advertisement

Answer

First the code, then the explanations.

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class The extends WindowAdapter implements ActionListener, Runnable {
    private static final String  PATH = "color1.dat";

    private Color  defaultBackground;
    private JButton  st1;
    private JFrame  frame;

    @Override // java.awt.event.ActionListener
    public void actionPerformed(ActionEvent event) {
        Object source = event.getSource();
        if (source == st1) {
            Color col = st1.getBackground();
            if (col == defaultBackground) {
                st1.setBackground(Color.red);
            }
            else {
                st1.setBackground(defaultBackground);
            }
        }
    }

    @Override // java.lang.Runnable
    public void run() {
        createAndDisplayGui();
    }

    @Override // java.awt.event.WindowAdapter
    public void windowClosing(WindowEvent event) {
        Color background = st1.getBackground();
        try (FileOutputStream fos = new FileOutputStream(PATH);
             ObjectOutputStream oos = new ObjectOutputStream(fos)) {
            oos.writeObject(background);
        }
        catch (IOException xIo) {
            throw new RuntimeException("Failed to save button background.", xIo);
        }
    }

    private void createAndDisplayGui() {
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.addWindowListener(this);
        st1 = new JButton("26");
        st1.addActionListener(this);
        defaultBackground = st1.getBackground();
        init();
        JPanel panel = new JPanel();
        panel.add(st1);
        frame.add(panel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private void init() {
        try (FileInputStream fis = new FileInputStream(PATH);
             ObjectInputStream ois = new ObjectInputStream(fis)) {
            Object obj = ois.readObject();
            if (obj instanceof Color) {
                Color bg = (Color) obj;
                st1.setBackground(bg);
            }
        }
        catch (FileNotFoundException xFileNotFound) {
            // Ignore.
        }
        catch (ClassNotFoundException | IOException x) {
            throw new RuntimeException("Failed to read saved background", x);
        }
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new The());
    }
}
  • In method main I explicitly launch the Event Dispatch Thread (EDT). The parameter to method invokeLater is an instance of a class that implements interface java.lang.Runnable (which class The does). Hence method invokeLater will call method run in class The.
  • Method run (in class The) calls method createAndDisplayGui. In this method I build the GUI.
  • Method createAndDisplayGui calls method init. Method init tries to read the file that stores the last background color of st1 (i.e. the JButton). Notice that the code uses try-with-resources and multi-catch. Also note that the first time you run the app, the file may not exist. Hence I ignore FileNotFoundException.
  • You only really want to save the background color of st1 when you exit the app. Hence I added a WindowListener. Method windowClosing is called just before the JFrame is closed.
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement