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.
I'm having some problems with my class that I need some help with. The class is supposed to take retrieve a csv.file from the file chooser, and then put the name of the file into a Jlist, but I can't get the JList to print the arraylist that I put the chosen files into. This is the code I've got, so I'd be grateful if you could take a look at it and tell me what I need to change with it in order to get the JList to print the arraylist.
import dao.UserDAO;
import db.DemoDB;
import model.Activity;
import model.DataPoint;
import model.Statistics;
public class LoginGUI1 {
DemoDB DemoDBSingleton = null;
private JTabbedPane tabbedPane = new JTabbedPane();
UserDAO userDao = new UserDAO();
JFrame mainFrame = new JFrame("Välkommen till din app");
JFrame f = new JFrame("User Login");
JLabel l = new JLabel("Användarnamn:");
JLabel l1 = new JLabel("Lösenord:");
JTextField textfieldUsername = new JTextField(10);
JPasswordField textfieldPassword = new JPasswordField(10);
JButton loginButton = new JButton("Logga In");
JFileChooser fc = new JFileChooser();
JMenuBar mb = new JMenuBar();
JList listAct = new JList();
List<Activity> activityList = new ArrayList<Activity>();
List activityList1 = new Vector();
JFrame jf;
JMenu menu;
JMenuItem importMenu, exitMenu;
Activity activity = new Activity();
public LoginGUI1() throws IOException {
DemoDBSingleton = DemoDB.getInstance();
ProgramMainFrame();
}
private void ProgramMainFrame() throws IOException {
mainFrame.setSize(800, 600);
mainFrame.setVisible(true);
mainFrame.setJMenuBar(mb);
mainFrame.getContentPane().setLayout(new BorderLayout());;
tabbedPane.add("Dina Aktiviteter", createViewActPanel());
mainFrame.getContentPane().add(tabbedPane, BorderLayout.CENTER);
tabbedPane.add("Diagram för vald aktivitet", createViewDiagramPanel());
tabbedPane.add("Statistik för vald aktivitet", createViewStatisticsPanel());
tabbedPane.add("Kartbild över vald aktivitet", createViewMapPanel());
JMenuBar mb = new JMenuBar();
menu = new JMenu("Meny");
importMenu = new JMenuItem("Importera aktivitet");
importMenu.addActionListener(importActionListener);
exitMenu = new JMenuItem("Avsluta program");
exitMenu.addActionListener(exitActionListener);
menu.add(importMenu);
menu.add(exitMenu);
mb.add(menu);
mainFrame.setJMenuBar(mb);
/* JPanel listholder = new JPanel();
listholder.setBorder(BorderFactory.createTitledBorder("ListPanel"));
mainFrame.add(listholder);
listholder.setVisible(true);
listholder.setSize(500,400);*/
}
private JPanel createViewActPanel() {
JPanel analogM = new JPanel();
analogM.setBackground(new Color(224, 255, 255));
return analogM;
}
ActionListener importActionListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int returnValue = fc.showOpenDialog(mainFrame);
if(returnValue == JFileChooser.APPROVE_OPTION)
{
File file = fc.getSelectedFile();
if(file != null)
{
String fileName = file.getAbsolutePath();
Activity activity = null;
try {
activity = new Activity();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
activity.csvFileReader(fileName);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
activityList.add(activity);
listAct.setListData(activityList.toArray());
}
}
}
};
public static void main(String[] args) throws IOException {
new LoginGUI();
}
}
There's a lot of context missing, so the best I can do is provide a simple running example which works.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class Test {
public static void main(String args[]) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JList<File> fileList;
private DefaultListModel<File> fileListModel;
public TestPane() {
fileListModel = new DefaultListModel<>();
fileList = new JList(fileListModel);
JButton addButton = new JButton("Add");
addButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showOpenDialog(TestPane.this) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
fileListModel.addElement(file);
}
}
});
setLayout(new BorderLayout());
add(new JScrollPane(fileList));
add(addButton, BorderLayout.SOUTH);
}
}
}
I'd highly recommend having a look at How to use lists to get a better understanding of how the API works
if I enter text in the JTextArea and click the "Save" button, the JTextArea text should write/save into a .txt file. Is my try & catch in the correct place being in the event handler method or should parts of it be in the constructor?
This is my code:
package exercises;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class SimpleNotePadApp extends JFrame implements ActionListener {
JButton button1 = new JButton("Open");
JButton button2 = new JButton("Save");
public SimpleNotePadApp(String title) {
super(title);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(300, 350);
setLayout(null);
JTextArea newItemArea = new JTextArea();
newItemArea.setLocation(3, 3);
newItemArea.setSize(297, 282);
getContentPane().add(newItemArea);
button1.setLocation(30,290);
button1.setSize(120, 25);
getContentPane().add(button1);
button2.setLocation(150,290);
button2.setSize(120, 25);
getContentPane().add(button2);
}
public static void main(String[] args) {
SimpleNotePadApp frame;
frame = new SimpleNotePadApp("Text File GUI");
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button1)
{
try {
PrintWriter out = new PrintWriter(new FileWriter("TestFile.txt"));
newItemArea.getText();
newItemArea.write(out);
out.println(newItemArea);
out.flush();
out.close();
} catch (IOException e1) {
System.err.println("Error occurred");
e1.printStackTrace();
}
}
}
}
Thanks in advance
Your try ... catch is in the correct spot, but the contents should just be:
PrintWriter out = new PrintWriter(new FileWriter("TestFile.txt"));
newItemArea.write(out);
out.close();
Consider using try-with-resources, and the .close() becomes unnecessary:
try ( PrintWriter out = new PrintWriter(new FileWriter("TestFile.txt")) {
newItemArea.write(out);
} catch (IOException e1) {
System.err.println("Error occurred");
e1.printStackTrace();
}
Also, you'll need to attach the ActionListener to the JButton during the construction:
button2.addActionListener(this);
(this is the SimpleNotePadApp instance, which implements ActionListener)
Finally, you'll want:
if(e.getSource() == button2)
... since button2 is your "Save" button (not button1)
When I add JFileChooser and initialize it, then it throws the NullPointerException. Without JFileChooser, the same code runs pretty well every time I compile and run. But when I add JFileChooser then it throws the Exception. Sometimes, it runs successfully and sometimes it doesn't.Exceptionis:
Exception in thread "main" java.lang.NullPointerException
at javax.swing.text.PlainView.getPreferredSpan(PlainView.java:233)
at javax.swing.plaf.basic.BasicTextUI$RootView.getPreferredSpan(BasicTextUI.java:1353)
at javax.swing.plaf.basic.BasicTextUI.getPreferredSize(BasicTextUI.java:921)
at javax.swing.plaf.basic.BasicTextAreaUI.getPreferredSize(BasicTextAreaUI.java:120)
at javax.swing.JComponent.getPreferredSize(JComponent.java:1659)
at javax.swing.JTextArea.getPreferredSize(JTextArea.java:619)
at javax.swing.ScrollPaneLayout.layoutContainer(ScrollPaneLayout.java:791)
at java.awt.Container.layout(Container.java:1508)
at java.awt.Container.doLayout(Container.java:1497)
at java.awt.Container.validateTree(Container.java:1693)
at java.awt.Container.validateTree(Container.java:1702)
at java.awt.Container.validateTree(Container.java:1702)
at java.awt.Container.validateTree(Container.java:1702)
at java.awt.Container.validateTree(Container.java:1702)
at java.awt.Container.validate(Container.java:1628)
at java.awt.Container.validateUnconditionally(Container.java:1665)
at java.awt.Window.show(Window.java:1033)
at java.awt.Component.show(Component.java:1654)
at java.awt.Component.setVisible(Component.java:1606)
at java.awt.Window.setVisible(Window.java:1014)
at notepad.Notepad.<init>(Notepad.java:66)
at notepad.Notepad.main(Notepad.java:144)
My code is:
package notepad;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class Notepad extends JFrame implements ActionListener{
private JTextArea area;
private ImageIcon frameicon;
private JMenu filemenu;
private JMenu editmenu;
private JMenu formatmenu;
private JMenu helpmenu;
private JScrollPane scroll;
private Font font;
private JMenuBar menubar;
private JMenuItem newmenuitem;
private JMenuItem openmenuitem;
private JMenuItem savemenuitem;
private JMenuItem exitmenuitem;
private int msg;
private int returnVal;
private JFileChooser choose;
public Notepad(){
initComponents();
setComponents();
setTitle("Simple Notepad");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocation(500, 100);
setResizable(true);
setSize(600,600);
setJMenuBar(menubar);
menubar.add(filemenu);
menubar.add(editmenu);
menubar.add(formatmenu);
menubar.add(helpmenu);
filemenu.add(newmenuitem);
filemenu.add(openmenuitem);
filemenu.add(savemenuitem);
filemenu.add(exitmenuitem);
add(scroll);
setIconImage(frameicon.getImage());
setVisible(true);
}
public final void initComponents(){
area = new JTextArea();
scroll = new JScrollPane (area, //no need of add textArea when added in JScrollPane
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
menubar = new JMenuBar();
filemenu = new JMenu(" File");
editmenu = new JMenu(" Edit");
formatmenu = new JMenu(" Format");
helpmenu = new JMenu(" Help");
newmenuitem = new JMenuItem(" New");
openmenuitem = new JMenuItem(" Open");
savemenuitem = new JMenuItem(" Save");
exitmenuitem = new JMenuItem(" Exit");
choose = new JFileChooser("E:");
font = new Font("Calibri",Font.PLAIN,26);
frameicon = new ImageIcon(getClass().getResource("/res/setting.png"));
}
public final void setComponents(){
area.setSize(600,600);
area.setBackground(Color.WHITE);
area.setFont(font);
//adding ActionListener
newmenuitem.addActionListener(this);
exitmenuitem.addActionListener(this);
openmenuitem.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e){
//if newmenuitemclicked
if(e.getSource()==newmenuitem) {
if(area.getText()!=""){
msg = JOptionPane.showConfirmDialog(menubar, "DO you want to save changes?");
if(msg == JOptionPane.YES_OPTION){
try {
FileOutputStream file = new FileOutputStream("E:\\newdocument.txt");
String s = area.getText();
byte c[] = s.getBytes();
file.write(c);
area.setText("");
JOptionPane.showMessageDialog(menubar, "File saved as E:\\newdocument.txt");
file.close();
} catch (FileNotFoundException ex) {
} catch (IOException ex) {
}
}
if(msg == JOptionPane.NO_OPTION){
}
}
}
if(e.getSource() == exitmenuitem){
msg = JOptionPane.showConfirmDialog(menubar, "Are you sure you want to exit?");
if(msg == JOptionPane.YES_OPTION)
System.exit(0);
}
if(e.getSource() == openmenuitem){
}
}
public static void main(String[] args) {
Notepad n = new Notepad();
}
}
No relevance to JFileChooser I think. Seems one of your components is not instantiated properly.
at java.awt.Window.setVisible(Window.java:1014)
And you can't call its setVisible(true) method.
Anyway to realize the true cause you should include your code.
Update: since your code is included, you can't use setVisible method in constructor. Use it in init() method.
It's because your object won't get instanced properly before constructor execution ends.
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]);