Need to make Prev and Next JButton Java - java

Hello everyone I need to make Prev and next Jbutton to read lines from a csv file to JTextField I managed to make Load button but now I am stuck. This is for my homework. So if anyone could help it would be nice :D. This is the question in homework:
The Next and Previous buttons display the next or previous order from the file.
Use the String’s split method. Separate methods are needed for next, previous.
Do not duplicate any significant amount of code. Guideline is 3 lines or less is OK
to duplicate.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.text.*;
public class OrderSystem extends JFrame implements ActionListener
{
private JButton exit, cal, save, clear, load, prev, next;
private JTextField text, text1, text2, text3;
private int counter;
//ArrayList<String> splitLine = new ArrayList<String>();
String[] textLine = new String[3];
public OrderSystem()
{
JFrame myFrame = new JFrame("{Your Name} Item Orders Calculator");
myFrame.setLayout(new BorderLayout(2, 2));
JPanel panel = new JPanel();
panel.setLayout( new GridLayout(0, 2));
panel.add( new JLabel("Item name: ", SwingConstants.RIGHT));
text = new JTextField("", 25);
panel.add( text );
panel.add( new JLabel("Number of: ", SwingConstants.RIGHT));
text1 = new JTextField("", 20);
panel.add( text1 );
panel.add( new JLabel("Cost: ", SwingConstants.RIGHT));
text2 = new JTextField("", 20);
panel.add( text2 );
panel.add( new JLabel("Amount owed: ", SwingConstants.RIGHT));
text3 = new JTextField("", 20);
text3.setEnabled(false);
panel.add( text3 );
add(panel,BorderLayout.CENTER);
JPanel panelS = new JPanel( new FlowLayout(FlowLayout.CENTER, 20,3) );
// Create some buttons to place in the south area
cal = new JButton("Calculate");
save = new JButton("Save");
clear = new JButton("Clear");
exit = new JButton("Exit");
load = new JButton("Load");
prev = new JButton("<prev");
next = new JButton("next>");
exit.addActionListener(this);
clear.addActionListener(this);
cal.addActionListener(this);
save.addActionListener(this);
load.addActionListener(this);
prev.addActionListener(this);
next.addActionListener(this);
panelS.add(cal);
panelS.add(save);
panelS.add(clear);
panelS.add(exit);
panelS.add(load);
panelS.add(prev);
panelS.add(next);
add(panelS, BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == exit)
{
System.exit(0);
}
else if(e.getSource() == cal)
{
double amount = Double.parseDouble(text1.getText()) * Double.parseDouble(text2.getText());
text3.setText(String.format(Locale.ENGLISH, "%.2f", amount));
}
else if(e.getSource() == save)
{
boolean append = true;
try
{
BufferedWriter out = new BufferedWriter(new FileWriter("121Lab1.csv", append));
out.write(String.format("%s,%s,%s,%s", text.getText(), text1.getText(), text2.getText(), text3.getText()));
out.newLine();
out.flush();
out.close();
}
catch (IOException ex)
{
JOptionPane.showMessageDialog(null, "Error");
}
counter++;
}
else if(e.getSource() == clear)
{
text.setText("");
text1.setText("");
text2.setText("");
text3.setText("");
}
else if(e.getSource() == load)
{
try {
String splitLine;
BufferedReader br = new BufferedReader( new FileReader("121Lab1.csv"));
while ((splitLine = br.readLine()) != null)
{
textLine = splitLine.split(",");
text.setText(textLine[0]);
text1.setText(textLine[1]);
text2.setText(textLine[2]);
text3.setText(textLine[3]);
}
}
catch (IOException exp)
{
JOptionPane.showMessageDialog(null, "Error no file found.");
}
}
else if(e.getSource() == prev)
{
//Prev line
}
else if(e.getSource() == next)
{
//Read next line
}
}
public static void main(String[] args)
{
OrderSystem main = new OrderSystem();
main.setTitle("Item Orders Calculator");
main.setSize(450, 150);
main.setLocationRelativeTo(null);
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main.setVisible(true);
}
}

Load the csv data upon clicking the load button. I recommend using OpenCSV for reading the whole csv file in one go. CSVReader's readAll() will give you a list of String array.
else if (e.getSource() == load) {
CSVReader reader = null;
try {
reader = new CSVReader(new FileReader("csv.csv"));
myEntries = reader.readAll();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
}
ptr = 1;
navigate(ptr);
}
myEntries should be instance level
private List<String[]> myEntries;
Define an instance level int variable that will decrement when prev button is pressed otherwise increment when next button is pressed.
private int ptr;
Define a private method that will retrieve data from the myEntries list based on the index that it will receive.
private void navigate(int index){
String[] data = myEntries.get(index);
text.setText(data[0]);
text1.setText(data[1]);
text2.setText(data[2]);
text3.setText(data[3]);
}
In your prev and next button, increment/decrement ptr then happily use the navigate method passing the resultant value.
else if (e.getSource() == prev) {
if(ptr > 1){
ptr--;
navigate(ptr);
}
} else if (e.getSource() == next) {
if(ptr < (myEntries.size()-1)){ //lists are 0 based
ptr++;
navigate(ptr);
}
}

Related

How can I avoid code duplication when creating similar elements in Swing? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I made code for small text editor with swing. I have many similar components that do similar actions. Similar code is duplicated many times. For instance, the code like following is repeated many times for different font sizes:
pkt8 = new JMenuItem("8 pts");
pkt8.addActionListener(this);
fontsize.add(pkt8);
...
if (e.getSource() == pkt8) {
textArea.setFont(new Font("monospaced", Font.PLAIN, 8))
...
How can I change my code to avoid such duplication?
Here is the full code:
package zad6;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.Writer;
import java.nio.file.AccessDeniedException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
import javax.swing.*;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuKeyEvent;
import javax.swing.event.MenuKeyListener;
import javax.swing.event.MenuListener;
public class DrawSwing {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Ramka();
}
});
}
}
class Ramka implements ActionListener {
// kolory 1-blue,2-yellow,3-orange,4-red,5-white,6-black,7-green
JMenuItem c1;
JMenuItem c2;
JMenuItem c3;
JMenuItem c4;
JMenuItem c5;
JMenuItem c6;
JMenuItem c7;
JMenuItem c1f;
JMenuItem c2f;
JMenuItem c3f;
JMenuItem c4f;
JMenuItem c5f;
JMenuItem c6f;
JMenuItem c7f;
JMenuItem pkt8;
JMenuItem pkt10;
JMenuItem pkt12;
JMenuItem pkt14;
JMenuItem pkt16;
JMenuItem pkt18;
JMenuItem pkt20;
JMenuItem pkt22;
JMenuItem pkt24;
JTextArea textArea;
JMenuItem szkola;
JMenuItem praca;
JMenuItem dom;
BufferedReader br;
String line;
FileDialog fd;
static String path;
public Ramka() {
JFrame jf = new JFrame();
jf.setTitle("Prosty edytor - bez tytulu");
jf.pack();
jf.setSize(500, 500);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JMenuBar menuBar = new JMenuBar();
jf.setJMenuBar(menuBar);
textArea = new JTextArea(5, 20);
textArea.setEditable(true);
jf.add(textArea, BorderLayout.CENTER);
JScrollPane scrollPane = new JScrollPane(textArea);
jf.add(scrollPane, BorderLayout.CENTER);
// Główne menu
// File menu
JMenu fileMenu = new JMenu("File");
menuBar.add(fileMenu);
// Open
JMenuItem open = new JMenuItem("Open", new ImageIcon("src/src/if_simpline_4_2305586.png"));
open.setMnemonic(KeyEvent.VK_CONTROL + KeyEvent.VK_O);
open.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
fileMenu.add(open);
open.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
fd = new FileDialog(jf, "Open", FileDialog.LOAD);
textArea.setText("");
fd.setVisible(true);
String katalog = fd.getDirectory();
String plik = fd.getFile();
System.out.println(fd.getFile());
path = katalog + plik;
jf.setTitle("Prosty edytor - " + path);
try {
br = new BufferedReader(new FileReader(path));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
line = br.readLine();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while (line != null) {
textArea.append(line + "\n");
try {
line = br.readLine();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
});
fileMenu.addSeparator();
// Save
JMenuItem save = new JMenuItem("Save", new ImageIcon("src/src/if_simpline_53_2305609.png"));
save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
fileMenu.add(save);
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
File f2 = new File(path);
jf.setTitle("Prosty edytor - " + path);
try {
BufferedWriter out = new BufferedWriter(new FileWriter(f2));
BufferedReader input = new BufferedReader(new StringReader(textArea.getText()));
String line;
while ((line = input.readLine()) != null)
out.write(line);
out.newLine();
out.close();
} catch (AccessDeniedException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
fileMenu.addSeparator();
// Saveas
JMenuItem saveas = new JMenuItem("Save As...", new ImageIcon("src/src/if_simpline_53_2305609.png"));
fileMenu.add(saveas);
saveas.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK));
saveas.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
fd = new FileDialog(jf, "Save As..", FileDialog.SAVE);
fd.setVisible(true);
String katalog = fd.getDirectory();
String plik = fd.getFile();
path = katalog + plik;
File f2 = new File(path);
jf.setTitle("Prosty edytor - " + path);
try {
BufferedWriter out = new BufferedWriter(new FileWriter(f2));
BufferedReader input = new BufferedReader(new StringReader(textArea.getText()));
String line;
while ((line = input.readLine()) != null)
out.write(line);
out.newLine();
out.close();
} catch (AccessDeniedException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
JSeparator sep = new JSeparator(SwingConstants.HORIZONTAL);
sep.setBackground(Color.RED);
fileMenu.add(sep);
// Exit
JMenuItem exit = new JMenuItem("Exit", new ImageIcon("src/src/if_simpline_43_2305619.png"));
exit.setMnemonic(KeyEvent.VK_CONTROL + KeyEvent.VK_X);
exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK));
fileMenu.add(exit);
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
// Exit the program
System.exit(0);
}
});
fileMenu.addSeparator();
// Edit menu
JMenu editMenu = new JMenu("Edit");
menuBar.add(editMenu);
// Sub menu
JMenu adresMenu = new JMenu("Adresy");
editMenu.add(adresMenu);
// Pod menu
praca = new JMenuItem("Praca");
praca.addActionListener(this);
praca.setBorder(BorderFactory.createLineBorder(Color.black));
adresMenu.add(praca);
praca.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.SHIFT_MASK + ActionEvent.CTRL_MASK));
adresMenu.addSeparator();
szkola = new JMenuItem("Szkoła");
szkola.addActionListener(this);
szkola.setBorder(BorderFactory.createLineBorder(Color.black));
adresMenu.add(szkola);
szkola.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.SHIFT_MASK + ActionEvent.CTRL_MASK));
adresMenu.addSeparator();
dom = new JMenuItem("Dom");
dom.addActionListener(this);
dom.setBorder(BorderFactory.createLineBorder(Color.black));
dom.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, ActionEvent.SHIFT_MASK + ActionEvent.CTRL_MASK));
adresMenu.add(dom);
// Options menu
JMenu optionsMenu = new JMenu("Options");
menuBar.add(optionsMenu);
// Sub menu
JMenu foreground = new JMenu("Foreground");
optionsMenu.add(foreground);
// Pod menu foreground
c1f = new JMenuItem("Blue", new ImageIcon("src/src/blue.png"));
foreground.add(c1f);
c1f.addActionListener(this);
c2f = new JMenuItem("Yellow", new ImageIcon("src/src/yellow.png"));
foreground.add(c2f);
c2f.addActionListener(this);
c3f = new JMenuItem("Orange", new ImageIcon("src/src/orange.png"));
foreground.add(c3f);
c3f.addActionListener(this);
c4f = new JMenuItem("Red", new ImageIcon("src/src/red.png"));
foreground.add(c4f);
c4f.addActionListener(this);
c5f = new JMenuItem("White", new ImageIcon("src/src/white.png"));
foreground.add(c5f);
c5f.addActionListener(this);
c6f = new JMenuItem("Black", new ImageIcon("src/src/black.png"));
foreground.add(c6f);
c6f.addActionListener(this);
c7f = new JMenuItem("Green", new ImageIcon("src/src/green.png"));
foreground.add(c7f);
c7f.addActionListener(this);
// Background
JMenu background = new JMenu("Background");
optionsMenu.add(background);
JMenu fontsize = new JMenu("Font size");
optionsMenu.add(fontsize);
// Pod menu background
c1 = new JMenuItem("Blue", new ImageIcon("src/src/blue.png"));
background.add(c1);
c1.addActionListener(this);
c2 = new JMenuItem("Yellow", new ImageIcon("src/src/yellow.png"));
background.add(c2);
c2.addActionListener(this);
c3 = new JMenuItem("Orange", new ImageIcon("src/src/orange.png"));
background.add(c3);
c3.addActionListener(this);
c4 = new JMenuItem("Red", new ImageIcon("src/src/red.png"));
background.add(c4);
c4.addActionListener(this);
c5 = new JMenuItem("White", new ImageIcon("src/src/white.png"));
background.add(c5);
c5.addActionListener(this);
c6 = new JMenuItem("Black", new ImageIcon("src/src/black.png"));
background.add(c6);
c6.addActionListener(this);
c7 = new JMenuItem("Green", new ImageIcon("src/src/green.png"));
background.add(c7);
c7.addActionListener(this);
// Pod menu font size
pkt8 = new JMenuItem("8 pts");
pkt8.addActionListener(this);
fontsize.add(pkt8);
pkt10 = new JMenuItem("10 pts");
fontsize.add(pkt10);
pkt10.addActionListener(this);
pkt12 = new JMenuItem("12 pts");
fontsize.add(pkt12);
pkt12.addActionListener(this);
pkt14 = new JMenuItem("14 pts");
fontsize.add(pkt14);
pkt14.addActionListener(this);
pkt16 = new JMenuItem("16 pts");
fontsize.add(pkt16);
pkt16.addActionListener(this);
pkt18 = new JMenuItem("18 pts");
fontsize.add(pkt18);
pkt18.addActionListener(this);
pkt20 = new JMenuItem("20 pts");
fontsize.add(pkt20);
pkt20.addActionListener(this);
pkt22 = new JMenuItem("22 pts");
fontsize.add(pkt22);
pkt22.addActionListener(this);
pkt24 = new JMenuItem("24 pts");
fontsize.add(pkt24);
pkt24.addActionListener(this);
}
String tab[] = { " adres praca", " adres szkola", " adres dom" };
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == pkt8) {
textArea.setFont(new Font("monospaced", Font.PLAIN, 8));
} else if (e.getSource() == pkt10) {
textArea.setFont(new Font("monospaced", Font.PLAIN, 10));
} else if (e.getSource() == pkt12) {
textArea.setFont(new Font("monospaced", Font.PLAIN, 12));
} else if (e.getSource() == pkt14) {
textArea.setFont(new Font("monospaced", Font.PLAIN, 14));
} else if (e.getSource() == pkt16) {
textArea.setFont(new Font("monospaced", Font.PLAIN, 16));
} else if (e.getSource() == pkt18) {
textArea.setFont(new Font("monospaced", Font.PLAIN, 18));
} else if (e.getSource() == pkt20) {
textArea.setFont(new Font("monospaced", Font.PLAIN, 20));
} else if (e.getSource() == pkt22) {
textArea.setFont(new Font("monospaced", Font.PLAIN, 22));
} else if (e.getSource() == pkt24) {
textArea.setFont(new Font("monospaced", Font.PLAIN, 24));
} else if (e.getSource() == c1) {
textArea.setBackground(Color.BLUE);
} else if (e.getSource() == c2) {
textArea.setBackground(Color.YELLOW);
} else if (e.getSource() == c3) {
textArea.setBackground(Color.ORANGE);
} else if (e.getSource() == c4) {
textArea.setBackground(Color.RED);
} else if (e.getSource() == c5) {
textArea.setBackground(Color.WHITE);
} else if (e.getSource() == c6) {
textArea.setBackground(Color.BLACK);
} else if (e.getSource() == c7) {
textArea.setForeground(Color.GREEN);
} else if (e.getSource() == c1f) {
textArea.setForeground(Color.BLUE);
} else if (e.getSource() == c2f) {
textArea.setForeground(Color.YELLOW);
} else if (e.getSource() == c3f) {
textArea.setForeground(Color.ORANGE);
} else if (e.getSource() == c4f) {
textArea.setForeground(Color.RED);
} else if (e.getSource() == c5f) {
textArea.setForeground(Color.WHITE);
} else if (e.getSource() == c6f) {
textArea.setForeground(Color.BLACK);
} else if (e.getSource() == c7f) {
textArea.setForeground(Color.GREEN);
} else if (e.getSource() == praca) {
textArea.append(tab[0]);
} else if (e.getSource() == szkola) {
textArea.append(tab[1]);
} else if (e.getSource() == dom) {
textArea.append(tab[2]);
}
}
}
Code from comment:
public ZmianaTla(Color color, String label, JComponent target,
ImageIcon ico) {
super(label);
this.color=color;
this.target=target;
this.ico=ico;
}
background.add(new JMenuItem(new ZmianaTla(Color.YELLOW, "Yellow",
textArea),new ImageIcon("src/src/yellow.png"));
It is hard to make it essentially shorter. I suppose your point is rather how to reduce boiler plate, repetition of similar code. The one of solutions can be following.
Implement an action to change the font:
public class ChangeFontAction extends AbstractAction {
private int fontSize;
private JTextComponent target;
public ChangeFontAction(int fontSize, String label, JTextComponent target) {
super(label);
this.fontSize = fontSize;
this.target = target;
}
public void actionPerformed(ActionEvent e) {
target.setFont(new Font(Font.MONOSPACED, Font.PLAIN, fontSize));
}
}
In this action change the font:
target.setFont(new Font("monospaced", Font.PLAIN, fontSize))
Create menu items as follows:
fontsize.add(new JMenuItem(new ChangeFontAction(8, "8 pts", textArea)));
fontsize.add(new JMenuItem(new ChangeFontAction(10, "10 pts", textArea)));
You dont't need now any listener.
All in all may be not less code, but much easier to understand. And if you want to change what happens on button/menu click, you don't need repeat it many times, you will do it on a single place.
In similar fashion you can create an action class to change color.

JComboBox Null pointer Exception. Need to get Int from box and set int as selected int from box

My program right now needs to load up two text files and I'm sorting them by string of words. JcomboxBox is supposed to allow you to select int between 1 and 4 (the size of the string to compare)
so 2 would return "I am" whereas 1 would return "I"
I'm getting null pointed exception and I have never used combo boxes before. Please help/
import java.awt.GridLayout;
import javax.swing.JFrame;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.Scanner;
import java.util.Arrays;
import javax.swing.JComboBox;
public class Lab8 extends JPanel
{
private JPanel text;
private JComboBox input;
private JLabel label;
private JButton load, go,go2;
private CountList<SuperString> words;
private String filename;
private int width = 400;
private int height = 600;
private TextArea textarea,textarea2;
Scanner scan;
public Lab8()
{
Integer [] select = {1,2,3,4};
JComboBox input = new JComboBox(select);
text = new JPanel(new GridLayout(1,2));
go = new JButton("Select Text File");
go2 = new JButton("Select 2nd Text File");
label = new JLabel("How many sequenced words would you like to analyze? (Must be => 1)" );
input.setSelectedIndex(0);
ButtonListener listener = new ButtonListener();
go.addActionListener(listener);
go2.addActionListener(listener);
input.addActionListener(listener);
textarea = new TextArea("",0,0,TextArea.SCROLLBARS_VERTICAL_ONLY);
textarea2 = new TextArea("",0,0,TextArea.SCROLLBARS_VERTICAL_ONLY);
textarea.setFont(new Font("Helvetica",Font.PLAIN,24));
textarea2.setFont(new Font("Helvetica",Font.PLAIN,24));
textarea.setPreferredSize(new Dimension(width,height));
textarea2.setPreferredSize(new Dimension(width,height));
setPreferredSize(new Dimension(900,600));
text.add(textarea);
text.add(textarea2);
add(input);
add(go);
add(go2);
add(text);
textarea.setText("No File Selected");
textarea2.setText("No File Selected");
}
public class ButtonListener implements ActionListener //makes buttons do things
{
JFileChooser chooser = new JFileChooser("../Text");
public void actionPerformed(ActionEvent event)
{
Integer N = input.getSelectedIndex();
if(event.getSource() == go)
{
int returnvalue = chooser.showOpenDialog(null);
if(returnvalue == JFileChooser.APPROVE_OPTION)
{
try
{
File file = chooser.getSelectedFile();
filename = file.getName();
System.err.println(filename);
scan = new Scanner(file);
}
catch (IOException e)
{
System.err.println("IO EXCEPTION");
return;
}
}
else
{
return;
}
String[] storage = new String[N];
words = new CountLinkedList<SuperString>();
for(int i=1;i<N;i++)
storage[i] = scan.next().toLowerCase().replace(",","").replace(".","");
while(scan.hasNext())
{
for(int i=0;i<=N-2;i++)
storage[i] = storage[i+1];
storage[N-1] = scan.next().toLowerCase();
storage[N-1] = storage[N-1].replace(",","").replace(".","");
SuperString ss = new SuperString(storage);
// System.out.println(ss);
words.add(ss );
}
scan.close();
textarea.append(" "+filename+" has wordcount: "+words.size()+
"\n-------------------------\n\n");
SuperString[] ss = new SuperString[words.size()];
int i=0;
for(SuperString word: words)
{
ss[i] = word;
i++;
}
Arrays.sort(ss, new SuperStringCountOrder());
for(SuperString word : ss)
{
textarea.append(" "+word+"\n");
}
}
if(event.getSource() == go2)
{
int returnvalue = chooser.showOpenDialog(null);
if(returnvalue == JFileChooser.APPROVE_OPTION)
{
try
{
File file = chooser.getSelectedFile();
filename = file.getName();
System.err.println(filename);
scan = new Scanner(file);
}
catch (IOException e)
{
System.err.println("IO EXCEPTION");
return;
}
}
else
{
return;
}
String[] storage = new String[N];
words = new CountLinkedList<SuperString>();
for(int i=1;i<N;i++)
storage[i] = scan.next().toLowerCase().replace(",","").replace(".","");
while(scan.hasNext())
{
for(int i=0;i<=N-2;i++)
storage[i] = storage[i+1];
storage[N-1] = scan.next().toLowerCase();
storage[N-1] = storage[N-1].replace(",","").replace(".","");
SuperString ss = new SuperString(storage);
words.add(ss );
}
scan.close();
textarea2.append(" "+filename+" has wordcount: "+words.size()+
"\n-------------------------\n\n");
SuperString[] ss = new SuperString[words.size()];
int i=0;
for(SuperString word: words)
{
ss[i] = word;
i++;
}
Arrays.sort(ss, new SuperStringCountOrder());
for(SuperString word : ss)
{
textarea2.append(" "+word+"\n");
}
}
}
}
public static void main(String[] arg)
{
JFrame frame = new JFrame("Lab 8");
frame.getContentPane().add(new Lab8());
frame.pack();
frame.setVisible(true);
}
}
You're re-declaring your JComboBox variable in the constructor and thus shadowing the field found in the class. By doing this the field remains null:
public class Lab8 extends JPanel
{
private JPanel text;
private JComboBox input; // this guy remains null
// .... etc ....
public Lab8()
{
Integer [] select = {1,2,3,4};
// the line below initializes a local input variable.
// this variable is visible only inside of the constructor
JComboBox input = new JComboBox(select); // ***** here ****
Don't re-declare the variable:
public class Lab8 extends JPanel
{
private JPanel text;
private JComboBox input;
// .... etc ....
public Lab8()
{
Integer [] select = {1,2,3,4};
// JComboBox input = new JComboBox(select); // ***** here ****
input = new JComboBox(select); // ***** note difference? *****

How to Save/Open an ArrayList of objects using JFileChooser?

Okay so I'm kind of new to Java programming, and I don't quite understand the concepts of file reading/writing. I've tried looking at the docs.oracle webpages about Files, but I found they aren't really helpful considering what I'm trying to do is kind of different.
I have these 3 files: CVolunteer, CDialog, and TestDialog. CVolunteer creates and object of a person who can volunteer to tutor students. CDialog manages the adding/editing of the volunteer. TestDialog displays a JList of volunteers and allows the user to edit, add, remove, or clear the list. I have those 3 classes working perfectly and will display them below (sorry they're long!).
Here's what I need help with... I added two buttons to the main window, "Save" and "Open". At any time, the user should be able to save the current JList of volunteers. When "Save" is clicked, a JFileChooser window should pop up and ask the user for a filename where all the volunteer objects will be saved. When the user clicks "Open", another JFileChooser window should pop up and ask the user what file they want to open. The volunteers currently in the main window will be erased and the volunteers from the selected file will take their place. I'm not sure if I need to use Serialization or not....
If anyone could help explain how to accomplish this or help me write the code to handle the "Save"/"Open" events, I would really appreciate it! Thanks in advance:)
I believe the only file that needs changing is TestDialog, I included the others in case someone wants to try to run it
***Sorry if there are any indentation errors, I had to do it all by hand in this dialog box
CVolunteer.java
public class CVolunteer {
int volNum;
String name;
int sub, volDays, trans;
public CVolunteer(int vNum, String vName, int subj, int days, int needTrans){
volNum = vNum;
name = vName;
sub = subj;
volDays = days;
trans = needTrans;
}
private String subjectToString()
{
switch (sub){
case 0:
return "Math";
case 1:
return "Science";
case 2:
return "English";
case 3:
return "History";
}
return " ";
}
private String volDaysToString()
{
String str = "";
str +=((volDays&1)!=0)?"M":"-";
str +=((volDays&2)!=0)?"T":"-";
str +=((volDays&4)!=0)?"W":"-";
str +=((volDays&8)!=0)?"R":"-";
return str;
}
private String transToString()
{
switch(trans)
{
case 0:
return "Yes";
case 1:
return "No";
}
return " ";
}
public String getVolunteerLine()
{
return String.format("%05d %-30s%-30s%-30s%s",
volNum, name, subjectToString(), volDaysToString(), transToString());
}
}
CDialog.java
import java.awt.Container;
import java.awt.event.*;
import javax.swing.*;
public class CDialog extends JDialog implements ActionListener
{
private JLabel label1;
private JLabel lNum;
private JLabel label2;
private JTextField tfName;
private JLabel label3;
private ButtonGroup subGroup;
private JRadioButton rbMath;
private JRadioButton rbScience;
private JRadioButton rbEnglish;
private JRadioButton rbHistory;
private JLabel label4;
private JCheckBox cbMonday;
private JCheckBox cbTuesday;
private JCheckBox cbWednesday;
private JCheckBox cbThursday;
private JLabel label5;
private ButtonGroup transGroup;
private JRadioButton rbYes;
private JRadioButton rbNo;
private JButton okButton = null;
private JButton cancelButton = null;
private boolean cancelled = true;
public boolean isCancelled() {return cancelled;}
private CVolunteer answer;
public CVolunteer getAnswer() {return answer;}
public CDialog(JFrame owner, String title, CVolunteer vol)
{
super(owner, title, true);
Container c = getContentPane();
c.setLayout(null);
label1 = new JLabel ("Volunteer Number:");
label1.setSize(140,20);
label1.setLocation(40,40);
c.add(label1);
lNum = new JLabel(String.format("%05d", vol.volNum));
lNum.setSize(40,20);
lNum.setLocation(150,40);
c.add(lNum);
label2 = new JLabel ("Volunteer Name: ");
label2.setSize(100,20);
label2.setLocation(40,90);
c.add(label2);
tfName = new JTextField(vol.name);
tfName.setSize(120,20);
tfName.setLocation(140,90);
c.add(tfName);
int x,y;
int w,h;
x=4;
y=150;
w=180;
h=20;
label3 = new JLabel("Subject: ");
label3.setSize(85,13);
label3.setLocation(x,y);
c.add(label3);
rbMath = new JRadioButton("Math", vol.sub==0);
rbMath.setSize(w,h);
rbMath.setLocation(x+16,y+30);
c.add(rbMath);
rbScience = new JRadioButton("Science", vol.sub==1);
rbScience.setSize(w,h);
rbScience.setLocation(x+16,y+66);
c.add(rbScience);
rbEnglish = new JRadioButton("English", vol.sub==2);
rbEnglish.setSize(w,h);
rbEnglish.setLocation(x+16,y+102);
c.add(rbEnglish);
rbHistory = new JRadioButton("History", vol.sub==3);
rbHistory.setSize(w,h);
rbHistory.setLocation(x+16,y+138);
c.add(rbHistory);
subGroup = new ButtonGroup();
subGroup.add(rbMath);
subGroup.add(rbScience);
subGroup.add(rbEnglish);
subGroup.add(rbHistory);
x=220;
y=150;
w=120;
h=20;
label4 = new JLabel("Days Available: ");
label4.setSize(w,h);
label4.setLocation(x,y);
c.add(label4);
cbMonday = new JCheckBox("Monday (M)", (vol.volDays&1)!=0);
cbMonday.setSize(w,h);
cbMonday.setLocation(x+6,y+30);
c.add(cbMonday);
cbTuesday = new JCheckBox("Tuesday (T)", (vol.volDays&2)!=0);
cbTuesday.setSize(w,h);
cbTuesday.setLocation(x+6,y+66);
c.add(cbTuesday);
cbWednesday = new JCheckBox("Wednesday (W)", (vol.volDays&4)!=0);
cbWednesday.setSize(w,h);
cbWednesday.setLocation(x+6,y+102);
c.add(cbWednesday);
cbThursday = new JCheckBox("Thursday (R)", (vol.volDays&8)!=0);
cbThursday.setSize(w,h);
cbThursday.setLocation(x+6,y+138);
c.add(cbThursday);
x=480;
y=150;
w=180;
h=20;
label5 = new JLabel("Need Transport? :");
label5.setSize(150,13);
label5.setLocation(x,y);
c.add(label5);
rbYes = new JRadioButton("Yes", vol.trans==0);
rbYes.setSize(w,h);
rbYes.setLocation(x+12,y+30);
c.add(rbYes);
rbNo = new JRadioButton("No", vol.trans==1);
rbNo.setSize(w,h);
rbNo.setLocation(x+12,y+66);
c.add(rbNo);
transGroup = new ButtonGroup();
transGroup.add(rbYes);
transGroup.add(rbNo);
cancelButton = new JButton("Cancel");
cancelButton.addActionListener(this);
cancelButton.setSize(100,50);
cancelButton.setLocation(116,380);
c.add(cancelButton);
okButton = new JButton("OK");
okButton.addActionListener(this);
okButton.setSize(100,50);
okButton.setLocation(400,380);
c.add(okButton);
setSize(700,480);
setLocationRelativeTo(owner);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource()==okButton) {
int num=Integer.parseInt(lNum.getText());
String name=tfName.getText();
int subj=-1;
if (rbMath.isSelected()) subj = 0;
if (rbScience.isSelected()) subj = 1;
if (rbEnglish.isSelected()) subj = 2;
if (rbHistory.isSelected()) subj = 3;
int days=0;
if (cbMonday.isSelected()) days |= 1;
if (cbTuesday.isSelected()) days |= 2;
if (cbWednesday.isSelected()) days |= 4;
if (cbThursday.isSelected()) days |= 8;
int tran=0;
if (rbYes.isSelected()) tran = 0;
if (rbNo.isSelected()) tran = 1;
answer=new CVolunteer(num, name, subj, days, tran);
cancelled = false;
setVisible(false);
}
else if(e.getSource()==cancelButton) {
cancelled = true;
setVisible(false);
}
}
}
TestDialog.java
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.ArrayList;
public class TestDialog extends JFrame implements ActionListener
{
JLabel myLabel1 = null;
JLabel myLabel2 = null;
JLabel myLabel3 = null;
JLabel myLabel4 = null;
JLabel myLabel5 = null;
JLabel myLabel6 = null;
File fileName = new File("Volunteers.txt");
ArrayList<CVolunteer> volArray;
private DefaultListModel volunteers;
JList volList;
JScrollPane scrollPane = null;
JButton bAdd = null;
JButton bEdit = null;
JButton bRemove = null;
JButton bClear = null;
JButton bSave = null;
JButton bOpen = null;
int volNumb;
public TestDialog()
{
super("Volunteer Info");
Container c = getContentPane();
c.setLayout(null);
myLabel1 = new JLabel("Vol Number");
myLabel1.setSize(200,50);
myLabel1.setLocation(100,10);
c.add(myLabel1);
myLabel2 = new JLabel("Vol Name");
myLabel2.setSize( 200, 50 );
myLabel2.setLocation( 200, 10 );
c.add(myLabel2);
myLabel3 = new JLabel("Subject");
myLabel3.setSize( 200, 50 );
myLabel3.setLocation( 310, 10);
c.add(myLabel3);
myLabel4 = new JLabel("Vol Days");
myLabel4.setSize( 200, 50 );
myLabel4.setLocation( 400, 10 );
c.add(myLabel4);
myLabel5 = new JLabel("Transport");
myLabel5.setSize( 200, 50 );
myLabel5.setLocation( 500, 10 );
c.add(myLabel5);
volArray = new ArrayList<CVolunteer>();
volunteers = new DefaultListModel();
volList = new JList(volunteers);
volList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
scrollPane = new JScrollPane(volList);
scrollPane.setSize(500,300);
scrollPane.setLocation(100,50);
c.add(scrollPane);
bAdd = new JButton("Add");
bAdd.setSize( 100, 50 );
bAdd.setLocation( 20, 400 );
bAdd.addActionListener(this);
c.add(bAdd);
bEdit = new JButton("Edit");
bEdit.setSize( 100, 50 );
bEdit.setLocation( 150, 400 );
bEdit.addActionListener(this);
c.add(bEdit);
bRemove = new JButton("Remove");
bRemove.setSize( 100, 50 );
bRemove.setLocation( 280, 400 );
bRemove.addActionListener(this);
c.add(bRemove);
bClear = new JButton("Clear");
bClear.setSize( 100, 50 );
bClear.setLocation( 410, 400 );
bClear.addActionListener(this);
c.add(bClear);
bSave = new JButton("Save");
bSave.setSize( 100, 50 );
bSave.setLocation( 540, 400 );
bSave.addActionListener(this);
c.add(bSave);
bOpen = new JButton("Open");
bOpen.setSize( 100, 50 );
bOpen.setLocation( 670, 400 );
bOpen.addActionListener(this);
c.add(bOpen);
setSize( 800, 600 );
setLocation( 100, 100 );
setVisible(true);
volNumb = 0;
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==bAdd) {
volNumb++;
CVolunteer defaultVol = new CVolunteer(volNumb, "", 1, 0, 0);
CDialog dialogWnd = new CDialog(this, "Add a Volunteer", defaultVol);
if (!dialogWnd.isCancelled()) {
volArray.add(dialogWnd.getAnswer());
volunteers.addElement(dialogWnd.getAnswer().getVolunteerLine());
volList.setSelectedIndex(volunteers.size()-1);
volList.ensureIndexIsVisible(volunteers.size()-1);
}
}
else if(e.getSource()==bEdit) {
int index=volList.getSelectedIndex();
if (index>=0) {
CDialog dialogWnd = new CDialog (this, "Edit a Volunteer", volArray.get(index));
if (!dialogWnd.isCancelled()) {
volArray.set(index, dialogWnd.getAnswer());
volunteers.set(index, dialogWnd.getAnswer().getVolunteerLine());
}
}
}
else if(e.getSource()==bRemove) {
int index=volList.getSelectedIndex();
if (index>=0) {
volArray.remove(index);
volunteers.remove(index);
if (volunteers.size()>0) {
if (index==volunteers.size()) {
index--;
}
volList.setSelectedIndex(index);
volList.ensureIndexIsVisible(index);
}
}
}
else if(e.getSource()==bClear) {
volArray.clear();
volunteers.clear();
}
else if (e.getSource()==bSave)
{
//my sorry attempt at writing a file.. ignore this!
try {
FileWriter fw = new FileWriter(fileName);
Writer output = new BufferedWriter(fw);
int size = volArray.size();
for (int i = 0; i<size; i++)
{
output.write(volArray.get(i).getVolunteerLine() + "\n");
}
output.close();
}
catch (Exception e1) {
// TODO Auto-generated catch block
}
final JFileChooser fc = new JFileChooser();
}
else if (e.getSource()==bOpen)
{
}
}
public static void main(String[] args) {
TestDialog mainWnd = new TestDialog();
}
}
EDIT:
Here is some attempted code for my "Save" Button.... I still don't know if this is on the right track or not! It doesn't seem to be doing anything
else if (e.getSource()==bSave)
{
try
{
FileOutputStream fileOut = new FileOutputStream("???");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
for(int i=0; i<volArray.size(); i++)
{
out.writeObject(volArray.get(i).getVolunteerLine());
}
out.close();
fileOut.close();
} catch (Exception e1) {
// TODO Auto-generated catch block
}
final JFileChooser fc = new JFileChooser();
}
You have to use a specific format that you define to write in your file :
Add a serialize method in you volunteer class then you can iterate over them and serialize each of them.
String serialize() will encode all the members as a string then you can reconstruct at reading (on Open).
An example could be a coma separated list : member1=xxx, member2=xxx, ...
Or xml or json for more ease :)
At reading, it's the opposite, parse the content of the file and build your volunteers back !
Edit:
Saving:
Open a file in write mode
write all your n volunteers
at this point you should have n lines in your file
close the file
Reading:
Open your file in reading mode
Read it line by line
For each line
split over ','
build your volunteer
add it to volArray
close your file
Does it make sense for you ? Each of these steps are trivial with a simple google search
Edit :
Final JFileChooser fc = new JFileChooser();
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
//This is where a real application would open the file.
log.append("Opening: " + file.getName() + "." + newline);
// Here you can open the file and write to it
//
} else {
log.append("Open command cancelled by user." + newline);
}
You can do the same when on open, select the file then read from it

Java: Components disappearing after event

I'm trying to make something for fun and my components keep disappearing after I press the "ok" button in my gui.
I'm trying to make a "Guess a word" program, where one will get a tip and you can then enter a guess and if it matches it will give you a message and if not, another tip. The problem is, if you enter something that's not the word it will give you a message that it's not the correct word and it will then give you another tip. But the other tip won't show up. They disappear.
I've two classes, "StartUp" and "QuizLogic".
The problem arrives somewhere in the "showTips" method (I think).
If someone would try it themselves a link to the file can be found here: Link to file
Thank you.
public class StartUp {
private JFrame frame;
private JButton showRulesYesButton;
private JButton showRulesNoButton;
private JButton checkButton;
private JPanel mainBackgroundManager;
private JTextField guessEntery;
private QuizLogic quizLogic;
private ArrayList<String> tips;
private JLabel firstTipLabel;
private JLabel secondTipLabel;
private JLabel thirdTipLabel;
// CONSTRUCTOR
public StartUp() {
// Show "Start Up" message
JOptionPane.showMessageDialog(null, "Guess a Word!");
showRules();
}
// METHODS
public void showRules() {
// Basic frame methods
frame = new JFrame("Rules");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(500, 500));
frame.setLocationRelativeTo(null);
// Creates JLabels and adds to JPanel
JLabel firstRule = new JLabel("1. You will get one tip at a time of what the word could be.");
JLabel secoundRule = new JLabel("2. You will get three tips and unlimited guesses.");
JLabel thirdRule = new JLabel("3. Every word is a noun and in its basic form.");
JLabel understand = new JLabel("Are you ready?");
// Creates JPanel and adds JLabels to JPanel
JPanel temporaryRulesPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 100, 60));
temporaryRulesPanel.add(firstRule);
temporaryRulesPanel.add(secoundRule);
temporaryRulesPanel.add(thirdRule);
temporaryRulesPanel.add(understand);
// Initialize buttons
showRulesYesButton = new JButton("Yes");
showRulesNoButton = new JButton("No");
showRulesYesButton.addActionListener(new StartUpEventHandler());
showRulesNoButton.addActionListener(new StartUpEventHandler());
// Creates JPanel and adds button to JPanel
JPanel temporaryButtonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 100, 35));
temporaryButtonPanel.add(showRulesYesButton);
temporaryButtonPanel.add(showRulesNoButton);
// Initialize and adds JPanel to JPanel
mainBackgroundManager = new JPanel(new BorderLayout());
mainBackgroundManager.add(temporaryRulesPanel, BorderLayout.CENTER);
mainBackgroundManager.add(temporaryButtonPanel, BorderLayout.SOUTH);
//Adds JPanel to JFrame
frame.add(mainBackgroundManager);
frame.setVisible(true);
}
public void clearBackground() {
mainBackgroundManager.removeAll();
quizLogic = new QuizLogic();
showGuessFrame();
showTips();
}
public void showGuessFrame() {
JPanel guessPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 50, 10));
firstTipLabel = new JLabel("a");
secondTipLabel = new JLabel("b");
thirdTipLabel = new JLabel("c");
tips = new ArrayList<String>();
guessEntery = new JTextField("Enter guess here", 20);
checkButton = new JButton("Ok");
checkButton.addActionListener(new StartUpEventHandler());
guessPanel.add(guessEntery);
guessPanel.add(checkButton);
mainBackgroundManager.add(guessPanel, BorderLayout.SOUTH);
frame.add(mainBackgroundManager);
}
public void showTips() {
JPanel temporaryTipsPanel = new JPanel(new GridLayout(3, 1));
temporaryTipsPanel.removeAll();
tips.add(quizLogic.getTip());
System.out.println(tips.size());
if (tips.size() == 1) {
firstTipLabel.setText(tips.get(0));
}
if (tips.size() == 2) {
secondTipLabel.setText(tips.get(1));
}
if (tips.size() == 3) {
thirdTipLabel.setText(tips.get(2));
}
temporaryTipsPanel.add(firstTipLabel);
temporaryTipsPanel.add(secondTipLabel);
temporaryTipsPanel.add(thirdTipLabel);
mainBackgroundManager.add(temporaryTipsPanel, BorderLayout.CENTER);
frame.add(mainBackgroundManager);
frame.revalidate();
frame.repaint();
}
public void getGuess() {
String temp = guessEntery.getText();
boolean correctAnswer = quizLogic.checkGuess(guessEntery.getText());
if (correctAnswer == true) {
JOptionPane.showMessageDialog(null, "Good Job! The word was " + temp);
}
else {
JOptionPane.showMessageDialog(null, temp + " is not the word we are looking for");
showTips();
}
}
private class StartUpEventHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getSource() == showRulesYesButton) {
clearBackground();
}
else if (event.getSource() == showRulesNoButton) {
JOptionPane.showMessageDialog(null, "Read the rules again");
}
else if (event.getSource() == checkButton) {
getGuess();
}
}
}
}
public class QuizLogic {
private ArrayList<String> quizWord;
private ArrayList<String> tipsList;
private int tipsNumber;
private String word;
public QuizLogic() {
tipsNumber = 0;
quizWord = new ArrayList<String>();
quizWord.add("Burger");
try {
loadTips(getWord());
} catch (Exception e) {
System.out.println(e);
}
}
public String getWord() {
Random randomGen = new Random();
return quizWord.get(randomGen.nextInt(quizWord.size()));
}
public void loadTips(String word) throws FileNotFoundException {
Scanner lineScanner = new Scanner(new File("C:\\Users\\Oliver Nielsen\\Dropbox\\EclipseWorkspaces\\BuildingJava\\GuessAWord\\src\\domain\\" + word + ".txt"));
this.word = word;
tipsList = new ArrayList<String>();
while (lineScanner.hasNext()) {
tipsList.add(lineScanner.nextLine());
}
}
public String getTip() {
if (tipsNumber >= tipsList.size()) {
throw new NoSuchElementException();
}
String temp = tipsList.get(tipsNumber);
tipsNumber++;
System.out.println(temp);
return temp;
}
public boolean checkGuess(String guess) {
return guess.equalsIgnoreCase(word);
}
}
I figured it out!
I don't know why it can't be done but if I deleted this line: JPanel temporaryTipsPanel = new JPanel(new GridLayout(3, 1));
and placed it in another method it worked. If someone could explain why that would be great but at least I/we know what was the problem.
Thank you. :)

reading name contact

Im making a contact list, and my code compiles and runs, when you add the contact, type or email or phone its supposed to read them to you, the problem I have here is when I add the contacts and press next or previous, first or last it doesnt read the Name Contact, but it reads everything else...does it have to do something with spacing ? here is what I have...thanks
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class ContactSystem extends JFrame{
//Specify the size of five string fields in the record
final static int NAME_SIZE = 32;
final static int TYPE_SIZE = 32;
final static int CITY_SIZE = 20;
final static int PHONE_SIZE = 15;
final static int EMAIL_SIZE = 15;
final static int RECORD_SIZE =
(NAME_SIZE + TYPE_SIZE + CITY_SIZE + PHONE_SIZE + EMAIL_SIZE);
//access contact.dat using RandomAccessFile
private RandomAccessFile raf;
//Text Fields
private JTextField jbtName = new JTextField(NAME_SIZE);
private JTextField jbtType = new JTextField(TYPE_SIZE);
private JTextField jbtCity = new JTextField(CITY_SIZE);
private JTextField jbtPhone = new JTextField(PHONE_SIZE);
private JTextField jbtEmail = new JTextField(EMAIL_SIZE);
//Buttons
private JButton jbtAdd = new JButton("Add");
private JButton jbtFirst = new JButton("First");
private JButton jbtNext = new JButton("Next");
private JButton jbtPrevious = new JButton("Previous");
private JButton jbtLast = new JButton("Last");
public ContactSystem(){
//open or create a random access file
try {
raf = new RandomAccessFile("contact.txt", "rw");
}
catch(IOException ex) {
System.out.print("Error: " + ex);
System.exit(0);
}
//Panel p1 for holding labels Name , Type, Email or phone
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(3,1));
p1.add(new JLabel("Name Contact"));
p1.add(new JLabel("Email Address"));
p1.add(new JLabel("Type of Contact"));
//Panel jpPhone for holding Phone
JPanel jpPhone = new JPanel();
jpPhone.setLayout(new BorderLayout());
jpPhone.add(new JLabel("Phone"), BorderLayout.WEST);
jpPhone.add(jbtPhone, BorderLayout.CENTER);
//Panel jpEmail for holding Phone
JPanel jpEmail = new JPanel();
jpEmail.setLayout(new BorderLayout());
jpEmail.add(new JLabel("Phone"), BorderLayout.WEST);
jpEmail.add(jbtEmail, BorderLayout.CENTER);
// Panel p2 for holding jpPhone and jpEmail
JPanel p2 = new JPanel();
p2.setLayout(new BorderLayout());
p2.add(jpPhone, BorderLayout.WEST);
p2.add(jpPhone, BorderLayout.CENTER);
JPanel p3 = new JPanel();
p3.setLayout(new BorderLayout());
p3.add(jbtCity, BorderLayout.CENTER);
p3.add(p2, BorderLayout.EAST);
//panel p4 for holding jtfName, jtfType, and p3
JPanel p4 = new JPanel();
p4.setLayout(new GridLayout(3,1));
p4.add(jbtName);
p4.add(jbtType);
p4.add(p3);
//place p1 and p4 into jpContact
JPanel jpContact = new JPanel(new BorderLayout());
jpContact.add(p1, BorderLayout.WEST);
jpContact.add(p4, BorderLayout.CENTER);
//set panel with line border
jpContact.setBorder(new BevelBorder(BevelBorder.RAISED));
//add buttons to a panel
JPanel jpButton = new JPanel();
jpButton.add(jbtAdd);
jpButton.add(jbtFirst);
jpButton.add(jbtNext);
jpButton.add(jbtPrevious);
jpButton.add(jbtLast);
//add jpContact and jpButton to the frame
add(jpContact, BorderLayout.CENTER);
add(jpButton, BorderLayout.SOUTH);
jbtAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
writeContact();
}
});
jbtFirst.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
if (raf.length() > 0) readContact(0);
}
catch(IOException ex){
ex.printStackTrace();
}
}
});
jbtNext.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
try {
long currentPosition = raf.getFilePointer();
if (currentPosition < raf.length())
readContact(currentPosition);
}
catch (IOException ex) {
ex.printStackTrace();
}
}
});
jbtPrevious.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
long currentPosition = raf.getFilePointer();
if(currentPosition - 2 * RECORD_SIZE > 0)
//why 2 * 2 * RECORD_SIZE? see the the follow-up remarks
readContact(currentPosition - 2 * 2 * RECORD_SIZE);
else
readContact(0);
}
catch(IOException ex){
ex.printStackTrace();
}
}
});
jbtLast.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
long lastPosition = raf.length();
if(lastPosition > 0)
//why 2 * RECORD_SIZE? see the follow up remarks
readContact(lastPosition - 2 * RECORD_SIZE);
}
catch (IOException ex) {
ex.printStackTrace();
}
}
});
try {
if (raf.length() > 0) readContact(0);
}
catch (IOException ex) {
ex.printStackTrace();
}
}
//write a record at the end of file
public void writeContact() {
try {
raf.seek(raf.length());
FixedLengthStringIO.writeFixedLengthString(
jbtName.getText(), NAME_SIZE, raf);
FixedLengthStringIO.writeFixedLengthString(
jbtType.getText(), TYPE_SIZE, raf);
FixedLengthStringIO.writeFixedLengthString(
jbtCity.getText(), CITY_SIZE, raf);
FixedLengthStringIO.writeFixedLengthString(
jbtPhone.getText(), PHONE_SIZE, raf);
FixedLengthStringIO.writeFixedLengthString(
jbtEmail.getText(), EMAIL_SIZE, raf);
}
catch (IOException ex) {
ex.printStackTrace();
}
}
//read a contact at the specific position
public void readContact(long position) throws IOException{
raf.seek(position);
String name = FixedLengthStringIO.readFixedLengthString(
NAME_SIZE, raf);
String type = FixedLengthStringIO.readFixedLengthString(
TYPE_SIZE, raf);
String city = FixedLengthStringIO.readFixedLengthString(
CITY_SIZE, raf);
String phone = FixedLengthStringIO.readFixedLengthString(
PHONE_SIZE, raf);
String email = FixedLengthStringIO.readFixedLengthString(
EMAIL_SIZE, raf);
jbtName.setText(name);
jbtType.setText(type);
jbtCity.setText(city);
jbtName.setText(phone);
jbtName.setText(email);
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ContactSystem frame = new ContactSystem();
frame.pack();
frame.setTitle("Contact System");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
fixedlengthstringIO class
import java.io.*;
public class FixedLengthStringIO {
//read fixed number of characters from datainput stream
public static String readFixedLengthString(int size,
DataInput in) throws IOException {
//declare an array of characters
char[] chars = new char[size];
//read fixed number of characters to the array
for(int i = 0; i < size; i++)
chars[i] = in.readChar();
return new String (chars);
}
//write fixed number of characters to a dataoutput stream
public static void writeFixedLengthString(String s, int size,
DataOutput out) throws IOException {
char[] chars = new char[size];
//fill an array of characters from the string
s.getChars(0, Math.min(s.length(), size), chars, 0);
//fill in blank characters in the rest of the array
for (int i = Math.min(s.length(), size); i < chars.length; i++)
chars[i] = ' ';
//create and write a new string padded with blank characters
out.writeChars(new String(chars));
}
}
here is when I type in contact name, type, email etc into the list
and when I press next or previous, or first or last, it doesnt read the name..
Glitch is in your readContact method, change this
public void readContact(long position) throws IOException {
raf.seek(position);
String name = FixedLengthStringIO.readFixedLengthString(
NAME_SIZE, raf);
String type = FixedLengthStringIO.readFixedLengthString(
TYPE_SIZE, raf);
String city = FixedLengthStringIO.readFixedLengthString(
CITY_SIZE, raf);
String phone = FixedLengthStringIO.readFixedLengthString(
PHONE_SIZE, raf);
String email = FixedLengthStringIO.readFixedLengthString(
EMAIL_SIZE, raf);
jbtName.setText(name);
jbtType.setText(type);
jbtCity.setText(city);
jbtPhone.setText(phone);
jbtEmail.setText(email);
}
Also instead of adding separate ActionListner command button you can implement like
public class ContactSystem extends JFrame implements ActionListener
{
.....
jbtAdd.addActionListener(this);
jbtFirst.addActionListener(this);
.....
#Override
public void actionPerformed(ActionEvent e) {
String actionCommand = e.getActionCommand();
if(actionCommand.equals("Add")) {
//do add stuff
} else if (actionCommand.equals("First")) {
// move first
}
}
}

Categories