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";
Related
So i'm doing a school project based on a medical store (it's about plants). I have two classes(each has one JFrame).
Login:
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JOptionPane;
public class Login extends JFrame{
JPanel panelLogin;
JTextField usernameField;
JPasswordField parolaField;
JButton butonLogin,butonCancel;
public JPanel createContentPane (){
//Creez un panel pe care sa pun toate campurile.
panelLogin = new JPanel();
panelLogin.setLayout(null);
panelLogin.setBackground(new java.awt.Color(204, 204, 255));
panelLogin.setBorder(javax.swing.BorderFactory.createTitledBorder("Login"));
//usernameField
usernameField = new JTextField();
usernameField.setLocation(50, 50);
usernameField.setSize(300, 25);
usernameField.setHorizontalAlignment(JTextField.CENTER);
//placeholder pt usernameField
final String placeholderUsername = "Username";
usernameField.setText(placeholderUsername);
usernameField.addFocusListener(new FocusListener() {
private boolean showingPlaceholder = true;
public void focusGained(FocusEvent e) {
if (showingPlaceholder) {
showingPlaceholder = false;
usernameField.setText("");
}
}
public void focusLost(FocusEvent arg0) {
if (usernameField.getText().isEmpty()) {
usernameField.setText(placeholderUsername);
showingPlaceholder = true;
}
}
});
panelLogin.add(usernameField);
//parolaField
parolaField = new JPasswordField();
parolaField.setLocation(50, 100);
parolaField.setSize(300, 25);
parolaField.setHorizontalAlignment(JTextField.CENTER);
//placeholder pt parolaField
final String placeholderParola = "Parola";
parolaField.setText(placeholderParola);
parolaField.addFocusListener(new FocusListener() {
private boolean showingPlaceholder = true;
public void focusGained(FocusEvent e) {
if (showingPlaceholder) {
showingPlaceholder = false;
parolaField.setText("");
}
}
public void focusLost(FocusEvent arg0) {
if (parolaField.getText().isEmpty()) {
parolaField.setText(placeholderParola);
showingPlaceholder = true;
}
}
});
panelLogin.add(parolaField);
//butonLogin
butonLogin = new JButton("Login");
butonLogin.setLocation(70, 140);
butonLogin.setSize(100, 20);
butonLogin.addActionListener(new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
butonLoginActionPerformed(evt);
/*
String uname=usernameField.getText();
String pword=parolaField.getText();
if(uname.equals("admin") && pword.equals("admin")){
Home home=new Home();
home.setVisible(true);
//this.dispose();
}
else{
JFrame rootPane = null;
JOptionPane.showMessageDialog(rootPane, "Username sau parola incorecte","Eroare la conectare",JOptionPane.WARNING_MESSAGE);
}*/
}
});
panelLogin.add(butonLogin);
//butonCancel
butonCancel = new JButton("Cancel");
butonCancel.setLocation(220, 140);
butonCancel.setSize(100, 20);
butonCancel.addActionListener(new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}
});
panelLogin.add(butonCancel);
//Returnez panelul
panelLogin.setOpaque(true);
return panelLogin;
}
private static void LoginGUI() {
JFrame frameLogin = new JFrame("PLAFAR * Calinescu George-Catalin * 221");
//Creez panelul peste frame si il stilizez
Login login = new Login();
frameLogin.setContentPane(login.createContentPane());
frameLogin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frameLogin.setSize(400, 250);
frameLogin.setVisible(true);
}
private void butonLoginActionPerformed(java.awt.event.ActionEvent evt) {
String uname=usernameField.getText();
String pword=parolaField.getText();
if(uname.equals("admin") && pword.equals("admin")){
Home ho=new Home();
ho.setVisible(true);
this.dispose();
}
else{
JFrame rootPane = null;
JOptionPane.showMessageDialog(rootPane, "Username sau parola incorecte","Eroare la conectare",JOptionPane.WARNING_MESSAGE);
}
}
public static void main(String[] args) {
//Creez GUI si il afisez pe ecran
SwingUtilities.invokeLater(new Runnable() {
public void run() {
LoginGUI();
}
});
}
}
and Home:
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.SwingUtilities;
public class Home extends JFrame{
JPanel panelHome;
static String[] listaplante=new String[10];
static String[] listacantitati=new String[10];
static String[] listapreturi=new String[10];
static int kPlante=0, kCantitati=0, kPreturi=0;
JButton butonCumpara,butonAdauga;
JTextField cantitateField;
public JPanel createHomeContentPane (){
//Creez un panel pe care sa pun toate campurile.
panelHome = new JPanel();
panelHome.setLayout(null);
panelHome.setBackground(new java.awt.Color(204, 204, 255));
panelHome.setBorder(javax.swing.BorderFactory.createTitledBorder("Home"));
//Creez lista cu plante
DefaultListModel<String> listaPlante = new DefaultListModel<>();
JList<String> list = new JList<>(citirePlante());
list.setBounds(50,100, 75,75);
panelHome.add(list);
//Creez lista cu cantitatile fiecarei plante
DefaultListModel<String> listaCantitati = new DefaultListModel<>();
JList<String> list2 = new JList<>(citireCantitati());
list2.setBounds(150,100, 75,75);
panelHome.add(list2);
//Creez lista cu preturile fiecarei plante
DefaultListModel<String> listaPreturi = new DefaultListModel<>();
JList<String> list3 = new JList<>(citirePreturi());
list3.setBounds(250,100, 75,75);
panelHome.add(list3);
//Creez titlurile pt fiecare lista
JLabel denumireLabel=new JLabel("Denumire:");
denumireLabel.setBounds(50,80,70,20);
panelHome.add(denumireLabel);
JLabel cantitatiLabel=new JLabel("Cantitati:");
cantitatiLabel.setBounds(150,80,70,20);
panelHome.add(cantitatiLabel);
JLabel preturiLabel=new JLabel("Preturi:");
preturiLabel.setBounds(250,80,70,20);
panelHome.add(preturiLabel);
//Creez un camp pt a adauga cantitatea dorita care urmeaza a fi cumparata
//cantitateField
cantitateField = new JTextField();
cantitateField.setBounds(180,180,100,20);
cantitateField.setHorizontalAlignment(JTextField.CENTER);
//placeholder pt cantitateField
final String placeholderCantitate = "Cantitatea dorita";
cantitateField.setText(placeholderCantitate);
cantitateField.addFocusListener(new FocusListener() {
private boolean showingPlaceholder = true;
public void focusGained(FocusEvent e) {
if (showingPlaceholder) {
showingPlaceholder = false;
cantitateField.setText("");
}
}
public void focusLost(FocusEvent arg0) {
if (cantitateField.getText().isEmpty()) {
cantitateField.setText(placeholderCantitate);
showingPlaceholder = true;
}
}
});
panelHome.add(cantitateField);
//Butonul de cumparare
butonCumpara = new JButton("Cumpara");
butonCumpara.setLocation(180, 200);
butonCumpara.setSize(100, 20);
butonCumpara.addActionListener(new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
String plantaselectata = list.getSelectedValue();
int indexplanta=list.getSelectedIndex();
String cantitateselectata = list2.getSelectedValue();
int indexcantitate=list2.getSelectedIndex();
String pretselectat = list3.getSelectedValue();
int indexpret=list3.getSelectedIndex();
String cantitatedorita=cantitateField.getText();
int valCantitate=Integer.valueOf(cantitateselectata);
int valCantitateDorita=Integer.valueOf(cantitatedorita);
int valPret=Integer.valueOf(pretselectat);
if(indexplanta==indexcantitate && indexplanta==indexpret){
if(valCantitateDorita<=valCantitate){
try {
afisPlantaCumparata(plantaselectata,valCantitateDorita);
} catch (IOException ex) {
Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex);
}
int a=valCantitate-valCantitateDorita;
String b=Integer.toString(a);
listacantitati[indexcantitate]=b;
panelHome.setVisible(false);
panelHome.setVisible(true);
}
else{
JFrame rootPane = null;
JOptionPane.showMessageDialog(rootPane, "Cantitatea nu esti disponibila","Eroare de cumparare",JOptionPane.WARNING_MESSAGE);
}
}
else{
JFrame rootPane = null;
JOptionPane.showMessageDialog(rootPane, "Planta, cantitate si pretul nu sunt din aceeasi categorie","Eroare de cumparare",JOptionPane.WARNING_MESSAGE);
}
}
});
panelHome.add(butonCumpara);
//Butonul de adaugare a unei plantei noi
butonAdauga = new JButton("Adauga");
butonAdauga.setLocation(80, 200);
butonAdauga.setSize(100, 20);
butonAdauga.addActionListener(new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
System.out.println("DsA");
}
});
panelHome.add(butonAdauga);
//Returnez panelul
panelHome.setOpaque(true);
return panelHome;
}
public static String[] citirePlante(){
BufferedReader objReader = null;
try {
String strCurrentLine;
objReader = new BufferedReader(new FileReader("Plante.txt"));
while ((strCurrentLine = objReader.readLine()) != null) {
listaplante[kPlante] = strCurrentLine;
kPlante++;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (objReader != null)
objReader.close();
}catch (IOException ex) {
ex.printStackTrace();
}
}
return listaplante;
}
public static String[] citireCantitati(){
BufferedReader objReader = null;
try {
String strCurrentLine;
objReader = new BufferedReader(new FileReader("Cantitati.txt"));
while ((strCurrentLine = objReader.readLine()) != null) {
listacantitati[kCantitati] = strCurrentLine;
kCantitati++;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (objReader != null)
objReader.close();
}catch (IOException ex) {
ex.printStackTrace();
}
}
return listacantitati;
}
public static String[] citirePreturi(){
BufferedReader objReader = null;
try {
String strCurrentLine;
objReader = new BufferedReader(new FileReader("Preturi.txt"));
while ((strCurrentLine = objReader.readLine()) != null) {
listapreturi[kPreturi] = strCurrentLine;
kPreturi++;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (objReader != null)
objReader.close();
}catch (IOException ex) {
ex.printStackTrace();
}
}
return listapreturi;
}
public static void afisPlantaCumparata(String p, int c) throws IOException{
FileWriter writer = new FileWriter("PlanteVandute.txt");
try (
BufferedWriter bw = new BufferedWriter(writer)) {
bw.write(p+" "+c+"\n");
} catch (IOException e) {
System.err.format("IOException: %s%n", e);
}
}
private static void HomeGUI() {
JFrame frameHome = new JFrame("PLAFAR * Calinescu George-Catalin * 221");
//Creez panelul peste frame si il stilizez
Home home = new Home();
frameHome.setContentPane(home.createHomeContentPane());
frameHome.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frameHome.setSize(400, 300);
frameHome.setVisible(true);
}
public static void main(String[] args) {
//Creez GUI si il afisez pe ecran
SwingUtilities.invokeLater(new Runnable() {
public void run() {
HomeGUI();
}
});
}
}
So i can't switch the frames when i login in with username admin and password admin. It's showing another frame that looks new to me, not my Home Frame. Why? what i did wrong?
And the other question is that: if i buy one plant i write into a text file the name and the amount that the buyer buyed but if i buy another one the file rewrites and i want to have all the plants that are buyed there. any typs?
Why use two frames in the first place??
Just use single main JFrame.
set its layout to be CardLayout
create both Login and Home by extending JPanel.
place them in main frame and show Login or Home panel as required!!
learn about CardLayout here
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)
{
}
}
}
Im woking on some code to do some computations on different types of beer. I have a main class which uses a GUI and has a JTextArea to print output. Calling append within the main class works just fine, but as soon as I try to call append from an outside class to write to the text area..no cigar..i've worked at this for awhile and simply have no clue. Quite a bit of code, but I think the fix is simple
and I guess while im at it, does it make sense to extend NewFileOpener into LagerChooser? Or should it extend jpanel?
thanks for the help!!
public class NewFinalOpener extends JPanel implements ActionListener {
JFileChooser fc;
private CustomPanel customPanel;
public CustomTextArea customTextArea = new CustomTextArea();
private double versionID = 1.0;
private JButton openButton;
protected ArrayList<String> namesForGeneration;
private boolean namesRead = false;
void displayGUI() {
JFrame frame = new JFrame("Binary Brewing! " + "Version:" + versionID);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(5, 5));
contentPane.setBorder(BorderFactory.createLineBorder(Color.BLUE, 5));
customPanel = new CustomPanel();
// customTextArea = new CustomTextArea();
customTextArea
.append(" Program progress and/or errors will display below:");
customTextArea
.append("\n"
+ "----------------------------------------------------------------------------------------------------");
customTextArea.append("\n" + "\n"
+ "To Enable Beer recipe Generation please read in Name file!" + "\n");
contentPane.add(customTextArea, BorderLayout.CENTER);
contentPane.add(customPanel, BorderLayout.LINE_START);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
new NewFinalOpener().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
class CustomPanel extends JPanel implements ActionListener {
private static final int GAP = 5;
JButton openButton, b2, b3, b4;
public CustomPanel() {
fc = new JFileChooser();
setOpaque(true);
setBackground(Color.WHITE);
setBorder(BorderFactory.createLineBorder(Color.GRAY, GAP));
openButton = new JButton("Choose names file");
openButton.setVerticalTextPosition(AbstractButton.CENTER);
openButton.setHorizontalTextPosition(AbstractButton.LEADING);
openButton.setMnemonic(KeyEvent.VK_D);
openButton.setActionCommand("open");
openButton.setEnabled(true);
openButton.addActionListener(this);
add(openButton);
b2 = new JButton("Ale");
b2.setVerticalTextPosition(AbstractButton.CENTER);
b2.setHorizontalTextPosition(AbstractButton.LEADING);
b2.setMnemonic(KeyEvent.VK_D);
b2.setActionCommand("ale");
if(namesRead == false){
b2.setEnabled(false);
}
b2.addActionListener(this);
add(b2);
b3 = new JButton("Lager");
b3.setVerticalTextPosition(AbstractButton.CENTER);
b3.setHorizontalTextPosition(AbstractButton.LEADING);
b3.setMnemonic(KeyEvent.VK_D);
b3.setActionCommand("lager");
if(namesRead == false){
b3.setEnabled(false);
}
b3.addActionListener(this);
add(b3);
b4 = new JButton("Random");
b4.setVerticalTextPosition(AbstractButton.BOTTOM);
b4.setHorizontalTextPosition(AbstractButton.LEADING);
b4.setMnemonic(KeyEvent.VK_D);
b4.setActionCommand("lager");
if(namesRead == false){
b4.setEnabled(false);
}
b4.addActionListener(this);
add(b4);
}
public Dimension getPreferredSize() {
return (new Dimension(200, 100));
}
#Override
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
if (action.equals("open")) {
int returnVal = fc.showOpenDialog(NewFinalOpener.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
try {
BufferedReader br = new BufferedReader(new FileReader(
fc.getSelectedFile()));
String line = " ";
namesForGeneration = new ArrayList<String>();
while (br.ready() == true) {
line = br.readLine();
namesForGeneration.add(line);
}
if (br.ready() == false) {
customTextArea.append("\n"
+ "Successfully read all names!" + " "
+ file + "\n");
customTextArea.append("\n" + "Beer Recipe Generator Enabled!" + "\n");
namesRead = true;
b2.setEnabled(true);
b3.setEnabled(true);
b4.setEnabled(true);
openButton.setEnabled(false);
customTextArea
.append("\n"
+ "---------------------------------------------------------");
br.close();
}
} catch (Exception f) {
JOptionPane.showMessageDialog(null, e);
}
} else {
customTextArea.append("Open command cancelled by user."
+ "\n");
}
}
if(action.equalsIgnoreCase("lager")){
customTextArea.append("\n" + "\n "+ "Ale recipe generation selected proceeding to sub categories...");
b2.setEnabled(false);
b3.setEnabled(false);
b4.setEnabled(false);
createLagerFrame();
}
}
protected void createLagerFrame(){
LagerChooser l1 = new LagerChooser();
}
}
class CustomTextArea extends JTextArea {
private static final int GAP = 5;
public CustomTextArea() {
setEditable(false);
setBorder(BorderFactory.createLineBorder(Color.CYAN, GAP));
}
public Dimension getPreferredSize() {
return (new Dimension(800, 800));
}
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
public void setCustomText(String text){
customTextArea.append(text);
}
}
and the class that needs to append to the JTextarea
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class LagerChooser extends NewFinalOpener{
public LagerChooser() {
}
public void tellCustom(String line){
setCustomText(line);
}
}
You can use:
public static final PrintStream OUT = System.out;
public CustomPanel() throws Throwable
{
...
System.setOut(new PrintStream(new OutputStream(){
#Override
public void write(int oneByte) throws IOException {
if(oneByte<0||oneByte>255)
return;
write(new byte[]{(byte)oneByte}, 0, 1);
}
#Override
public void write(byte[] b, int offset, int length) throws IOException {
String str = new String(b, offset, length);
customTextArea.append(str);
}
}));
And write to System.out. it will print to console and to textarea.
PS. Why you create custom textarea class? You should use JTextArea:
customTextArea=new JTextArea();
customTextArea.setEditable(false);
customTextArea.setBorder(BorderFactory.createLineBorder(Color.CYAN, GAP));
customTextArea.setPrefferedSize(...);
Your code uses lot of memory, size of exported JAR isn't small for "simple program".
Optimized code:
import java.io.*;
import java.util.*;
class NewFinalOpener extends JPanel implements ActionListener {
JFileChooser fc;
private CustomPanel customPanel;
public JTextArea customTextArea = new JTextArea();
private double versionID = 1.0;
private JButton openButton;
protected ArrayList < String > namesForGeneration;
private boolean namesRead = false;
private static final PrintStream SYSOUT = System.out;
public NewFinalOpener() {
JFrame frame = new JFrame("Binary Brewing! Version:" + versionID);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(5, 5));
contentPane.setBorder(BorderFactory.createLineBorder(Color.BLUE, 5));
customPanel = new CustomPanel();
customTextArea.setEditable(false);
customTextArea.setBorder(BorderFactory.createLineBorder(Color.CYAN, GAP));
customTextArea.setPreferredSize(new Dimension(800, 800));
System.setOut(new PrintStream(new OutputStream(){
#Override
public void write(int oneByte) throws IOException {
if(oneByte<0||oneByte>255)
return;
write(new byte[]{(byte)oneByte}, 0, 1);
}
#Override
public void write(byte[] b, int offset, int length) throws IOException {
String str = new String(b, offset, length);
SYSOUT.write(b,offset,length);
customTextArea.append(str);
}
}));
System.setErr(System.out);
System.out.println(" Program progress and/or errors will display below:");
System.out.println("----------------------------------------------------------------------------------------------------\n");
System.out.println("To Enable Beer recipe Generation please read in Name file!");
contentPane.add(customTextArea, BorderLayout.CENTER);
contentPane.add(customPanel, BorderLayout.LINE_START);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new NewFinalOpener();
}
});
}
class CustomPanel extends JPanel implements ActionListener {
private static final int GAP = 5;
JButton openButton, b2, b3, b4;
public CustomPanel() {
setPreferredSize(new Dimension(200, 100));
fc = new JFileChooser();
setOpaque(true);
setBackground(Color.WHITE);
setBorder(BorderFactory.createLineBorder(Color.GRAY, GAP));
openButton = new JButton("Choose names file");
openButton.setVerticalTextPosition(AbstractButton.CENTER);
openButton.setHorizontalTextPosition(AbstractButton.LEADING);
openButton.setMnemonic(KeyEvent.VK_D);
openButton.setActionCommand("open");
openButton.setEnabled(true);
openButton.addActionListener(this);
add(openButton);
b2 = new JButton("Ale");
b2.setVerticalTextPosition(AbstractButton.CENTER);
b2.setHorizontalTextPosition(AbstractButton.LEADING);
b2.setMnemonic(KeyEvent.VK_D);
b2.setActionCommand("ale");
if (namesRead == false) {
b2.setEnabled(false);
}
b2.addActionListener(this);
add(b2);
b3 = new JButton("Lager");
b3.setVerticalTextPosition(AbstractButton.CENTER);
b3.setHorizontalTextPosition(AbstractButton.LEADING);
b3.setMnemonic(KeyEvent.VK_D);
b3.setActionCommand("lager");
if (namesRead == false) {
b3.setEnabled(false);
}
b3.addActionListener(this);
add(b3);
b4 = new JButton("Random");
b4.setVerticalTextPosition(AbstractButton.BOTTOM);
b4.setHorizontalTextPosition(AbstractButton.LEADING);
b4.setMnemonic(KeyEvent.VK_D);
b4.setActionCommand("lager");
if (namesRead == false) {
b4.setEnabled(false);
}
b4.addActionListener(this);
add(b4);
}
#Override
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
if (action.equals("open")) {
int returnVal = fc.showOpenDialog(NewFinalOpener.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
try {
BufferedReader br = new BufferedReader(new FileReader(fc.getSelectedFile()));
String line = " ";
namesForGeneration = new ArrayList < String > ();
while (br.ready() == true) {
line = br.readLine();
namesForGeneration.add(line);
}
if (br.ready() == false) {
System.out.println("Successfully read all names!" + " " + file + "\n");
System.out.println("Beer Recipe Generator Enabled!" + "\n");
namesRead = true;
b2.setEnabled(true);
b3.setEnabled(true);
b4.setEnabled(true);
openButton.setEnabled(false);
System.out.println("\n---------------------------------------------------------");
br.close();
}
} catch (Throwable f) {
f.printStackTrace();
JOptionPane.showMessageDialog(null, e);
}
} else {
System.out.println("Open command cancelled by user.");
}
}
if (action.equalsIgnoreCase("lager")) {
System.out.println("Ale recipe generation selected proceeding to sub categories...");
b2.setEnabled(false);
b3.setEnabled(false);
b4.setEnabled(false);
createLagerFrame();
}
}
protected void createLagerFrame() {
LagerChooser l1 = new LagerChooser();
}
}
}
class LagerChooser extends NewFinalOpener {
public LagerChooser() {}
public void tellCustom(String line) {
setCustomText(line);
}
}
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
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);
}
}
}