Java JCheckBox ActionListener - java

I have a program that is a list of notes that can be added by the user. Every note is loaded through a for loop and given a JCheckBox on runtime from the notes.txt. How do I add an actionlistener for my JCheckBoxes when they are only instance based and not permanent code?
(e.g. they don't have their own variable names?)
I need to update notes.txt with a 0 or a 1 based on if the JCheckBox is checked or not. Here is my code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class SideNotes {
public static JPanel panel = new JPanel();
private static JButton add = new JButton("Add note");
JCheckBox[] notes;
public SideNotes() {
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(add);
loadNotes();
add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
addNote();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
}
public void addNote() throws IOException {
String note = JOptionPane.showInputDialog("Enter note: ", null);
JCheckBox jcb = new JCheckBox(note, false);
panel.add(jcb);
panel.revalidate();
panel.repaint();
File file = new File("notes.txt");
FileWriter writer = new FileWriter(file, true);
BufferedWriter brw = new BufferedWriter(writer);
brw.write(note);
brw.newLine();
brw.close();
}
private void loadNotes() {
File file = new File("notes.txt");
if (file.exists()) {
try {
FileInputStream fs = new FileInputStream(file);
BufferedReader br = new BufferedReader(
new InputStreamReader(fs));
BufferedReader reader = new BufferedReader(new FileReader(
"notes.txt"));
int lines = 0;
while (reader.readLine() != null)
lines++;
reader.close();
notes = new JCheckBox[lines];
for (int i = 0; i < notes.length; i++) {
String note = br.readLine();
int checked = note.charAt(note.length() - 1);
System.out.println(checked);
if (checked == 49) {
note = note.substring(0, note.length() - 1);
notes[i] = new JCheckBox(note, true);
} else {
note = note.substring(0, note.length() - 1);
notes[i] = new JCheckBox(note, false);
}
panel.add(notes[i]);
panel.revalidate();
panel.repaint();
}
br.close();
} catch (Exception e1) {
}
} else {
System.out.println("File does not exist");
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(200, 400);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(add);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
new SideNotes();
}
}

Create a generic ActionListener outside the loop where you create the checkboxes:
ActionListener al = new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
JCheckBox checkbox = (JCheckBox)e.getSource();
// do something with the checkbox
}
}
Then after you create the checkbox you add the ActionListener to the checkbox
notes[i].addActionListener(al);
panel.add(notes[i]);

Related

How can I make six buttons in Java inside one JFrame according to the instructions?

One button will make new file in the source, the second button will write what is in the text field on my JFrame inside that file, third button will do the exact opposite (write from that file to the text field), fourth button will delete text from the file, but not the file as a whole, fifth button will close the project window and the sixth one will delete the file. I need also that the layout around buttons needs to be colored and I would like if the project will tell me if the file was created/deleted too. I hope you can help me with that. I'm trying this all day but something still doesn't work. If I make some progress, I will comment here.
Edit:
For now I have this, but it doesn't show anything:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class project2 {
public static void main(String[] args) {
JFrame window = new JFrame("New window");
JButton button = new JButton ("Create");
JButton writeto = new JButton ("Write to file");
JButton close = new JButton ("Close");
JButton delete = new JButton ("Delete file");
JTextField field = new JTextField();
JLabel text = new JLabel("Testing");
JButton writefrom = new JButton("Write from file");
JButton deletetext = new JButton("Delete");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(550,450);
window.setVisible(true);
}
}
I did it somehow. I think I just didn't know how to make the buttons to appear, but after I found some functional parts of code on the internet, I did what I wanted. I think I was too rushed so I asked here, but hopefully that's okay. It would be good to make this project to take less rows, so more answers will be appreciated, but I'm already happy with the functionality.
Anyways here's my code for the six buttons:
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class project {
public static void main(String[] args) {
JFrame window = new JFrame("New window");
JButton button = new JButton ("Create");
button.setBounds(80,20,100,30);
JButton writeto = new JButton ("Write to file");
writeto.setBounds(80,80,100,30);
JButton close = new JButton ("Close");
close.setBounds(80,140,100,30);
JButton delete = new JButton ("Delete file");
delete.setBounds(80,200,100,30);
JTextField field = new JTextField();
field.setBounds(80,380,100,30);
JLabel text = new JLabel("Testing");
text.setBounds(110,440,100,30);
JButton writefrom = new JButton("Write from file");
writefrom.setBounds(80,260,120,30);
JPanel panel = new JPanel();
panel.setBounds(75,15,110,40);
JButton deletetext = new JButton("Delete");
deletetext.setBounds(80,320,100,30);
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
File file = new File("file.txt");
try {
if (file.createNewFile()) {
text.setText("Created");
}
else {
text.setText("Not created");
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
writeto.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
try {
FileWriter writeto = new FileWriter("file.txt");
writeto.write(field.getText());
writeto.close();
field.setText("");
text.setText("Task successful");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
text.setText("Task unsuccessful");
}
}
});
close.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
delete.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
File delete = new File("file.txt");
if (delete.delete()) {
text.setText("Deleted");
}
else {
text.setText("Not deleted");
}
}
});
writefrom.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
File writefrom = new File("file.txt");
try {
Scanner scanner = new Scanner(writefrom);
while (scanner.hasNextLine()) {
String data = scanner.nextLine();
field.setText(data);
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
panel.setBackground(Color.GREEN);
deletetext.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
try {
FileWriter deletetext = new FileWriter("file.txt");
deletetext.write("");
deletetext.close();
field.setText("");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
text.setText("Task unsuccessful");
}
}
});
window.add(button);
window.add(writeto);
window.add(close);
window.add(delete);
window.add(field);
window.add(text);
window.add(writefrom);
window.add(panel);
window.setLayout(null);
window.add(deletetext);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(300,600);
window.setVisible(true);
}
}
Below is my rewrite of your application. Note the following:
You should almost always use a layout manager (rather than setting the layout to null and calling method setBounds). In the below code I use BoxLayout.
After you read or writer a file, you should close it. In the below code I use try-with-resources to ensure that the file is closed.
Rather than using anonymous, inner classes to implement the ActionListeners, I use method references.
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Project2 {
private static final String FILE_NAME = "file.txt";
private JLabel text;
private JTextField field;
private void addComponentToPanel(Component cmpt, JPanel panel) {
panel.add(cmpt);
panel.add(Box.createRigidArea(new Dimension(0, 10)));
}
private void close(ActionEvent event) {
System.exit(0);
}
private void createAndDisplayGui() {
JFrame window = new JFrame("New Window");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.add(createPanel(), BorderLayout.CENTER);
window.pack();
window.setLocationByPlatform(true);
window.setVisible(true);
}
private JButton createButton(String text,
int mnemonic,
String tooltip,
Dimension prefSize,
ActionListener listener) {
JButton button = new JButton(text);
button.setAlignmentX(Component.CENTER_ALIGNMENT);
if (prefSize != null) {
button.setMaximumSize(prefSize);
}
if (mnemonic > 0) {
button.setMnemonic(mnemonic);
}
if (tooltip != null && !tooltip.isEmpty()) {
button.setToolTipText(tooltip);
}
button.addActionListener(listener);
return button;
}
private void createFile(ActionEvent event) {
File file = new File(FILE_NAME);
try {
if (file.createNewFile()) {
text.setText("Created");
}
else {
text.setText("Not created");
}
}
catch (IOException e1) {
e1.printStackTrace();
}
}
private JPanel createPanel() {
JPanel panel = new JPanel();
BoxLayout layout = new BoxLayout(panel, BoxLayout.PAGE_AXIS);
panel.setLayout(layout);
panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
JButton widest = createButton("Write from file",
KeyEvent.VK_F,
"Display file contents.",
null,
this::writeFrom);
Dimension dim = widest.getPreferredSize();
addComponentToPanel(createButton("Create",
KeyEvent.VK_R,
"Create file.",
dim,
this::createFile),
panel);
addComponentToPanel(createButton("Write to file",
KeyEvent.VK_T,
"Write entered text to file.",
dim,
this::writeTo),
panel);
addComponentToPanel(createButton("Close",
KeyEvent.VK_C,
"Close application.",
dim,
this::close),
panel);
addComponentToPanel(createButton("Delete file",
KeyEvent.VK_E,
"Delete the file.",
dim,
this::delete),
panel);
addComponentToPanel(widest, panel);
addComponentToPanel(createButton("Delete",
KeyEvent.VK_D,
"Delete file contents.",
dim,
this::deleteText),
panel);
field = new JTextField();
addComponentToPanel(field, panel);
text = new JLabel("Testing");
text.setAlignmentX(Component.CENTER_ALIGNMENT);
addComponentToPanel(text, panel);
return panel;
}
private void delete(ActionEvent event) {
File delete = new File(FILE_NAME);
if (delete.delete()) {
text.setText("Deleted");
}
else {
text.setText("Not deleted");
}
}
private void deleteText(ActionEvent event) {
try (FileWriter deletetext = new FileWriter(FILE_NAME)) {
deletetext.write("");
deletetext.close();
field.setText("");
}
catch (IOException e1) {
e1.printStackTrace();
text.setText("Task unsuccessful");
}
}
private void writeFrom(ActionEvent event) {
File writefrom = new File(FILE_NAME);
try (Scanner scanner = new Scanner(writefrom)) {
while (scanner.hasNextLine()) {
String data = scanner.nextLine();
field.setText(data);
}
}
catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
private void writeTo(ActionEvent event) {
try (FileWriter writeto = new FileWriter(FILE_NAME)) {
writeto.write(field.getText());
writeto.close();
field.setText("");
text.setText("Task successful");
}
catch (IOException e1) {
e1.printStackTrace();
text.setText("Task unsuccessful");
}
}
public static void main(String[] args) {
Project2 proj2 = new Project2();
EventQueue.invokeLater(() -> proj2.createAndDisplayGui());
}
}
This is how the GUI looks when I run the above code.

Java: Reading an array of a directory to display the images contained in the directory to be able to go forwards and backwards through the array

Hello and thanks for your assistance in advance.
My goal is to load a directory called resource to create an array. After doing that the program should use a "Next" and "Previous" button to cycle both forwards and backwards through the array by using a counter. Cycling through the array should display the appropriate picture (without knowing what the picture is, just the order that it is in the array).
My code this far:
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.BoxLayout;
import javax.swing.JTextField;
import java.io.IOException;
import javax.swing.ImageIcon;
import java.io.*;
import java.util.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.awt.*;
import java.awt.event.*;
public class viewer extends JFrame implements ActionListener
{
int counter = 0; //Initial counter value
int maxItems = 0; // Set it equal to the length of the array
int minItems = 0; //Minimum items for previous button
JPanel botPanel = null;
JPanel midPanel = null;
JLabel midLabel = null;
ImageIcon image;
String[] picture = new String [1000];
public viewer()
{
setTitle ("Roberts Viewer");
setSize (1000, 1000);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Allow the X button to close the program and not just the frame
JPanel midPanel = new JPanel ();
JPanel botPanel = new JPanel ();
midLabel = new JLabel();
JButton prv = new JButton("Previous"); botPanel.add(prv); prv.addActionListener(this);
JButton nxt = new JButton("Next"); botPanel.add(nxt); nxt.addActionListener(this);
JButton quitButton = new JButton ("Quit Program"); botPanel.add(quitButton); quitButton.addActionListener(this);
add(midPanel, BorderLayout.CENTER);
add(botPanel, BorderLayout.SOUTH);
File dir = new File ("resource");
File[] picture = dir.listFiles();
for (int maxItems = 0;maxItems < picture.length; maxItems++);
midPanel.add(midLabel);
setVisible(true);
}
public static void main(String[] args)
{
viewer v = new viewer();
}
public void actionPerformed (ActionEvent e)
{
String action = e.getActionCommand();
if (action.equals("Quit Program"))
{
System.exit(0);
}
if(action.equals("Next"))
{
if (counter < 0){counter = 0;}
if (counter> maxItems) {counter = 0;}
String pictureString = String.format("resource/%s", picture[counter]);
System.out.printf("Retrieving[%s]\n",pictureString);
try
{
image = new ImageIcon(getClass().getClassLoader().getResource(pictureString));
}
catch (Exception xu)
{
System.out.println("Woops");
}
midLabel.setIcon(image);
counter++;
}
if(action.equals("Previous"))
{
if (counter < 0) {counter = maxItems;}
if (counter < minItems) {counter = maxItems;}
String pictureString = String.format("resource/%s",picture[counter]);
System.out.printf("Retrieving[%s]\n", pictureString);
try
{
image = new ImageIcon(getClass().getClassLoader().getResource(pictureString));
}
catch (Exception xu)
{
System.out.println("Woops");
}
midLabel.setIcon(image);
counter--;
}
}
}
The problem was solved. I had some bugs but here is the fixed code.
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.BoxLayout;
import javax.swing.JTextField;
import java.io.IOException;
import javax.swing.ImageIcon;
import java.io.*;
import java.util.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.awt.*;
import java.awt.event.*;
public class viewer extends JFrame implements ActionListener
{
int counter = 0; //Initial counter value
int maxItems = 0; // Set it equal to the length of the array
int minItems = 0; //Minimum items for previous button
JPanel botPanel = null;
JPanel midPanel = null;
JLabel midLabel = null;
ImageIcon image;
File[] picture;
public viewer()
{
setTitle ("Roberts Viewer");
setSize (500, 500);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel midPanel = new JPanel ();
JPanel botPanel = new JPanel ();
midLabel = new JLabel();
JButton prv = new JButton("Previous"); botPanel.add(prv); prv.addActionListener(this);
JButton nxt = new JButton("Next"); botPanel.add(nxt); nxt.addActionListener(this);
JButton quitButton = new JButton ("Quit Program"); botPanel.add(quitButton); quitButton.addActionListener(this);
add(midPanel, BorderLayout.CENTER);
add(botPanel, BorderLayout.SOUTH);
File dir = new File ("resource");
picture = dir.listFiles();
midPanel.add(midLabel);
image = new ImageIcon("resource/"+picture [0].getName());
midLabel.setIcon(image);
setVisible(true);
}
public static void main(String[] args)
{
viewer v = new viewer();
}
public void actionPerformed (ActionEvent e)
{
String action = e.getActionCommand();
if (action.equals("Quit Program"))
{
System.exit(0);
}
if(action.equals("Next"))
{
counter++;
if (counter>= picture.length) {counter = 0;}
try
{
image = new ImageIcon("resource/"+picture[counter].getName());
midLabel.setIcon(image);
}
catch (Exception xu)
{
System.out.println("Woops");
}
System.out.printf("Exit next: " + counter + "\n");
}
if(action.equals("Previous"))
{
counter--;
if (counter < 0) {counter = picture.length-1;}
String.format("resource/%s",picture[counter].getName());
try
{
image = new ImageIcon("resource/"+picture[counter].getName());
midLabel.setIcon(image);
}
catch (Exception xu)
{
System.out.println("Woops");
}
System.out.printf("Exit prev: " + counter + "\n");
}
}
}

Save From buffered reader to JTextArea

I want to make the result of my buffered reader to appear in a text area, but It doesn't work for me.
I want the text area to get the result exactly as the system out print do, it is for more than one line, I tried to set the text area with string s but didn't work, just give me the result of one line.
Here is my Code:
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import java.awt.ScrollPane;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Window extends JFrame {
/**
* Launch the application.
* #throws FileNotFoundException
*/
public static void main(String[] args) {
Window frame = new Window();
frame.setTitle("SWMA Extractor");
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setBounds(50, 50, 665, 550);
//frame.setLocation(500, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.getContentPane().setLayout(null);
}
/**
* Create the frame.
*/
public Window() {
setResizable(false);
JPanel contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel path = new JLabel("File Location");
path.setHorizontalAlignment(SwingConstants.CENTER);
path.setBounds(20, 11, 74, 23);
contentPane.add(path);
final JTextField location = new JTextField();
location.setBounds(104, 12, 306, 20);
contentPane.add(location);
location.setColumns(10);
final JTextArea textArea = new JTextArea();
ScrollPane scrollPane = new ScrollPane();
scrollPane.setBounds(20, 80, 605, 430);
contentPane.add(scrollPane);
scrollPane.add(textArea);
JButton btn = new JButton("Get Info.");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
File output = null;
try {
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String s;
int lineNumber = 1;
while((s = br.readLine()) != null) {
if (s.contains("System")) {
System.out.println(s);
String nextLine = br.readLine();
System.out.println(nextLine);
String nextLine1 = br.readLine();
System.out.println(nextLine1);
String nextLine2 = br.readLine();
System.out.println(nextLine2);
String nextLine3 = br.readLine();
System.out.println(nextLine3);
System.out.println();
}
}
lineNumber++;
} catch (IOException e2) {
e2.printStackTrace();
}
}
});
btn.setBounds(433, 11, 192, 23);
contentPane.add(btn);
JButton clr = new JButton("Clear");
clr.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String getLocation = location.getText();
String s;
try {
textArea.setText("");
location.setText("");
} catch (Exception e1) {
}
}
});
clr.setBounds(20, 45, 605, 23);
contentPane.add(clr);
}
}
I see you say you tried setting the text, but the setText method actually replaces the whole current text with the new one:
JTextComponent #1669:
((AbstractDocument)doc).replace(0, doc.getLength(), t,null);
You should use insert or append methods:
Replace
System.out.println(s);
with
textArea.append(s);
Also, check the following question for a better way of doing this:
Opening, Editing and Saving text in JTextArea to .txt file
private void fileRead(){
try{
FileReader read = new FileReader("filepath");
Scanner scan = new Scanner(read);
while(scan.hasNextLine()){
String temp = scan.nextLine() + System.lineSeparator();
storeAllString = storeAllString + temp;
}
}
catch (Exception exception) {
exception.printStackTrace();
}
}
#Hovercraft's suggestion is very good. If you don't want to process the file in any way, you could directly read it into the JTextArea:
try {
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
textArea.read(br, "Stream description");
} catch (IOException e2) {
e2.printStackTrace();
}

Why can't I retrieve my buttons when I run my program?

So, my program is a user adding buttons during runtime. When he/she clicks on the 'save' button the program is saved to a file. But when I run it again, the buttons are gone. I tried to serialize my buttons using XMLEncoder and XMLDecoder, but when I ran my program, it didn't save anything, it started all over again. How would I serialize this correctly so that when I start my program, the buttons are there? Any help would be appreciated.
Here is a snippet of my code:
public class saveButton
{
//JFrame and JPanels have been declared earlier
class ClickListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
str = JOptionPane.showInputDialog("What is the name of the new button?");
JButton b = new JButton(str);
frame.add(b);
try
{
XMLEncoder encdr = new XMLEncoder(new BufferedOutputStream(new FileOutputStream("file.ser")));
encdr.writeObject(new JButton(str));
encdr.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
ActionListener addButtonClicked = new ClickListener();
b.addActionListener(addButtonClicked);
class ClickListenerTwo implements ActionListener
{
public void actionPerformed(ActionEvent f)
{
try
{
XMLDecoder d = new XMLDecoder(new BufferedInputStream(new FileInputStream("file.ser")));
Object result = d.readObject();
d.close();
}
catch (IOException decoder)
{
decoder.printStackTrace();
}
}
}
Once you decode the object, you need to cast the object appropriately and then add the component to the container.
This is pretty basic example which generates a random number of buttons on a panel each time you click the Random button. When you click Save, the panel is saved to disk and when you click Load, it loads the panel from disk and reapplies it the container
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private RandomButtonPane pane;
public TestPane() {
setLayout(new BorderLayout());
JPanel actions = new JPanel();
JButton random = new JButton("Random");
JButton save = new JButton("Save");
JButton load = new JButton("Load");
actions.add(random);
actions.add(save);
actions.add(load);
add(actions, BorderLayout.SOUTH);
random.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (pane != null) {
remove(pane);
}
pane = new RandomButtonPane();
pane.randomise();
add(pane);
Window window = SwingUtilities.windowForComponent(TestPane.this);
window.pack();
window.setLocationRelativeTo(null);
}
});
save.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (pane != null) {
try (OutputStream os = new FileOutputStream(new File("Save.dat"))) {
try (XMLEncoder encoder = new XMLEncoder(os)) {
encoder.writeObject(pane);
remove(pane);
pane = null;
}
} catch (IOException exp) {
exp.printStackTrace();
}
}
}
});
load.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (pane != null) {
remove(pane);
pane = null;
}
try (InputStream is = new FileInputStream(new File("Save.dat"))) {
try (XMLDecoder decoder = new XMLDecoder(is)) {
Object value = decoder.readObject();
if (value instanceof RandomButtonPane) {
pane = (RandomButtonPane)value;
pane.revalidate();
add(pane);
}
}
} catch (IOException exp) {
exp.printStackTrace();
}
Window window = SwingUtilities.windowForComponent(TestPane.this);
window.pack();
window.setLocationRelativeTo(null);
}
});
}
}
public static class RandomButtonPane extends JPanel {
public RandomButtonPane() {
setLayout(new GridBagLayout());
}
public void randomise() {
int count = ((int) (Math.random() * 100)) + 1;
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
for (int index = 0; index < count; index++) {
if (index % 10 == 0) {
gbc.gridx = 0;
gbc.gridy++;
}
add(new JButton(Integer.toString(index)), gbc);
gbc.gridx++;
}
}
}
}

Making my ERROR message in GUI disappear

I have this simple GUI that ask for a string and then write it to a text file but if no input is given the JLabel shows an error message and i want that error message to stay for 5 seconds
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.*;
import javax.swing.JFrame;
import net.miginfocom.swing.MigLayout;
public class Q1 extends JFrame {
private JLabel lblString, lblMessage;
private JTextField txtString;
private JButton btnStore;
private JPanel thePanel;
public static void main(String[] args) {
new Q1();
}// End of main
public Q1() {
super("Store your text");
this.setSize(600, 100);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
thePanel = new JPanel(new MigLayout());
lblString = new JLabel("Enter Your Text :");
txtString = new JTextField(50);
btnStore = new JButton("Store");
// Listener for Store Button
ListenerForButton lForButton = new ListenerForButton();
btnStore.addActionListener(lForButton);
lblMessage = new JLabel();
thePanel.add(lblString);
thePanel.add(txtString, "wrap");
thePanel.add(btnStore, "skip,split2");
thePanel.add(lblMessage, "gapleft 200");
this.add(thePanel);
this.setResizable(false);
this.setVisible(true);
}// End of constructor
// Listener implement
public class ListenerForButton implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnStore) {
if (txtString.getText().equals("")) {
lblMessage.setText("ERROR-NO Text is given !");
lblMessage.setForeground(Color.red);
} else {
try {
String str = txtString.getText();
File file = new File("appending-Text-File.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fileWritter = new FileWriter(file.getName(),
true);
BufferedWriter bufferWritter = new BufferedWriter(
fileWritter);
bufferWritter.newLine();// Write a new line
bufferWritter.write(str);
bufferWritter.close();
lblMessage.setText("String is successfully stored !");
txtString.setText("");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}// End actionPerfomred
}
}// End of Class
Try updating your if block as:
if (txtString.getText().equals("")) {
lblMessage.setText("ERROR-NO Text is given !");
lblMessage.setForeground(Color.red);
Thread.currentThread().sleep(5000);
lblMessage.setText("");
}

Categories

Resources