saving a text file using JFileChooser - jfilechooser

I am writing a small program where are user enters some information into text fields and then has the option to save that information using JFileChooser. I have not been able to figure out how to get it to save. What am I doing wrong? Thank you in advance.
public class Program implements ActionListener{
JMenuItem loadMenuItem, saveMenuItem, quitMenuItem;
JFrame frame;
JPanel mainPanel, inputPanel, listPanel;
JLabel firstNameLabel, lastNameLabel, rentLabel, listLabel;
JTextField firstNameTextField, lastNameTextField, rentTextField;
JButton addButton;
JList list;
DefaultListModel<TenantInfo> listModel;
JScrollPane scrollPane;
public ArrayList<TenantInfo>tenantInfo;
private void saveFile() {
// TODO Auto-generated method stub
JFileChooser jfc = new JFileChooser();
int userSelected = jfc.showSaveDialog(null);
if(userSelected == JFileChooser.APPROVE_OPTION){
try{
FileOutputStream fos = new FileOutputStream(jfc.getSelectedFile());
ObjectOutputStream oos = new ObjectOutputStream(fos);
for(TenantInfo t : tenantInfo){
oos.writeObject(t);
}
oos.writeObject(tenantInfo.get(0));
oos.close();
fos.close();
}catch(Exception ex){
ex.printStackTrace();
}
}

Related

saving arraylists to internal storage

I am writing a program which calculates and shows Installed program's data usage.
I want to save My variables and reload them.
I have checked other questions about this but i didn't find my answer.
I have 5 Arraylists in my code to save these items:
"Application Name","Application Icon","Received Data","Sent Data" and "Total Data".
I get these informations and convert Arraylists to String arrays whith "for loop" and show them with my custom Adapter and a listview.
My problem is that my application force stops when i run it on my phone.
I save some variables with SharedPreferences and save Arraylists into internal storage.
I have also tried to save Arraylists with SharedPreferences and i could save them. but when i want to reload and set them to arraylists, i get error.
Here is my "onCreate" method code:
public class MainActivity extends AppCompatActivity {
private static final String MyPREFERENCES="MyPrefs";
private SharedPreferences myPrefs;
int first;
List<String> list=new ArrayList<>();
List<String> s=new ArrayList<>();
List<String> r=new ArrayList<>();
List<String> t=new ArrayList<>();
List<Drawable> ic=new ArrayList<>();
List<Double> StartRx=new ArrayList<>();
List<Double> StartTx=new ArrayList<>();
private long StartTotal;
private long TotalDataUsage;
private long prevData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView1=(ListView)findViewById(R.id.mainListView1);
registerForContextMenu(listView1);
myPrefs=getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
first=myPrefs.getInt("FirstCall",0);
StartTotal=myPrefs.getLong("StartData",0);
TotalDataUsage=myPrefs.getLong("TotalData",0);
prevData=myPrefs.getLong("prevData",0);
try {
list=(ArrayList<String>) InternalStorage.readObject(this,"NamesList");
r=(ArrayList<String>) InternalStorage.readObject(this,"ReceivedData");
s=(ArrayList<String>) InternalStorage.readObject(this,"SentData");
t=(ArrayList<String>) InternalStorage.readObject(this,"TotalData");
ic=(ArrayList<Drawable>) InternalStorage.readObject(this,"IconsList");
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();***
}
DataUsage();
int l=list.size();
if (l>0) {
String[] Names = new String[l];
String[] DReceived = new String[l];
String[] DSent = new String[l];
String[] DTotal = new String[l];
Drawable[] icons = new Drawable[l];
for (int i = 0; i < l; i++) {
Names[i] = list.get(i);
DReceived[i] = r.get(i);
DSent[i] = s.get(i);
DTotal[i] = t.get(i);
icons[i] = ic.get(i);
}
assert listView1 != null;
listView1.setAdapter(new CustomAdapter(this, Names, DReceived, DSent, DTotal, icons));
}
}
and "onResume" method code is:
protected void onPause() {
super.onPause();
try {
InternalStorage.writeObject(this,"NamesList",list);
InternalStorage.writeObject(this,"ReceivedData",r);
InternalStorage.writeObject(this,"SentData",s);
InternalStorage.writeObject(this,"TotalData",t);
InternalStorage.writeObject(this,"IconsList",ic);
} catch (IOException e) {
e.printStackTrace();
}
SharedPreferences.Editor edit = myPrefs.edit();
edit.putInt("FirstCall", first);
edit.putLong("TotalData",TotalDataUsage);
edit.putLong("StartData", StartTotal);
edit.putLong("prevData", prevData);
edit.commit();
}
and the "InternalStorage" class is:
public final class InternalStorage {
private InternalStorage() {}
public static void writeObject(Context context,String fileName,Object object) throws IOException {
FileOutputStream fos=context.openFileOutput(fileName,Context.MODE_PRIVATE);
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(object);
oos.close();
fos.close();
}
public static Object readObject(Context context,String fileName) throws IOException, ClassNotFoundException {
FileInputStream fis=context.openFileInput(fileName);
ObjectInputStream ois=new ObjectInputStream(fis);
return ois.readObject();
}
}
I didn't get any error from android studio.
I know that the problem is with below codes because when i delete them, it works!
try {
list=(ArrayList<String>) InternalStorage.readObject(this,"NamesList");
r=(ArrayList<String>) InternalStorage.readObject(this,"ReceivedData");
s=(ArrayList<String>) InternalStorage.readObject(this,"SentData");
t=(ArrayList<String>) InternalStorage.readObject(this,"TotalData");
ic=(ArrayList<Drawable>) InternalStorage.readObject(this,"IconsList");
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
and this code:
try {
InternalStorage.writeObject(this,"NamesList",list);
InternalStorage.writeObject(this,"ReceivedData",r);
InternalStorage.writeObject(this,"SentData",s);
InternalStorage.writeObject(this,"TotalData",t);
InternalStorage.writeObject(this,"IconsList",ic);
} catch (IOException e) {
e.printStackTrace();
}
CAN ANYONE HELP ME PLEASE?!!

Implementing a Launcher Framework - disabled Apply button on dialog

I am working on a eclipse plugin and implementing a custom launcher as per the link https://eclipse.org/articles/Article-Launch-Framework/launch.html .
I have implemented a class BrowsersTab which extends AbstractLaunchConfigurationTab and implemented all the methods. The problem is that when I call the updateLaunchConfigurationDialog(); on the selection event , the 'Apply' Button remains disabled.
Code :
public class BrowsersTab extends AbstractLaunchConfigurationTab {
private Button chrome;
private Button firefox;
private Button safari;
private Button ie;
private Button opera;
private Button android;
private Button ios;
#Override
public void createControl(Composite parent) {
Composite comp = new Composite(parent, SWT.NONE);
setControl(comp);
GridLayout topLayout = new GridLayout();
comp.setLayout(topLayout);
Group fGroup = new Group(comp, SWT.NONE);
fGroup.setFont(parent.getFont());
fGroup.setLayout(new GridLayout(2, true));
fGroup.setText(DialogMessages.browserSelection);
chrome = new Button(fGroup, SWT.CHECK);
chrome.setText("Google Chrome");
chrome.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
System.out.println("chrome selected");
updateLaunchConfigurationDialog();
}
public void widgetDefaultSelected(SelectionEvent e) {
// TODO Auto-generated method stub
}
});
Image chromeIcon= getBrowserIcon("chrome-browser-24X24.png");
if(null!=chromeIcon)
chrome.setImage(chromeIcon);
Combo comboDropDown = new Combo(fGroup, SWT.DROP_DOWN | SWT.BORDER);
comboDropDown.setText("Version");
firefox = new Button(fGroup, SWT.CHECK);
firefox.setText("Mozilla Firefox");
Image firefoxIcon= getBrowserIcon("Firefox-icon.png");
if(null!=firefoxIcon)
firefox.setImage(firefoxIcon);
comboDropDown = new Combo(fGroup, SWT.DROP_DOWN | SWT.BORDER);
comboDropDown.setText("Version");
safari = new Button(fGroup, SWT.CHECK);
safari.setText("Apple Safari");
Image safariIcon= getBrowserIcon("Safari-icon.png");
if(null!=safariIcon)
safari.setImage(safariIcon);
comboDropDown = new Combo(fGroup, SWT.DROP_DOWN | SWT.BORDER);
comboDropDown.setText("Version");
ie = new Button(fGroup, SWT.CHECK);
ie.setText("Internet Explorer");
Image ieIcon= getBrowserIcon("Internet-Explorer-icon.png");
if(null!=ieIcon)
ie.setImage(ieIcon);
comboDropDown = new Combo(fGroup, SWT.DROP_DOWN | SWT.BORDER);
comboDropDown.setText("Version");
opera= new Button(fGroup, SWT.CHECK);
opera.setText("Opera");
Image operaIcon= getBrowserIcon("browser-opera-icon.png");
if(null!=operaIcon)
opera.setImage(operaIcon);
comboDropDown = new Combo(fGroup, SWT.DROP_DOWN | SWT.BORDER);
comboDropDown.setText("Version");
android= new Button(fGroup, SWT.CHECK);
android.setText("Android");
Image androidIcon= getBrowserIcon("android-platform-icon.png");
if(null!=androidIcon)
android.setImage(androidIcon);
comboDropDown = new Combo(fGroup, SWT.DROP_DOWN | SWT.BORDER);
comboDropDown.setText("Version");
ios= new Button(fGroup, SWT.CHECK);
ios.setText("Mobile Safari");
Image iosIcon= getBrowserIcon("Apple-grey-icon.png");
if(null!=iosIcon)
ios.setImage(iosIcon);
comboDropDown = new Combo(fGroup, SWT.DROP_DOWN | SWT.BORDER);
comboDropDown.setText("Version");
}
#Override
public String getName() {
return "Browsers";
}
public Image getBrowserIcon(String name){
Image icon=null;
try {
icon = AbstractUIPlugin.imageDescriptorFromPlugin("SuitACore","icons/"+name).createImage();
} catch (Exception e) {
// Swallow it; we'll do without images
}
return icon;
}
public Image getImage() {
Image tab=null;
try {
tab = AbstractUIPlugin.imageDescriptorFromPlugin("SuitACore","icons/browser.png").createImage();
} catch (Exception e) {
// Swallow it; we'll do without images
}
return tab;
}
public void initializeFrom(ILaunchConfiguration configuration) {
try {
List<String> browsersDefaults = new ArrayList<String>();
browsersDefaults.add("chrome");
List<String> browsers =configuration.getAttribute("browsers", browsersDefaults);
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
chrome.setSelection(true);
}
public void performApply(ILaunchConfigurationWorkingCopy configuration) {
List<String> browsers = new ArrayList<String>();
browsers.add("chrome");
configuration.setAttribute("browser",browsers );
}
public void setDefaults(ILaunchConfigurationWorkingCopy arg0) {
}
}
You must call updateLaunchConfigurationDialog() whenever anything changes that might update the Apply button - so all checkboxes and combos.
You must also save everything that changes in the ILaunchConfigurationWorkingCopy in the performApply method. The Apply button state is determined by checking that the working copy is different from the original configuration.

adding JDatepicker in Jframe

I want to develop a Swing desktop application with jlabel, JDateChooser and a submit button.
I am using below code :
public class Homeg {
public static void main(String args[]) {
JFrame frame=new JFrame("date display");
JDatePickerImpl datePicker;
UtilDateModel model = new UtilDateModel();
model.setDate(1990, 8, 24);
model.setSelected(true);
JDatePanelImpl datePanel = new JDatePanelImpl(model,null);
datePicker = new JDatePickerImpl(datePanel, null);
frame.setLayout(new FlowLayout());
JLabel label=new JLabel("Date");
JButton submit=new JButton("SUBMIT");
frame.add(label);
frame.add(datePicker);
frame.add(submit);
frame.setSize(400,400);
frame.setVisible(true);
}
}
And it is giving output having only JDatechooser.
Instead I wanted a output which must have a JLabel, JDatePicker and a submit button. Here it is showing only JDatePicker.
You should always call pack() before making a call to setVisible();
{
...
frame.setSize(400,400);
frame.pack();
frame.setVisible(true);
}
Then to actuall make the date the submit button submit the date use:
JButton submit= new JButton("SUBMIT");
submit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Date date = (Date) datePicker.getModel().getValue();
/* do something with 'date' */
}
});

Null pointer Exception using a PrintWriter

I have that inner class shown under. This is for a client/server and I had nullpointer exception at the "println" from an PrintWriter. I have tried all I know to solve it but, unsuccessfully. Anyone can give me a tip or an idea for what I have to do. Thanks guys!
Here's the FULL CLASS code:
public class ChatClient extends JFrame{
private JTextField textToSend;
private Socket socket;
private PrintWriter writer
private String name;
private JTextArea receivedText;
private Scanner reader;
public ChatCliente(String name){
super("Chat: "+ name);
this.name = name;
Font font = new Font("Serif", Font.PLAIN, 20);
textToSend = new JTextField();
textToSend.setFont(font);
JButton btn = new JButton("Send");
btn.setFont(font);
btn.addActionListener(new Listener());
Container content = new JPanel();
content.setLayout(new BorderLayout());
content.add(BorderLayout.CENTER, textToSend);
content.add(BorderLayout.EAST, btn);
receivedText = new JTextArea();
receivedText.setFont(font);
JScrollPane scroll = new JScrollPane(receivedText);
getContentPane().add(BorderLayout.CENTER, scroll);
getContentPane().add(BorderLayout.SOUTH, content);
configureNetwork();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500,500);
setVisible(true);
}
private void configureNetwork(){
try{
socket = new Socket("127.0.0.1",5000);
writer = new PrintWriter(socket.getOutputStream());
reader = new Scanner(socket.getInputStream());
new Thread(new ServerThread()).start();
}catch (Exception e){}
}
private class Listener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
try{
String s = name;
String t = textToSend.getText();
System.out.println(name+" : "+ textToSend.getText());
writer.println(s+" : "+t);
writer.flush();
textToSend.setText("");
textToSend.requestFocus();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
private class ServerThread implements Runnable{
#Override
public void run() {
String text;
try{
while((text = reader.nextLine()) != null){
receivedText.append(text+"\n");
}
}catch(Exception e){}
}
}
}
'name' is not declared.
Maybe you meant:
String s = "name";
Just some stupid thing that happened to me: do not insert "/" in the name of your file, or it will of course look for an extra folder that probably isn't there.
int number = 1, total = 126;
String path = "some/path/found " + number + "/" + total;
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(path, true)));

Adding numbers to an arraylist from the Jtextfield

I am sure its very simple but this is my first java class. the user enters a number into the input Jtextfield. the Add button is supposed to add that number to the arraylist. I am having trouble figuring out how to do that exactly. Any help you can give me would be awesome
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
public class ArrayExercise extends JFrame
{
private final int WINDOW_WIDTH = 300;
private final int WINDOW_HEIGHT = 300;
private JPanel panel1;
private JPanel panel2;
private JLabel messageLabel;
private JTextField input;
private JTextArea output;
private JButton addButton;
private JButton list;
private JButton rlist;
private JButton clear;
public ArrayExercise()
{
setTitle("Array Exercise");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
panel1();
panel2();
add(panel1, BorderLayout.EAST);
add(panel2, BorderLayout.WEST);
setVisible(true);
input.requestFocus();
}
private void panel1()
{
messageLabel = new JLabel("Input");
input = new JTextField(5);
addButton = new JButton("Add");
list = new JButton("List");
rlist = new JButton("R-List");
clear = new JButton("Clear");
addButton.addActionListener(new ButtonListener());
list.addActionListener(new ButtonListener());
rlist.addActionListener(new ButtonListener());
clear.addActionListener(new ButtonListener());
panel1 = new JPanel();
panel1.setLayout(new GridLayout(6,1));
panel1.add(messageLabel);
panel1.add(input);
panel1.add(addButton);
panel1.add(list);
panel1.add(rlist);
panel1.add(clear);
}
private void panel2()
{
output = new JTextArea(12, 10);
panel2 = new JPanel();
panel2.add(output);
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String in;
int number;
int index = 0;
ArrayList<String> list = new ArrayList<>();
String actionCommand = e.getActionCommand();
if (actionCommand.equals("Add"))
{
index++;
in = addButton.getText();
list.add(addButton.getText());
if (index == 9)
{
input.setEditable(false);
addButton.setEnabled(false);
}
output.setText(in + " added.");
input.setText(null);
input.requestFocus();
}
if (actionCommand.equals("List"))
{
for(int x = 0; x <= list.size(); x++)
{
output.setText((x+1)+ ". " + list.get(x) + "\n");
}
}
}
}
public static void main(String[] args)
{
new ArrayExercise();
}
}
You have ArrayList list which is not adding any string value to that list and you are trying to run that over loop to get you values. If you are not adding anything to list then how can you extract anything out of it.
ArrayList<String> list = new ArrayList<String>();
For each button attach different actionlistener as all buttons are not supposed to act same way.
To add elements in ArrayList use this
list.add(input.getText()); // adding text entered into input textfield.
Make a list
List item
Make a TextField
Make Button Add Listener to button
Get the text from the text field or text area Add to array list
object
Here is all the work you need to do:
ArrayList<String> arrayObject= new ArrayList<String>();
JButton button = new JButton();
JtextField textBox = new JtextField ();
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//inside your action listener:
String add_item_to_array = textBox.getText().trim();
arrayObject.add(add_item_to_array);
}
});