I've code like this:
public main() {
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(700, 500);
//tabbed pane
add(tb);
}
public JTextArea txtArea() {
JTextArea area = new JTextArea();
String st = String.valueOf(tab);
area.setName(st);
return area;
}
public static void main (String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new main();
}
});
}
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if(source==mnew) {
tab++;
tb.add("Untitled-"+tab,new JPanel().add(txtArea()));
int s = tb.getSelectedIndex();
s = tb.getTabCount()-1;
tb.setSelectedIndex(s);
}
if(source==save) {
int s = tb.getSelectedIndex()+1;
}
Every click on the "New" menu item, code creates new tab with new panel and textarea (it's similar to a lot of text editors like notepad++).
After clicked "Save" in menu bar I want to get text from focused jtextarea.
Please help.
Add a document listener to the text area.
public JTextArea txtArea() {
JTextArea area = new JTextArea();
tstDocumentListener dcL = new tstDocumentListener();
area.getDocument().addDocumentListener(dcL);
String st = String.valueOf(tab);
area.setName(st);
return area;
}
tstDocumentListener
public class tstDocumentListener implements DocumentListener
{
public void changedUpdate(DocumentEvent e) {}
public void removeUpdate(DocumentEvent e)
{
String newString = "";
int lengthMe = e.getDocument().getLength();
try
{
newString = e.getDocument().getText(0,lengthMe);
System.out.println(newString);
}
catch(Exception exp)
{
System.out.println("Error");
}
}
public void insertUpdate(DocumentEvent e)
{
String newString = "";
int lengthMe = e.getDocument().getLength();
try
{
newString = e.getDocument().getText(0,lengthMe);
System.out.println(newString);
}
catch(Exception exp)
{
System.out.println("Error");
}
}
}
Edit
As for getting the text when you gain or lose focus on the text area
public JTextArea txtArea() {
JTextArea area = new JTextArea();
CustomFocusListener cFL = new CustomFocusListener();
area.addFocusListener(cFL);
String st = String.valueOf(tab);
area.setName(st);
return area;
}
CustomFocusListener
public class CustomFocusListener implements FocusListener
{
#Override
public void focusGained(FocusEvent e)
{
String parseMe = "";
JTextArea src;
try
{
src = (JTextArea)e.getSource();
parseMe = src.getText();
System.out.println(parseMe);
}
catch (ClassCastException ignored)
{
}
}
#Override
public void focusLost(FocusEvent e)
{
String parseMe = "";
JTextArea src;
try
{
src = (JTextArea)e.getSource();
parseMe = src.getText();
System.out.println(parseMe);
}
catch (ClassCastException ignored)
{
}
}
}
Related
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;
}
I am developing a messaging application with sockets. I have an initial JFrame that allows the user to choose a contact to connect to, and lets them choose if they'd like to be the client or the server. When they make this choice, it calls a method in which creates the chat window frame, and also uses a SwingWorker to initialise a connection, create an action listner on the send buton of the chat window so that it sends messages when pressed, and creates a SocketListener that is always listening while the window is open.
This works just fine, however if I close the chat window and then reopen it by choosing server or client again, nothing happens - the frame loads up however I cannot send any messages on it.
I'm not sure what the problem is here, could it be that i'm not disposing of the swing worker or the frame properly? Any help would be greatly appreciated and apologies for my lack of knowledge.
Here is the relevent code for this:
public static void server() {
JButton server = new JButton();
server.setText("Server");
server.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String name = nameChoice;
String ip = ipChoice;
String port = portChoice;
try {
server2(port);
} catch (IOException e1) {
e1.printStackTrace();
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
panel.add(server);
}
public static void server2(String port) throws Exception {
gui.frame();
SwingWorker worker = new SwingWorker() {
#Override
protected Void doInBackground() throws Exception {
sockets.serverSetup(port);
gui.sendButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String msg = gui.newMsg.getText();
gui.newMsg.setText(null);
try {
sockets.sendMsg(msg);
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
while(gui.open==true) {
sockets.receiveMsg();
}
sockets.closeConnection();
System.out.println("Closed");
return null;
}
};
worker.execute();
}
network
package com.company;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Vector;
public class network {
static ServerSocket s;
static Socket s1;
static OutputStream s1out;
static DataOutputStream dos;
static InputStream s1in;
static chatWindowScreen gui = new chatWindowScreen();
static String st;
public static Vector sentVec = new Vector();
public static Vector receivedVec = new Vector();
public static Vector messages = new Vector();
public static void serverSetup(String port) throws IOException {
System.out.println("Test");
int portInt = Integer.parseInt(port);
s = new ServerSocket(portInt);
s1 = s.accept();
System.out.println("Server set up");
//sendMsg("Hi");
}
public static void clientSetup(String port, String ip) throws IOException {
System.out.println("Test");
int portInt = Integer.parseInt(port);
s1 = new Socket(ip, portInt);
System.out.println("Client set up");
//receiveMsg();
}
public static void closeConnection() throws IOException {
dos.close();
s1out.close();
s1.close();
}
public static void sendMsg(String message) throws IOException {
System.out.println("Test");
s1out = s1.getOutputStream();
dos = new DataOutputStream(s1out);
dos.writeUTF(message);
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String t1 = sdf.format(cal.getTime());
message = t1 + " - " + message;
sentVec.add(message);
receivedVec.add("");
messages.add(message);
gui.sent.setText("Sent \n");
for (int i = 0; i < sentVec.size(); i++) {
gui.sent.append(sentVec.get(i) + "\n");
}
gui.received.setText("Received \n");
for (int i = 0; i < receivedVec.size(); i++) {
gui.received.append(receivedVec.get(i) + "\n");
}
System.out.println("complete");
}
public static void receiveMsg() throws IOException {
System.out.println("Test");
s1in = s1.getInputStream();
DataInputStream dis = new DataInputStream(s1in);
st = (dis.readUTF());
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String t1 = sdf.format(cal.getTime());
st = t1 + " - " + st;
receivedVec.add(st);
sentVec.add("");
messages.add(st);
gui.received.setText("Received \n");
for (int i = 0; i < receivedVec.size(); i++) {
gui.received.append((String) receivedVec.get(i) + "\n");
}
gui.sent.setText("Sent \n");
for (int i = 0; i < sentVec.size(); i++) {
gui.sent.append((String) sentVec.get(i) + "\n");
}
}
public static Vector getSentVec() {
return sentVec;
}
public static Vector getReceivedVec() {
return receivedVec;
}
}
chatWindowScreen
package com.company;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.IOException;
import java.util.Vector;
public class chatWindowScreen {
static JFrame frame = new JFrame();
static JPanel panel = new JPanel();
static JTextArea sent;
static JTextArea received;
static JTextArea newMsg;
static JButton sendButton;
public static String msg;
static boolean open = true;
static network sockets = new network();
public static boolean close = false;
public void frame() throws Exception {
System.out.println("GUI opened");
frame.setTitle("Messaging Application");
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.addWindowListener(new WindowListener() {
#Override
public void windowOpened(WindowEvent e) {
}
#Override
public void windowClosing(WindowEvent e) {
}
#Override
public void windowClosed(WindowEvent e) {
System.out.println("Closed");
panel.removeAll();
open=false;
}
#Override
public void windowIconified(WindowEvent e) {
}
#Override
public void windowDeiconified(WindowEvent e) {
}
#Override
public void windowActivated(WindowEvent e) {
}
#Override
public void windowDeactivated(WindowEvent e) {
}
});
sentMsg();
receivedMsg();
msgBox();
sendBtn();
save();
frame.add(panel);
frame.setVisible(true);
}
public static void sentMsg() {
sent = new JTextArea(15, 20);
sent.setText("Sent" + "\n");
sent.setLineWrap(true);
sent.setEditable(false);
JScrollPane pane = new JScrollPane(sent, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
panel.add(pane);
}
public static void receivedMsg() {
received = new JTextArea(15, 20);
received.setText("Received" + "\n");
received.setEditable(false);
received.setLineWrap(true);
JScrollPane pane1 = new JScrollPane(received, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
panel.add(pane1);
}
public static void msgBox() {
newMsg = new JTextArea(1, 15);
newMsg.setText("");
newMsg.setLineWrap(true);
JScrollPane pane2 = new JScrollPane(newMsg, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
panel.add(pane2);
}
public static void sendBtn() {
sendButton = new JButton();
sendButton.setText("Send!");
/*sendButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
msg = newMsg.getText();
newMsg.setText(null);
SwingWorker worker = new SwingWorker() {
#Override
protected Object doInBackground() throws Exception {
sockets.sendMsg(msg);
return null;
}
};
worker.execute();
try {
sockets.sendMsg(msg);
} catch (IOException e1) {
e1.printStackTrace();
}
msg = null;
}
});*/
panel.add(sendButton);
}
public static void save(){
JButton save = new JButton();
save.setText("Save Conversation");
save.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
saveToFile save = new saveToFile();
}
});
panel.add(save);
}
}
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";
I made an application, which got quite alot textfields, which clear text on focus. When i run the application, the application works abolutely fine. Then, i made a menu, which give me a choice to open the application, or open the txt my FileWriter wrote. Now, when i run application using menu, it focuses on the first textfield. How do i make the menu run the application without focus on first textfield?? as i said, when i run application without menu, it doesnt focus.. hope u can help!
Best Regards, Oliver.
Menu:
public class menu extends JFrame{
private JFrame fr;
private JButton b1;
private JButton b2;
private JPanel pa;
public static void main(String[] args){
new menu();
}
public menu(){
gui();
}
public void gui(){
fr = new JFrame("menu");
fr.setVisible(true);
fr.setSize(200,63);
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fr.setLocationRelativeTo(null);
pa = new JPanel(new GridLayout(1,2));
b1 = new JButton("Infostore");
b2 = new JButton("log");
pa.add(b1);
pa.add(b2);
fr.add(pa);
Eventhandler eh = new Eventhandler();
b1.addActionListener(eh);
b2.addActionListener(eh);
}
private class Eventhandler implements ActionListener{
public void actionPerformed(ActionEvent event){
if(event.getSource()==b1){
IS is = new IS();
fr.setVisible(false);
}
if(event.getSource()==b2){
try{
Runtime.getRuntime().exec("C:\\Windows\\System32\\notepad C:\\Applications\\Infostore.txt");
}catch(IOException ex){
ex.printStackTrace();
}
System.exit(1);
}
}
}
}
Application:
public class IS extends JFrame{
private JLabel fname;
private JTextField name;
private JTextField lname;
private JLabel birth;
private JTextField date;
private JTextField month;
private JTextField year;
private JTextField age;
private JButton cont;
private JLabel lcon;
private JTextField email;
private JTextField numb;
String inumb;
int[] check = {0,0,0,0,0,0,0};
int sum=0;
private JPanel p;
private JFrame f;
public static void main(String[] args){
new IS();
}
public IS(){
gui();
}
public void gui(){
f = new JFrame("Infostore");
f.setVisible(true);
f.setSize(200,340);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);
p = new JPanel();
fname = new JLabel("Name ");
name = new JTextField("Name",12);
lname = new JTextField("Last name",12);
birth = new JLabel("Birthday");
date = new JTextField("Date",12);
month = new JTextField("Month",12);
year = new JTextField("Year",12);
age = new JTextField("Your age",12);
lcon = new JLabel("Contact");
email = new JTextField("E-mail",12);
numb = new JTextField("Phone (optional)",12);
cont = new JButton("Store Information");
p.add(fname);
p.add(name);
p.add(lname);
p.add(birth);
p.add(date);
p.add(month);
p.add(year);
p.add(age);
p.add(lcon);
p.add(email);
p.add(numb);
p.add(cont);
f.add(p);
f.setVisible(true);
name.addFocusListener(new FocusListener(){
public void focusGained(FocusEvent e) {
String jname = name.getText();
if(jname.equalsIgnoreCase("name")){
name.setText("");
}
}
public void focusLost(FocusEvent e) {
String jname = name.getText();
if(jname.equals("")){
name.setText("Name");
check[0] = 0;
}else{
check[0] = 1;
}
}});
lname.addFocusListener(new FocusListener(){
public void focusGained(FocusEvent e) {
String jlname = lname.getText();
if(jlname.equalsIgnoreCase("last name")){
lname.setText("");
}
}
public void focusLost(FocusEvent e) {
String jlname = lname.getText();
if(jlname.equals("")){
lname.setText("Last name");
check[1] = 0;
}else{
check[1] = 1;
}
}});
date.addFocusListener(new FocusListener(){
public void focusGained(FocusEvent e) {
String jdate = date.getText();
if(jdate.equalsIgnoreCase("date")){
date.setText("");
}
}
public void focusLost(FocusEvent e) {
String jdate = date.getText();
if(jdate.equals("")){
date.setText("Date");
check[2] = 0;
}else{
check[2] = 1;
}
}});
month.addFocusListener(new FocusListener(){
public void focusGained(FocusEvent e) {
String jmonth = month.getText();
if(jmonth.equalsIgnoreCase("month")){
month.setText("");
}
}
public void focusLost(FocusEvent e) {
String jmonth = month.getText();
if(jmonth.equals("")){
month.setText("Month");
check[3] = 0;
}else{
check[3]=1;
}
}});
year.addFocusListener(new FocusListener(){
public void focusGained(FocusEvent e) {
String jyear = year.getText();
if(jyear.equalsIgnoreCase("year")){
year.setText("");
}
}
public void focusLost(FocusEvent e) {
String jyear = year.getText();
if(jyear.equals("")){
year.setText("Year");
check[4] = 0;
}else{
check[4] = 1;
}
}});
age.addFocusListener(new FocusListener(){
public void focusGained(FocusEvent e) {
String jage = age.getText();
if(jage.equalsIgnoreCase("your age")){
age.setText("");
}
}
public void focusLost(FocusEvent e) {
String jage = age.getText();
if(jage.equals("")){
age.setText("Your age");
check[5] = 0;
}else{
check[5] = 1;
}
}});
email.addFocusListener(new FocusListener(){
public void focusGained(FocusEvent e) {
String jemail = email.getText();
if(jemail.equalsIgnoreCase("e-mail")){
email.setText("");
}
}
public void focusLost(FocusEvent e) {
String jemail = email.getText();
if(jemail.equals("")){
email.setText("E-mail");
check[6]=0;
}else{
check[6]=1;
}
}});
numb.addFocusListener(new FocusListener(){
public void focusGained(FocusEvent e) {
String jnumb = numb.getText();
if(jnumb.equalsIgnoreCase("phone (optional)")){
numb.setText("");
}
}
public void focusLost(FocusEvent e) {
String jnumb = numb.getText();
if(jnumb.equals("")){
numb.setText("Phone (optional)");
}else{
}
}
});
eventh eh = new eventh();
cont.addActionListener(eh);
}
private class eventh implements ActionListener{
public void actionPerformed(ActionEvent event){
sum = check[0] + check[1] + check[2] + check[3] + check[4] + check[5] + check[6];
if(event.getSource()==cont&&sum==7){
String sname = name.getText();
String slname = lname.getText();
String sdate = date.getText();
String smonth = month.getText();
String syear = year.getText();
String sage = age.getText();
String semail = email.getText();
String snumb = numb.getText();
if(snumb.equalsIgnoreCase("Phone (optional)")){
numb.setText("");
}
String inumb = ("Phone: "+numb.getText());
String info = ("Name: "+sname+" "+slname+" "+"Birthday: "+sdate+"-"+smonth+"-"+syear+" "+" Age:"+sage+" "+"E-mail:"+" "+ semail+" "+inumb);
JOptionPane.showMessageDialog(null,info);
filewriter fw = new filewriter();
fw.setName(info);
fw.writeFile();
try{
Thread.sleep(150);
}catch(InterruptedException ex){
Thread.currentThread().interrupt();
}
System.exit(0);
}else{
JOptionPane.showMessageDialog(null,"Please fill out all fields");
}
}
}
}
You must force all the parents of the textfield to get focus, then we can set focus on the textfield
Java Textfield focus
This gui should draw moving images on frame panel called "system". But first of all i need to make those objects. Here i'm trying to add them to an array and use that array in other classes. But array keeps being empty!
I guess the problem is in declaring(bottom of the code). There is no exception thrown because I let other classes to execute only when this array(Planetarium) is not empty(it should work like that, because other moves depends on planets created(those objects)). But if it is empty that means nothing is declared...
What should i do if I want to fill an array in the thread executed in event listener?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GUI extends Frame implements WindowListener,ActionListener {
cpWindow window1 = new cpWindow();
cmWindow window2 = new cmWindow();
Delete window3 = new Delete();
SolarSystem system = new SolarSystem(300,300);
Planet[] Planetarium = null; // using this to make an array
Moon[] Moonarium = null;
/**
* Frame for general window.
*/
public void createFrame0(){
JFrame f0 = new JFrame("Choose what you want to do");
f0.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f0.addWindowListener(this);
f0.setLayout(new GridLayout(3,1));
JButton cP = new JButton("Create a planet");
JButton cM = new JButton("Create a moon");
JButton Delete = new JButton("Annihilate a planet or moon");
f0.add(cP);
f0.add(cM);
f0.add(Delete);
cP.addActionListener(this);
cM.addActionListener(this);
Delete.addActionListener(this);
cP.setActionCommand("1");
cM.setActionCommand("2");
Delete.setActionCommand("3");
f0.pack();
f0.setVisible(true);
}
/**
* Frame for planet adding window.
*/
class cpWindow implements ActionListener,WindowListener{
JLabel name1 = new JLabel("Name");
JLabel color1 = new JLabel("Color");
JLabel diam1 = new JLabel("Diameter");
JLabel dist1 = new JLabel("Distance");
JLabel speed1 = new JLabel("Speed");
JTextField name2 = new JTextField();
JTextField color2 = new JTextField();
JTextField diam2 = new JTextField();
JTextField dist2 = new JTextField();
JTextField speed2 = new JTextField();
double distance;
int Speed;
double diameter;
public void createFrame1() {
JFrame f1 = new JFrame("Add planet");
f1.addWindowListener(this);
f1.setLayout(new GridLayout(6,2,5,5));
JButton mygt = new JButton("Create planet");
mygt.addActionListener(this);
name2.setText("belekoks");color2.setText("RED");diam2.setText("30");dist2.setText("60");spe ed2.setText("2");
f1.add(name1);f1.add(name2);f1.add(color1);f1.add(color2);f1.add(diam1);
f1.add(diam2);f1.add(dist1);f1.add(dist2);f1.add(speed1);f1.add(speed2);
f1.add(mygt);
f1.pack();
f1.setVisible(true);
}
public void createVariables(){
try {
distance = Double.parseDouble(dist2.getText());
Speed = Integer.parseInt(speed2.getText());
diameter = Double.parseDouble(diam2.getText());
}
catch(NumberFormatException i) {
}
Main.diametras = diameter;
Main.distancija = distance;
Main.greitis = Speed;
Main.vardas = name2.getText();
Main.spalva = color2.getText();
}
public void actionPerformed(ActionEvent e) {
createVariables();
new NewThread().start();
list.display();
}
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
public void windowClosed(WindowEvent e) {}
public void windowActivated(WindowEvent arg0) {}
public void windowDeactivated(WindowEvent arg0) {}
public void windowDeiconified(WindowEvent arg0) {}
public void windowIconified(WindowEvent arg0) {}
public void windowOpened(WindowEvent arg0) {}
}
/**
* Frame for moon adding window
*/
CheckboxGroup planets = new CheckboxGroup();
String which;
class cmWindow implements ActionListener,WindowListener, ItemListener{
JLabel name1 = new JLabel("Name");
JLabel color1 = new JLabel("Color");
JLabel diam1 = new JLabel("Diameter");
JLabel speed1 = new JLabel("Speed");
JTextField name2 = new JTextField();
JTextField color2 = new JTextField();
JTextField diam2 = new JTextField();
JTextField speed2 = new JTextField();
JLabel info = new JLabel("Which planet's moon it will be?");
JLabel corDist1 = new JLabel("Distance from centre of rotation");
JLabel corSpeed1 = new JLabel("Speed which moon centres");
JTextField corDist2 = new JTextField();
JTextField corSpeed2 = new JTextField();
int cordistance;
int corspeed;
public void createFrame1() {
JFrame f1 = new JFrame("Add moon");
f1.addWindowListener(this);
f1.setLayout(new GridLayout(8,2,5,5));
JButton mygt = new JButton("Create moon");
mygt.addActionListener(this);
for(int i=0;i<Planetarium.length;i++){
add(new Checkbox(Planetarium[i].nam,planets,false));
}
corDist2.setText("15");corSpeed2.setText("3");
f1.add(name1);f1.add(name2);f1.add(color1);f1.add(color2);
f1.add(diam1);f1.add(diam2);f1.add(speed1);f1.add(speed2);
f1.add(corDist1);f1.add(corDist2);f1.add(corSpeed1);f1.add(corSpeed2);
f1.add(mygt);
f1.pack();
f1.setVisible(true);
}
int Speed;
double diameter;
public void createVariables(){
try {
Speed = Integer.parseInt(speed2.getText());
diameter = Double.parseDouble(diam2.getText());
cordistance = Integer.parseInt(corDist2.getText());
corspeed = Integer.parseInt(corSpeed2.getText());
}
catch(NumberFormatException i) {}
Main.diametras = diameter;
Main.greitis = Speed;
Main.vardas = name2.getText();
Main.spalva = color2.getText();
Main.centGrt = corspeed;
Main.centAts = cordistance;
}
public void actionPerformed(ActionEvent e) {
createVariables();
new NewThread().start();
}
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
public void windowClosed(WindowEvent e) {}
public void windowActivated(WindowEvent arg0) {}
public void windowDeactivated(WindowEvent arg0) {}
public void windowDeiconified(WindowEvent arg0) {}
public void windowIconified(WindowEvent arg0) {}
public void windowOpened(WindowEvent arg0) {}
#Override
public void itemStateChanged(ItemEvent e) {
which = planets.getSelectedCheckbox().getLabel();
}
}
/**
* Deleting window
*/
class Delete implements ActionListener,WindowListener{
Checkbox[] checkB = new Checkbox[100];
public void createFrame2(){
JFrame f2 = new JFrame("Death Start");
f2.addWindowListener(this);
f2.setLayout(new GridLayout(6,2,5,5));
JButton Del = new JButton("Shoot it!");
Del.addActionListener(this);
JLabel[] planetName = new JLabel[100];
for(int i=0;i<Planetarium.length;i++){
planetName[i].setText(Planetarium[i].nam);
checkB[i].setLabel("This");
checkB[i].setState(false);
f2.add(planetName[i]);f2.add(checkB[i]);
}
}
public void actionPerformed(ActionEvent e) {
for(int i=0;i<Planetarium.length;i++){
if(checkB[i].getState()){
Planetarium[i] = null;
}
}
}
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
public void windowClosed(WindowEvent e) {}
public void windowActivated(WindowEvent arg0) {}
public void windowDeactivated(WindowEvent arg0) {}
public void windowDeiconified(WindowEvent arg0) {}
public void windowIconified(WindowEvent arg0) {}
public void windowOpened(WindowEvent arg0) {}
}
////////////////////////////////////////////////////////
public GUI() {
createFrame0();
}
public void actionPerformed(ActionEvent e) {
if ("1".equals(e.getActionCommand())) {this.window1.createFrame1();}
else if ("2".equals(e.getActionCommand()) & Planetarium != null) {this.window2.createFrame1();}
else if ("3".equals(e.getActionCommand()) & Planetarium != null) {this.window3.createFrame2();}
}
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
public void windowClosed(WindowEvent e) {}
public void windowActivated(WindowEvent arg0) {}
public void windowDeactivated(WindowEvent arg0) {}
public void windowDeiconified(WindowEvent arg0) {}
public void windowIconified(WindowEvent arg0) {}
public void windowOpened(WindowEvent arg0) {}
LinkedList list = new LinkedList();
class NewThread extends Thread {
Thread t;
NewThread() {
t = new Thread(this);
t.start();
}
public void run() {
Moon moon = null;
Planet planet = new Planet(Main.vardas,Main.distancija,Main.diametras,Main.spalva,Main.greitis);
if(Planetarium != null){
for(int i=0;i<Planetarium.length;i++){
if (which == Planetarium[i].nam){
moon = new Moon(Main.vardas,Planetarium[i].dist,Main.diametras,Main.spalva,Main.greitis,Main.centGrt,Main.centAts);
}
}}
int a=0,b=0;
int i = 0;
if (Main.centAts == 0){
Planetarium[i] = planet; //i guess problem is here
a++;
list.add(planet);
for(i=0; i <= i+1 0; i++) {
planet.move();
planet.drawOn(system);
system.finishedDrawing();
if (i==360){i=0;}
}
}
else{
Moonarium[i] = moon;
b++;
if(i==Main.greitis){
for(int l = 0; l <= l+1; l++) {
moon.move();
moon.drawOn(system);
system.finishedDrawing();
}}
}
}
}
}
EDIT: add linkedlist(still nothing after display) and moved declaration before infinite loop
You don't appear to have assigned these arrays anything so they should be null rather than empty.
The way you are using them a List might be better.
final List<Planet> planetarium = new ArrayList<Planet>();
planetarium.add(new Planet( .... ));
Planet p = planetarium.get(i);
for(Planet p: planetarium){
// something for each planet.
}
Note: you have to create an array before using it and you have know its length which is fixed. A list can have any length, but you still need to create it first.
Look at the loop before:
Planetarium[i] = planet;
It looks like it will loop infinitely
for(i=0; i >= 0; i++)
i will alway be >= 0.