Dynamic Simple Text Editor Java - java

I have modified code from here for my project.
I want to make a editor that have dynamic text area. Each time I press the enter key, a new text area will create. Sorry, I cannot explain more with English.
Please look my code:
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.io.*;
import java.awt.event.*;
import java.util.Hashtable;
public class SimpleEditor extends JFrame {
int count = 0;
private Action openAction = new SimpleEditor.OpenAction();
private Action saveAction = new SimpleEditor.SaveAction();
//private JTextComponent textComp;
private JTextComponent[] textComp2;
//private Hashtable actionHash = new Hashtable();
public static void main(String[] args) {
SimpleEditor editor = new SimpleEditor();
editor.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
editor.setVisible(true);
}
// Create an editor.
public SimpleEditor() {
super("Swing Editor");
//textComp = createTextComponent();
coba();
makeActionsPretty();
Container content = getContentPane();
//content.add(textComp, BorderLayout.CENTER);
for (int i = 0; i < count; i++) {
content.add(textComp2[i], BorderLayout.CENTER);
}
content.add(createToolBar(), BorderLayout.NORTH);
setJMenuBar(createMenuBar());
setSize(320, 240);
}
//coba-coba
protected void coba() {
if (count == 0) {
textComp2 = new JTextComponent[1];
count += 1;
} else {
JTextComponent[] texttemp;
texttemp = new JTextComponent[count];
for (int i = 0; i < count; i++) {
texttemp[i] = createTextComponent();
texttemp[i] = textComp2[i];
}
count += 1;
textComp2 = new JTextComponent[count];
for (int i = 0; i < count - 1; i++) {
textComp2[i] = createTextComponent();
textComp2[i] = texttemp[i];
}
}
}
// Create the JTextComponent subclass.
protected JTextComponent createTextComponent() {
JTextArea ta = new JTextArea();
ta.setFont(new Font("Courier New", Font.PLAIN, 12));
ta.setLineWrap(true);
ta.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent ev) {
taKeyPressed(ev);
}
});
return ta;
}
private void taKeyPressed(java.awt.event.KeyEvent ev) {
if (ev.getKeyCode() == 13) {
coba();
}
}
// Add icons and friendly names to actions we care about.
protected void makeActionsPretty() {
Action a;
/*a = textComp.getActionMap().get(DefaultEditorKit.cutAction);
a.putValue(Action.SMALL_ICON, new ImageIcon("icons/cut.gif"));
a.putValue(Action.NAME, "Cut");
a = textComp.getActionMap().get(DefaultEditorKit.copyAction);
a.putValue(Action.SMALL_ICON, new ImageIcon("icons/copy.gif"));
a.putValue(Action.NAME, "Copy");
a = textComp.getActionMap().get(DefaultEditorKit.pasteAction);
a.putValue(Action.SMALL_ICON, new ImageIcon("icons/paste.gif"));
a.putValue(Action.NAME, "Paste");
a = textComp.getActionMap().get(DefaultEditorKit.selectAllAction);
a.putValue(Action.NAME, "Select All");*/
for (int i = 0; i < count; i++) {
a = textComp2[i].getActionMap().get(DefaultEditorKit.cutAction);
a.putValue(Action.SMALL_ICON, new ImageIcon("icons/cut.gif"));
a.putValue(Action.NAME, "Cut");
a = textComp2[i].getActionMap().get(DefaultEditorKit.copyAction);
a.putValue(Action.SMALL_ICON, new ImageIcon("icons/copy.gif"));
a.putValue(Action.NAME, "Copy");
a = textComp2[i].getActionMap().get(DefaultEditorKit.pasteAction);
a.putValue(Action.SMALL_ICON, new ImageIcon("icons/paste.gif"));
a.putValue(Action.NAME, "Paste");
a = textComp2[i].getActionMap().get(DefaultEditorKit.selectAllAction);
a.putValue(Action.NAME, "Select All");
}
}
// Create a simple JToolBar with some buttons.
protected JToolBar createToolBar() {
JToolBar bar = new JToolBar();
// Add simple actions for opening & saving.
bar.add(getOpenAction()).setText("");
bar.add(getSaveAction()).setText("");
bar.addSeparator();
// Add cut/copy/paste buttons.
/*bar.add(textComp.getActionMap().get(DefaultEditorKit.cutAction)).setText("");
bar.add(textComp.getActionMap().get(
DefaultEditorKit.copyAction)).setText("");
bar.add(textComp.getActionMap().get(
DefaultEditorKit.pasteAction)).setText("");*/
for (int i = 0; i < count; i++) {
bar.add(textComp2[i].getActionMap().get(DefaultEditorKit.cutAction)).setText("");
bar.add(textComp2[i].getActionMap().get(
DefaultEditorKit.copyAction)).setText("");
bar.add(textComp2[i].getActionMap().get(
DefaultEditorKit.pasteAction)).setText("");
}
return bar;
}
// Create a JMenuBar with file & edit menus.
protected JMenuBar createMenuBar() {
JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu("File");
JMenu edit = new JMenu("Edit");
menubar.add(file);
menubar.add(edit);
file.add(getOpenAction());
file.add(getSaveAction());
file.add(new SimpleEditor.ExitAction());
/* edit.add(textComp.getActionMap().get(DefaultEditorKit.cutAction));
edit.add(textComp.getActionMap().get(DefaultEditorKit.copyAction));
edit.add(textComp.getActionMap().get(DefaultEditorKit.pasteAction));
edit.add(textComp.getActionMap().get(DefaultEditorKit.selectAllAction));*/
for (int i = 0; i < count; i++) {
edit.add(textComp2[i].getActionMap().get(DefaultEditorKit.cutAction));
edit.add(textComp2[i].getActionMap().get(DefaultEditorKit.copyAction));
edit.add(textComp2[i].getActionMap().get(DefaultEditorKit.pasteAction));
edit.add(textComp2[i].getActionMap().get(DefaultEditorKit.selectAllAction));
}
return menubar;
}
// Subclass can override to use a different open action.
protected Action getOpenAction() {
return openAction;
}
// Subclass can override to use a different save action.
protected Action getSaveAction() {
return saveAction;
}
//protected JTextComponent getTextComponent() { return textComp; }
// ********** ACTION INNER CLASSES ********** //
// A very simple exit action
public class ExitAction extends AbstractAction {
public ExitAction() {
super("Exit");
}
public void actionPerformed(ActionEvent ev) {
System.exit(0);
}
}
// An action that opens an existing file
class OpenAction extends AbstractAction {
public OpenAction() {
super("Open", new ImageIcon("icons/open.gif"));
}
// Query user for a filename and attempt to open and read the file into the
// text component.
public void actionPerformed(ActionEvent ev) {
JFileChooser chooser = new JFileChooser();
if (chooser.showOpenDialog(SimpleEditor.this)
!= JFileChooser.APPROVE_OPTION) {
return;
}
File file = chooser.getSelectedFile();
if (file == null) {
return;
}
FileReader reader = null;
try {
reader = new FileReader(file);
//textComp.read(reader, null);
for (int i = 0; i < count; i++) {
textComp2[i].read(reader, null);
}
} catch (IOException ex) {
JOptionPane.showMessageDialog(SimpleEditor.this,
"File Not Found", "ERROR", JOptionPane.ERROR_MESSAGE);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException x) {
}
}
}
}
}
// An action that saves the document to a file
class SaveAction extends AbstractAction {
public SaveAction() {
super("Save", new ImageIcon("icons/save.gif"));
}
// Query user for a filename and attempt to open and write the text
// component’s content to the file.
public void actionPerformed(ActionEvent ev) {
JFileChooser chooser = new JFileChooser();
if (chooser.showSaveDialog(SimpleEditor.this)
!= JFileChooser.APPROVE_OPTION) {
return;
}
File file = chooser.getSelectedFile();
if (file == null) {
return;
}
FileWriter writer = null;
try {
writer = new FileWriter(file);
//textComp.write(writer);
for (int i = 0; i < count; i++) {
textComp2[i].write(writer);
}
} catch (IOException ex) {
JOptionPane.showMessageDialog(SimpleEditor.this,
"File Not Saved", "ERROR", JOptionPane.ERROR_MESSAGE);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException x) {
}
}
}
}
}
}
But, my code have some error like this:
Exception in thread "main" java.lang.NullPointerException
- at SimpleEditor.makeActionsPretty(SimpleEditor.java:101)
- at SimpleEditor.<init>(SimpleEditor.java:29)
- at SimpleEditor.main(SimpleEditor.java:19)
Can anybody help me as soon as possible?

The array JTextComponent[] has different sizes at different times, but an object in the array defaults to null until you change it:
textComp2[i] = new JTextField("Hello");

Related

How to connect method from another class to actionListener?

I'm trying to finish my project about searching graphs, where one of the functions is input (vertex and edges) from user.
I already have a method for this in another class, but now I need to put it into GUI.
I've already tried many of tutorials, but nothing worked. Can somebody help me, how to put the method getInputFromCommand to gui?
I've already tried to copy the method into the GUI, but there was problem with the "return g" because of the void result type, I've tried just to call the method, (I know.. stupid) but it didn't work either.
package Process;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Scanner;
public class FindIslands {
String message = "";
int V;
LinkedList<Integer>[] adjListArray;
static LinkedList<String> nodeList = new LinkedList<String>();
// constructor
FindIslands(int V) {
this.V = V;
adjListArray = new LinkedList[V];
for (int i = 0; i < V; i++) {
adjListArray[i] = new LinkedList<Integer>();
}
}
void addEdge(int src, int dest) {
adjListArray[src].add(dest);
adjListArray[dest].add(src);
}
void DFSUtil(int v, boolean[] visited) {
visited[v] = true;
message += getValue(v) + " ";
// System.out.print(getValue(v) + " ");
for (int x : adjListArray[v]) {
if (!visited[x]) {
DFSUtil(x, visited);
}
}
}
void connectedComponents() {
boolean[] visited = new boolean[V];
int count = 0;
message = "";
for (int v = 0; v < V; ++v) {
if (!visited[v]) {
DFSUtil(v, visited);
message += "\n";
// System.out.println();
count++;
}
}
System.out.println("" + count);
System.out.println("");
System.out.println("Vypis ostrovu: ");
String W[] = message.split("\n");
Arrays.sort(W, new java.util.Comparator<String>() {
#Override
public int compare(String s1, String s2) {
// TODO: Argument validation (nullity, length)
return s1.length() - s2.length();// comparison
}
});
for (String string : W) {
System.out.println(string);
}
}
public static void main(String[] args) {
FindIslands g = null; //
String csvFile = "nodefile.txt";
BufferedReader br = null;
String line = "";
int emptyLine = 0;
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
if (line.equals("")) {
emptyLine = 1;
// System.out.println("found blank line");
}
if (emptyLine == 0) {
// System.out.println(line);
nodeList.add(line);
} else if (line.isEmpty()) {
g = new FindIslands(nodeList.size());
} else {
String[] temp = line.split(",");
g.addEdge(getIndex(temp[0]), getIndex(temp[1]));
}
}
} catch (FileNotFoundException e) {
System.out.println("Soubor nenalezen, zadejte data v danem formatu");
g = getInputFromCommand();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Pocet ostrovu");
if (g != null) {
g.connectedComponents();
}
}
public static int getIndex(String str) {
return nodeList.indexOf(str);
}
public static String getValue(int index) {
return nodeList.get(index);
}
public static FindIslands getInputFromCommand() {
FindIslands g = null;
BufferedReader br = null;
String line = "";
int emptyLine = 0;
Scanner scanner = new Scanner(System.in);
line = scanner.nextLine();
while (!line.equals("")) {
if (line.equals("--gui")) {
Guicko gui = new Guicko();
gui.setVisible(true);
} else
nodeList.add(line);
line = scanner.nextLine();
}
g = new FindIslands(nodeList.size());
line = scanner.nextLine();
while (!line.equals("")) {
String[] temp = line.split(",");
if (temp.length != 2) {
System.out.println("spatny format zadanych dat, prosim zkuste znovu");
} else {
g.addEdge(getIndex(temp[0]), getIndex(temp[1]));
}
line = scanner.nextLine();
}
return g;
}
}
Where important is the last method "getInputFromCommand()"
and... gui
package Process;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.util.Scanner;
public class Guicko extends JFrame {
private JButton štartButton;
private JPanel panel;
private JTextField textField2;
private JTextArea textArea1;
public Guicko() {
add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setTitle("Zadej hodnoty");
setSize(500, 400);
textField2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
FindIslands.getInputFromCommand();
}
});
štartButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String str = "asd";
FindIslands g = null;
g.connectedComponents();
textArea1.setText(str);
}
});
}
public static void main (String args[]){
Guicko gui = new Guicko();
gui.setVisible(true);
}
}
I'm sure there are many correct ways this code can be fixed, but in IMHO, your Guicko class needs to have a FindIslands class member, and I think you need to move some stuff from FindIslands.main() into Guicko.main() or some other method.
Then your "Action Listener" inner classes' actionPerformed methods just delegate to the methods in the FindIslands member instance, like this
....
private FindIslands fi;
public Guicko() {
....
textField2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
fi = FindIslands.getInputFromCommand();
}
});
startButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String comps = fi.connectedComponents();// method needs to return a string
textArea1.setText(comps);
}
});
}
The whole idea of seperating GUI from domain is to make changes easily. GUI has knowledge of the domain but domain has no knowledge about the GUI. We can use an interface to seperate them, in that case, Domain says , i don't care who implements this interface but whoever implements this interface will get response and can work with me.
So , If we create a new GUI, we can let it implements that interface and the same domain will work with that GUI.
There are many mistakes but in order to make it work and to show you an example i did few changes.
public class Guicko extends JFrame implements PropertyChangeListener{
private JButton štartButton;
private JPanel panel;
private JTextField textField2;
private JTextArea textArea1;
private FindIslands land;
private JTextField textField;
private JButton button;
public Guicko() {
JPanel panel = new JPanel();
super.getContentPane().setLayout(new GridLayout());
//For each gui, there should be one land.
this.setLand(new FindIslands(100));
//Subscribe to the domain so that you can get update if something change in domain.
this.getLand().subscribe(this);
//Dummy buttons are fields(need too initiate first)
textField2 = new JTextField("",30);
štartButton = new JButton();
textField = new JTextField("",30);
button = new JButton();
button.setPreferredSize(new Dimension(100, 40));
button.setText("Get input from Domain");
štartButton.setPreferredSize(new Dimension(100, 40));
textField.setEditable(false);
štartButton.setText("Start");
panel.add(textField2);
panel.add(štartButton);
panel.add(textField);
panel.add(button);
add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setTitle("Zadej hodnoty");
setSize(500, 400);
//When you type something in , then this function will send it to domain(i mean to function : getInputFromCommand();).
this.addListerToField(štartButton,this.getLand(),textField2);
//Now the second case, suppose you press a button and want something to show up in textfield. In that case , this function will do work.
this.addListerToSecondField(button,this.getLand(),textField);
}
//Here i can catch the events from the domain.
#Override
public void propertyChange(PropertyChangeEvent e) {
if(e.getPropertyName().equals("String changed")) {
this.getTextField().setText((String) e.getNewValue());
}
}
private void addListerToSecondField(JButton button, FindIslands land, JTextField field) {
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
land.requireArgumentsForField();
}
});
}
private void addListerToField(JButton štartButton, FindIslands land, JTextField field) {
štartButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
land.getInputFromCommand(field.getText());
}
});
}
public static void main (String args[]){
Guicko gui = new Guicko();
gui.setVisible(true);
}
public FindIslands getLand() {
return land;
}
public void setLand(FindIslands land) {
this.land = land;
}
public JTextField getTextField() {
return textField;
}
public void setTextField(JTextField textField) {
this.textField = textField;
}
public JButton getButton() {
return button;
}
public void setButton(JButton button) {
this.button = button;
}
Here is the second class. Run it and try to get feeling for it how it works.
public class FindIslands {
String message = "";
int V;
LinkedList<Integer>[] adjListArray;
static LinkedList<String> nodeList = new LinkedList<String>();
// constructor
FindIslands(int V) {
this.V = V;
//initialize the list
this.setListeners(new ArrayList<>());
adjListArray = new LinkedList[V];
for (int i = 0; i < V; i++) {
adjListArray[i] = new LinkedList<Integer>();
}
}
void addEdge(int src, int dest) {
adjListArray[src].add(dest);
adjListArray[dest].add(src);
}
void DFSUtil(int v, boolean[] visited) {
visited[v] = true;
message += getValue(v) + " ";
// System.out.print(getValue(v) + " ");
for (int x : adjListArray[v]) {
if (!visited[x]) {
DFSUtil(x, visited);
}
}
}
void connectedComponents() {
boolean[] visited = new boolean[V];
int count = 0;
message = "";
for (int v = 0; v < V; ++v) {
if (!visited[v]) {
DFSUtil(v, visited);
message += "\n";
// System.out.println();
count++;
}
}
System.out.println("" + count);
System.out.println("");
System.out.println("Vypis ostrovu: ");
String W[] = message.split("\n");
Arrays.sort(W, new java.util.Comparator<String>() {
#Override
public int compare(String s1, String s2) {
// TODO: Argument validation (nullity, length)
return s1.length() - s2.length();// comparison
}
});
for (String string : W) {
System.out.println(string);
}
}
//You need only one main class, not two.----------------------------
/**
public static void main(String[] args) {
FindIslands g = null; //
String csvFile = "nodefile.txt";
BufferedReader br = null;
String line = "";
int emptyLine = 0;
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
if (line.equals("")) {
emptyLine = 1;
// System.out.println("found blank line");
}
if (emptyLine == 0) {
// System.out.println(line);
nodeList.add(line);
} else if (line.isEmpty()) {
g = new FindIslands(nodeList.size());
} else {
String[] temp = line.split(",");
g.addEdge(getIndex(temp[0]), getIndex(temp[1]));
}
}
} catch (FileNotFoundException e) {
System.out.println("Soubor nenalezen, zadejte data v danem formatu");
g = getInputFromCommand();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Pocet ostrovu");
if (g != null) {
g.connectedComponents();
}
}
**/
public static int getIndex(String str) {
return nodeList.indexOf(str);
}
public static String getValue(int index) {
return nodeList.get(index);
}
//Static cases are to be avoided.This is the property of object not class.
public void getInputFromCommand(String string) {
//Here you will recieve a string from the GUI and will be printed in command prompt.You can do whatever you want to do with it.
System.out.println("Recieve string is " + string);
//No idea what you are trying to do.
/** FindIslands g = null;
BufferedReader br = null;
String line = "";
int emptyLine = 0;
Scanner scanner = new Scanner(System.in);
line = scanner.nextLine();
while (!line.equals("")) {
if (line.equals("--gui")) {
Guicko gui = new Guicko();
gui.setVisible(true);
} else
nodeList.add(line);
line = scanner.nextLine();
}
g = new FindIslands(nodeList.size());
line = scanner.nextLine();
while (!line.equals("")) {
String[] temp = line.split(",");
if (temp.length != 2) {
System.out.println("spatny format zadanych dat, prosim zkuste znovu");
} else {
g.addEdge(getIndex(temp[0]), getIndex(temp[1]));
}
line = scanner.nextLine();
}
return line;**/
}
//This function is triggered with second button and you can send data to gui as shown below.
public void requireArgumentsForField() {
//Suppose i want to send following string.
String name = "I don't know";
this.getListeners().stream().forEach(e -> {
// I will catch this in view.
e.propertyChange(new PropertyChangeEvent(this, "String changed", null, name));
});
}
private ArrayList<PropertyChangeListener> listeners;
//Let the objects subscibe. You need this to publish the changes in domain.
public void subscribe(PropertyChangeListener listener) {
this.getListeners().add(listener);
}
public ArrayList<PropertyChangeListener> getListeners() {
return listeners;
}
public void setListeners(ArrayList<PropertyChangeListener> listeners) {
this.listeners = listeners;
}

how to detect what user my program is in in java

I am working on a word processor and i need to know what user my program is in so that my program can auto detect it on start and save the files in their my Documents. Im using java. and i have no precode for the directory detect. but in case this helps here is my code:
import javax.swing.*;
import java.io.*;
import java.awt.event.*;
import java.util.*;
#SuppressWarnings("serial")
class Word1 extends JFrame implements ActionListener, KeyListener{
ClassLoader Idr = this.getClass().getClassLoader();
static JPanel pnl = new JPanel();
public static JTextField Title = new JTextField("Document",25);
static JTextArea Body = new JTextArea("Body", 48, 68);
public static JScrollPane pane = new JScrollPane(Body);
JTextField textField = new JTextField();
JButton saveButton = new JButton("Save File");
JButton editButton = new JButton("Edit File");
JButton deleteButton = new JButton("Delete");
public static String Input = "";
public static String Input2 = "";
public static String Text = "";
public static void main(String[] args){
#SuppressWarnings("unused")
Word1 gui = new Word1();
}
public void ListB(){
// Directory path here
String username = JOptionPane.showInputDialog(getContentPane(), "File to Delete", "New ", JOptionPane.PLAIN_MESSAGE);
String path = "C:\\Users\\"+username+"\\Documents\\";
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
String files = listOfFiles[i].getName();
if (files.endsWith(".txt") || files.endsWith(".TXT")){
ArrayList<String> doclist = new ArrayList<String>();
doclist.add(files);
System.out.print(doclist);
String l = doclist.get(i);
}
}
}
}
public Word1()
{
ListB();
setTitle("Ledbetter Word");
setSize(800, 850);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
add(pnl);
Body.setLineWrap(true);
Body.setWrapStyleWord(true);
Body.setEditable(true);
Title.setEditable(true);
Title.addKeyListener(keyListen2);
saveButton.addActionListener(this);
editButton.addActionListener(len);
deleteButton.addActionListener(len2);
pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
Body.addKeyListener(keyListen);
pnl.add(saveButton);
pnl.add(editButton);
pnl.add(deleteButton);
pnl.add(Title);
pnl.add(pane);
setVisible(true);
}
KeyListener keyListen = new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
#SuppressWarnings("unused")
char keyText = e.getKeyChar();
}
#Override
public void keyPressed(KeyEvent e) {
}//ignore
#Override
public void keyReleased(KeyEvent e) {
Word1.Input = Body.getText();
}//ignore
};
KeyListener keyListen2 = new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
#SuppressWarnings("unused")
char keyText = e.getKeyChar();
}
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
Word1.Input2 = Title.getText();
}
};
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}
#Override
public void actionPerformed(ActionEvent e) {
if( e.getSource() == saveButton ){
try {
BufferedWriter fileOut = new BufferedWriter(new FileWriter("C:\\Users\\David\\Documents\\"+Title.getText()+".txt"));
fileOut.write(Word1.Input);
fileOut.close();
JOptionPane.showMessageDialog(getParent(), "Successfully saved to your documents", "Save", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException ECX) {
JOptionPane.showMessageDialog(getParent(), "There was an error saving your file", "Save-Error", JOptionPane.ERROR_MESSAGE);
}
}
}
ActionListener len = new ActionListener(){
#SuppressWarnings({ "resource" })
public void actionPerformed(ActionEvent e){
if(e.getSource() == editButton);{
String filename = JOptionPane.showInputDialog(getParent(), "File to Delete", "Deletion", JOptionPane.PLAIN_MESSAGE);
Word1.Body.setText("");
try{
FileReader file = new FileReader(filename+".txt");
BufferedReader reader = new BufferedReader(file);
String Text = "";
while ((Text = reader.readLine())!= null )
{
Word1.Body.append(Text+"\n");
}
Word1.Title.setText(filename);
} catch (IOException e2) {
JOptionPane.showMessageDialog(getParent(), "Open File Error\nFile may not exist", "Error!", JOptionPane.ERROR_MESSAGE);
}
}
}
};
ActionListener len2 = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == deleteButton);{
String n = JOptionPane.showInputDialog(getParent(), "File to Delete", "Deletion", JOptionPane.PLAIN_MESSAGE);
Delete(new File(n+".txt"));
}
}
};
public void Delete(File Files){
Files.delete();
}
}
Assuming you are targeting windows (My Documents hint) you can try this.
String myDocumentsPath = System.getProperty("user.home") + "/Documents";

cannot update in panel when i choose a file path

once a user selects the button "CLICK HERE TO UPLOAD", the3 file path is stored into a file, and these paths are read into an arraylist, which is shown on the JPanel. the problem is that once a file is selected, it is never updated automatically on the JPanel, unless the application is re runed, before the up to date number of information is displayed. How can this problem be rectified, because i have no clue where i have gone wrong. By the way the arraylists gets updated on runtime but the JPanel never gets updated.
public class Media2 extends JPanel {
private JPanel video_pnl, control_pnl;
private JButton play_btn;
private JLabel loc_lbl;
private int increment;
ArrayList<String> file_location;
ArrayList<JButton> button_lists;
private FileWriter file_writer;
private BufferedWriter buffered_writer;
private JFileChooser filechooser;
private File file;
private JButton btn_upload;
private BufferedReader br;
private FileReader fr;
public Media2(ArrayList<String> file_location) throws IOException {
btn_upload = new JButton("Click here to Upload Video");
String file_path = "C:\\Users\\goldAnthony\\Documents\\NetBeansProjects\\VDMS\\src\\VideoInfos.txt";
file = new File(file_path);
if (!file.exists()) {
file.createNewFile();
file_writer = new FileWriter(file.getAbsolutePath());
} else {
file_writer = new FileWriter(file.getAbsolutePath(), true);
}
add(btn_upload);
Handlers handler = new Handlers();
btn_upload.addActionListener(handler);
this.file_location = file_location;
readFile(file_location, file_path);
}
private void readFile(ArrayList<String> file_location, String file_path) throws FileNotFoundException, IOException {
fr = new FileReader(file_path);
br = new BufferedReader(fr);
String text = "";
String line2;
line2 = br.readLine();
while (line2 != null) {
int i = 0;
file_location.add(i, line2);
line2 = br.readLine();
i++;
}
configurePanel(file_location);
//System.out.print(file_location.size() + "in the read file 1");
}
private void configurePanel(ArrayList<String> file_location) {
increment = 0;
while (increment < file_location.size()) {
video_pnl = new JPanel();
video_pnl.setLayout(new BoxLayout(video_pnl, BoxLayout.Y_AXIS));
loc_lbl = new JLabel();
loc_lbl.setText(file_location.get(increment));
control_pnl = new JPanel();
control_pnl.setLayout(new FlowLayout(FlowLayout.CENTER));
video_pnl.add(loc_lbl);
control_pnl.add(createButton(increment));
video_pnl.add(control_pnl, BorderLayout.SOUTH);
video_pnl.revalidate();
add(video_pnl);
increment++;
}
}
private JButton createButton(final int i) {
play_btn = new JButton("Play");
play_btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// System.out.println(file_location.get(i));
play(i);
}
});
return play_btn;
}
public void play(int i) {
System.out.println(file_location.get(i));
}
private class Handlers implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btn_upload) {
try { //display the image in jlabel
file = new File("C:\\Users\\goldAnthony\\Documents\\NetBeansProjects\\VDMS\\src\\VideoInfos.txt");
if (!file.exists()) {
file.createNewFile();
file_writer = new FileWriter(file.getAbsolutePath());
} else {
file_writer = new FileWriter(file.getAbsolutePath(), true);
}
buffered_writer = new BufferedWriter(file_writer);
//creating a file chooser
filechooser = new JFileChooser();
filechooser.setDialogTitle("Choose Your Video");
// //below codes for select the file
int returnval = filechooser.showOpenDialog(null);
if (returnval == JFileChooser.APPROVE_OPTION) {
file = filechooser.getSelectedFile();
String filename = file.getAbsolutePath();
buffered_writer.write(filename);
buffered_writer.newLine();
buffered_writer.close();
}
} catch (IOException | HeadlessException ex) {
System.out.println(ex.getMessage());
}
}
}
}
public static void main(String[] args) throws IOException {
//Declare and initialize local variables
ArrayList<String> file_location = new ArrayList<>();
//creates instances of the VlcPlayer object, pass the mediaPath and invokes the method "run"
Media2 mediaplayer = new Media2(file_location);
JFrame ourframe = new JFrame();
ourframe.setContentPane(mediaplayer);
ourframe.setLayout(new GridLayout(5, 1));
ourframe.setSize(300, 560);
ourframe.setVisible(true);
ourframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
When you add components to a visible GUI the basic code is:
panel.add(...);
panel.revalidate();
panel.repaint();
You are revalidating the wrong panel:
video_pnl.revalidate(); // wrong panel
add(video_pnl);
You should be doing:
//video_pnl.revalidate();
add(video_pnl);
revalidate();
repaint();
Your code needs some changes, try:
private void configurePanel(ArrayList<String> file_location) {
increment = 0;
while (increment < file_location.size()) {
addEntry(file_location.get(increment));//--------->New line
increment++;
}
}
private void addEntry(String location) {//--------->New constructor
video_pnl = new JPanel();
video_pnl.setLayout(new BoxLayout(video_pnl, BoxLayout.Y_AXIS));
loc_lbl = new JLabel();
loc_lbl.setText(location);
control_pnl = new JPanel();
control_pnl.setLayout(new FlowLayout(FlowLayout.CENTER));
video_pnl.add(loc_lbl);
control_pnl.add(createButton(increment));
video_pnl.add(control_pnl, BorderLayout.SOUTH);
video_pnl.revalidate();
add(video_pnl);
}
and:
private class Handlers implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btn_upload) {
try { //display the image in jlabel
file = new File("C:\\VideoInfos.txt");
if (!file.exists()) {
file.createNewFile();
file_writer = new FileWriter(file.getAbsolutePath());
} else {
file_writer = new FileWriter(file.getAbsolutePath(), true);
}
buffered_writer = new BufferedWriter(file_writer);
//creating a file chooser
filechooser = new JFileChooser();
filechooser.setDialogTitle("Choose Your Video");
// //below codes for select the file
int returnval = filechooser.showOpenDialog(null);
if (returnval == JFileChooser.APPROVE_OPTION) {
file = filechooser.getSelectedFile();
String filename = file.getAbsolutePath();
buffered_writer.newLine();
buffered_writer.write(filename);
buffered_writer.newLine();
buffered_writer.close();
addEntry(filename);//---------------->New Line
validate();//------------>New Line
}
} catch (IOException | HeadlessException ex) {
System.out.println(ex.getMessage());
}
}
}
}
Now it's working. You have to make further changes, of course :)

JPanel elements are not appearing

I'm using the Swing library to ask a user for their zipcode, but all that is appearing is a box, without the text box, or any of the other elements that I've added in (see code). Also, you likely need to know that I'm trying to get the int AskZip() in my public static void main(String[] args) method.
private static int zip;
public static int AskZip() {
JFrame zaWindow = new JFrame("What Zipcode");
zaWindow.setSize(200, 300);
JPanel jp = new JPanel();
final JTextField tf = new JTextField("Enter Zip Here");
JLabel label = new JLabel();
JButton button = new JButton("Get Weather");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String sZip = tf.getText();
int rZip = 0;
try {
if (sZip.length() != 5) {
JOptionPane.showMessageDialog(null, "Invalid zipcode!", "Error", JOptionPane.ERROR_MESSAGE);
} else {
rZip = Integer.parseInt(sZip);
}
} catch (NumberFormatException arg) {
JOptionPane.showMessageDialog(null, "Invalid zipcode!", "Error", JOptionPane.ERROR_MESSAGE);
}
zip = rZip;
}
});
label.setText("What is your zipcode?");
jp.add(label);
jp.add(tf);
jp.add(button);
zaWindow.add(jp);
return zip;
}
JFrame zaWindow..
This should be a modal dialog or a JOptionPane. E.G. This country has 3 states, each with 10 postcodes.
import java.awt.*;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.event.ChangeListener;
class ZipQuery {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
ZipNumberModel znm = new ZipNumberModel();
JSpinner zip = new JSpinner(znm);
JOptionPane.showMessageDialog(null, zip, "Enter Zipcode", JOptionPane.QUESTION_MESSAGE);
System.out.println("User chose " + znm.getValue());
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
class ZipNumberModel extends SpinnerNumberModel {
private ArrayList<Integer> zipCodes;
private int index = 0;
ZipNumberModel() {
zipCodes = new ArrayList<Integer>();
int zip = 10000;
for (int jj = 1; jj < 4; jj++) {
for (int ii = jj * zip; ii < jj * zip + 10; ii++) {
zipCodes.add(new Integer(ii));
}
}
}
#Override
public Object getValue() {
return zipCodes.get(index);
}
#Override
public Object getNextValue() {
if (index < zipCodes.size()-1) {
index++;
} else {
index = 0;
}
return zipCodes.get(index);
}
#Override
public Object getPreviousValue() {
if (index > 0) {
index--;
} else {
index = zipCodes.size()-1;
}
return zipCodes.get(index);
}
}

Need to identify SwingWorker completion to stop the current process?

My aim is to select all the files named with MANI.txt which is present in their respective folders and then load path of the MANI.txt files different location in table. After I load the path in the table,I used to select needed path and modifiying those.
To load the MANI.txt files taking more time,because it may present more than 30 times in my workspace or etc. until load the files I want to give alarm to the user with help of ProgessBar.Once the list size has been populated I need to disable ProgressBar.
i came up with this ProgressBar, but progress bar operation gets complete or not, if the background process(finding files and putting their path in the table) got completed means, the result getting displayed and hiding the progress bar? i want the presence of progress bar opertion gets complete 100% in either case? please give me some ideas?how to implement it?
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class JTableHeaderCheckBox extends JFrame implements ActionListener {
protected int counter = 0;
Object colNames[] = { "", "Path" };
Object[][] data = {};
DefaultTableModel dtm;
JTable table;
JButton but;
java.util.List list;
File folder;
JProgressBar current;
JFrame fr1, frame;
int num = 0;
JProgressBar pbar;
JTableHeaderCheckBox it;
public void buildGUI() throws InterruptedException {
dtm = new DefaultTableModel(data, colNames);
table = new JTable(dtm);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
int vColIndex = 0;
TableColumn col = table.getColumnModel().getColumn(vColIndex);
int width = 10;
col.setPreferredWidth(width);
int vColIndex1 = 1;
TableColumn col1 = table.getColumnModel().getColumn(vColIndex1);
int width1 = 500;
col1.setPreferredWidth(width1);
JFileChooser chooser = new JFileChooser();
// chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("Choose workSpace Path");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
{
}
String path = chooser.getSelectedFile().getAbsolutePath();
folder = new File(path);
but = new JButton("REMOVE");
SwingWorker worker = new SwingWorker() {
#Override
public Object doInBackground() {
GatheringFiles ob = new GatheringFiles();
list = ob.returnlist(folder);
return list;
}
#Override
protected void done() {
// java.util.List list = (java.util.List)get();
for (int x = 0; x < list.size(); x++) {
dtm.addRow(new Object[] { new Boolean(false),
list.get(x).toString() });
}
try {
JPanel pan = new JPanel();
JScrollPane sp = new JScrollPane(table);
TableColumn tc = table.getColumnModel().getColumn(0);
tc.setCellEditor(table.getDefaultEditor(Boolean.class));
tc.setCellRenderer(table.getDefaultRenderer(Boolean.class));
tc.setHeaderRenderer(new CheckBoxHeader(
new MyItemListener()));
JFrame f = new JFrame();
pan.add(sp);
pan.add(but);
f.add(pan);
f.setSize(700, 100);
f.pack();
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
if (list.size() >= 0) {
// hide the progress bar
frame.hide();
}
} catch (Exception ex) {
}
}
};
worker.execute();
but.addActionListener(this);
//calling progressbar
if(!path.isEmpty())
{
SwingProgressBar();
}
}
public void SwingProgressBar() {
UIManager.put("ProgressBar.selectionBackground", Color.black);
UIManager.put("ProgressBar.selectionForeground", Color.white);
UIManager.put("ProgressBar.foreground", new Color(8, 32, 128));
pbar = new JProgressBar();
pbar.setMinimum(0);
pbar.setMaximum(100);
pbar.setForeground(Color.RED);
pbar.setStringPainted(true);
it = new JTableHeaderCheckBox();
frame = new JFrame("Loading");
final JLabel lb = new JLabel("0");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// frame.setContentPane(it);
frame.add(pbar);
frame.pack();
frame.setVisible(true);
counter = 0;
Thread runner = new Thread() {
public void run() {
counter = 0;
while (counter <= 99) {
Runnable runme = new Runnable() {
public void run() {
pbar.setValue(counter);
}
};
SwingUtilities.invokeLater(runme);
counter++;
try {
Thread.sleep(1000);
} catch (Exception ex) {
}
}
}
};
runner.start();
}
public void updateBar(int newValue) {
pbar.setValue(newValue);
}
class MyItemListener implements ItemListener {
public void itemStateChanged(ItemEvent e) {
Object source = e.getSource();
if (source instanceof AbstractButton == false)
return;
boolean checked = e.getStateChange() == ItemEvent.SELECTED;
for (int x = 0, y = table.getRowCount(); x < y; x++) {
table.setValueAt(new Boolean(checked), x, 0);
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
new JTableHeaderCheckBox().buildGUI();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
} catch (Exception ex) {
}
}
});
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (e.getSource() == but) {
System.err.println("table.getRowCount()" + table.getRowCount());
for (int x = 0, y = table.getRowCount(); x < y; x++) {
if ("true".equals(table.getValueAt(x, 0).toString())) {
System.err.println(table.getValueAt(x, 0));
System.err.println(list.get(x).toString());
delete(list.get(x).toString());
}
}
}
}
public void delete(String a) {
String delete = "C:";
System.err.println(a);
try {
File inFile = new File(a);
if (!inFile.isFile()) {
return;
}
// Construct the new file that will later be renamed to the // filename.
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader br = new BufferedReader(new FileReader(inFile));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
// Read from the original file and write to the new
// unless content matches data to be removed.
while ((line = br.readLine()) != null) {
System.err.println(line);
line = line.replace(delete, " ");
pw.println(line);
pw.flush();
}
pw.close();
br.close();
// Delete the original file
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}
// Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile))
System.out.println("Could not rename file");
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
class CheckBoxHeader extends JCheckBox implements TableCellRenderer,
MouseListener {
protected CheckBoxHeader rendererComponent;
protected int column;
protected boolean mousePressed = false;
public CheckBoxHeader(ItemListener itemListener) {
rendererComponent = this;
rendererComponent.addItemListener(itemListener);
}
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (table != null) {
JTableHeader header = table.getTableHeader();
if (header != null) {
rendererComponent.setForeground(header.getForeground());
rendererComponent.setBackground(header.getBackground());
rendererComponent.setFont(header.getFont());
header.addMouseListener(rendererComponent);
}
}
setColumn(column);
rendererComponent.setText("Check All");
setBorder(UIManager.getBorder("TableHeader.cellBorder"));
return rendererComponent;
}
protected void setColumn(int column) {
this.column = column;
}
public int getColumn() {
return column;
}
protected void handleClickEvent(MouseEvent e) {
if (mousePressed) {
mousePressed = false;
JTableHeader header = (JTableHeader) (e.getSource());
JTable tableView = header.getTable();
TableColumnModel columnModel = tableView.getColumnModel();
int viewColumn = columnModel.getColumnIndexAtX(e.getX());
int column = tableView.convertColumnIndexToModel(viewColumn);
if (viewColumn == this.column && e.getClickCount() == 1
&& column != -1) {
doClick();
}
}
}
public void mouseClicked(MouseEvent e) {
handleClickEvent(e);
((JTableHeader) e.getSource()).repaint();
}
public void mousePressed(MouseEvent e) {
mousePressed = true;
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
}
//
import java.io.File;
import java.util.*;
public class GatheringFiles {
public static List returnlist(File folder)
{
List<File> list = new ArrayList<File>();
List<File> list1 = new ArrayList<File>();
getFiles(folder, list);
return list;
}
private static void getFiles(File folder, List<File> list) {
folder.setReadOnly();
File[] files = folder.listFiles();
for(int j = 0; j < files.length; j++) {
if( "MANI.txt".equals(files[j].getName()))
{
list.add(files[j]);
}
if(files[j].isDirectory())
getFiles(files[j], list);
}
}
}

Categories