M
M
Maly2021-05-04 15:57:08
Java
Maly, 2021-05-04 15:57:08

How to display the button color which was last in java?

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

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Date;
import java.util.*;
import java.io. *;
import java.io.Serializable;
import java.io.IOException;
public class The extends JFrame{
  private JButton st1=new JButton("26");
public The(){

super("Plants");
JPanel panel=new JPanel();
panel.add(st1);



panel.add(st18);
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); \\Меняю цвет кнопки

}else {
    ((Component)source).setBackground(Color.red);
 
  }

     try {\\Тут я кинул в color1.txt папу состояние кнопки. Тоест цвет кнопки
            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);
       \\ Тепер нужно чтобы при перезагрузке окна вывелся цвет который был перед закрытием. Тоест если цвет кнопки была красный чтобы вывелся красный. Если цвет кнопки обычная то вывелся обычный цвет.
}
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan, 2021-05-04
Hasanly @azerphoenix

Good afternoon.
If I'm not mistaken, this is the third time you've asked this question.
Generally,

\\ Now it is necessary that when the window is reloaded, the color that was before closing was displayed. Ie if the color of the button was red to display red. If the color of the button is normal, then the normal color is displayed.

You need to:
1) Serialize the required data (for example, the color of the current button) to a file or, for example, save it to the database.
2) Next, when the application starts, read the contents of the file and if the file contains the data you need (for example, the color of a button), then it will be assigned to this button.
Read about serialization and deserialization in Java. And also read how to change button color.
Ready.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question