How to switch java Frames? - java

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

Related

Is there any method i can add a scroll pane to a jlist that its added on a panel with null layout?

I'm doing a school project based on a medical store and I want to add a scroll pane to all my 3 lists that I'm using
package Interfata;
import java.awt.Color;
import java.awt.GridBagLayout;
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 denumireField,
pretField,
cantitateField,
cantitateDoritaField;
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, 75, 75, 100);
list.setSelectionBackground(Color.ORANGE);
panelHome.add(list);
//Creez lista cu cantitatile fiecarei plante
DefaultListModel < String > listaCantitati = new DefaultListModel < >();
JList < String > list2 = new JList < >(citireCantitati());
list2.setBounds(150, 75, 75, 100);
list2.setSelectionBackground(Color.YELLOW);
panelHome.add(list2);
//Creez lista cu preturile fiecarei plante
DefaultListModel < String > listaPreturi = new DefaultListModel < >();
JList < String > list3 = new JList < >(citirePreturi());
list3.setBounds(250, 75, 75, 100);
list3.setSelectionBackground(Color.GREEN);
panelHome.add(list3);
//Creez titlurile pt fiecare lista
JLabel denumireLabel = new JLabel("Denumire:");
denumireLabel.setBounds(50, 55, 70, 20);
panelHome.add(denumireLabel);
JLabel cantitatiLabel = new JLabel("Cantitati:");
cantitatiLabel.setBounds(150, 55, 70, 20);
panelHome.add(cantitatiLabel);
JLabel preturiLabel = new JLabel("Preturi:");
preturiLabel.setBounds(250, 55, 70, 20);
panelHome.add(preturiLabel);
//Creez un camp pt a adauga cantitatea dorita care urmeaza a fi cumparata
//cantitateDoritaField
cantitateDoritaField = new JTextField();
cantitateDoritaField.setBounds(80, 200, 100, 20);
cantitateDoritaField.setHorizontalAlignment(JTextField.CENTER);
//placeholder pt cantitateField
final String placeholderCantitateDorita = "Cantitatea dorita";
cantitateDoritaField.setText(placeholderCantitateDorita);
cantitateDoritaField.addFocusListener(new FocusListener() {
private boolean showingPlaceholder = true;
public void focusGained(FocusEvent e) {
if (showingPlaceholder) {
showingPlaceholder = false;
cantitateDoritaField.setText("");
}
}
public void focusLost(FocusEvent arg0) {
if (cantitateDoritaField.getText().isEmpty()) {
cantitateDoritaField.setText(placeholderCantitateDorita);
showingPlaceholder = true;
}
}
});
panelHome.add(cantitateDoritaField);
//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 = cantitateDoritaField.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);
//Cumpurile denumire cantitate si pret pt adaugarea plantei
//denumireField
denumireField = new JTextField();
denumireField.setBounds(80, 240, 100, 20);
denumireField.setHorizontalAlignment(JTextField.CENTER);
//placeholder pt denumireField
final String placeholderDenumire = "Denumire";
denumireField.setText(placeholderDenumire);
denumireField.addFocusListener(new FocusListener() {
private boolean showingPlaceholder = true;
public void focusGained(FocusEvent e) {
if (showingPlaceholder) {
showingPlaceholder = false;
denumireField.setText("");
}
}
public void focusLost(FocusEvent arg0) {
if (denumireField.getText().isEmpty()) {
denumireField.setText(placeholderDenumire);
showingPlaceholder = true;
}
}
});
panelHome.add(denumireField);
//cantitateField
cantitateField = new JTextField();
cantitateField.setBounds(80, 260, 100, 20);
cantitateField.setHorizontalAlignment(JTextField.CENTER);
//placeholder pt cantitateField
final String placeholderCantitate = "Cantitatea";
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);
//pretField
pretField = new JTextField();
pretField.setBounds(80, 280, 100, 20);
pretField.setHorizontalAlignment(JTextField.CENTER);
//placeholder pt pretField
final String placeholderPret = "Pret";
pretField.setText(placeholderPret);
pretField.addFocusListener(new FocusListener() {
private boolean showingPlaceholder = true;
public void focusGained(FocusEvent e) {
if (showingPlaceholder) {
showingPlaceholder = false;
pretField.setText("");
}
}
public void focusLost(FocusEvent arg0) {
if (pretField.getText().isEmpty()) {
pretField.setText(placeholderPret);
showingPlaceholder = true;
}
}
});
panelHome.add(pretField);
//Butonul de adaugare a unei plantei noi
butonAdauga = new JButton("Adauga");
butonAdauga.setLocation(180, 260);
butonAdauga.setSize(100, 20);
butonAdauga.addActionListener(new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
String denumireNou = denumireField.getText();
String cantitateNou = cantitateField.getText();
String pretNou = pretField.getText();
listaplante[kPlante++] = denumireNou;
listacantitati[kCantitati++] = cantitateNou;
listapreturi[kPreturi++] = pretNou;
panelHome.setVisible(false);
panelHome.setVisible(true);
}
});
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", true);
try (
BufferedWriter bw = new BufferedWriter(writer)) {
bw.write(p + " " + c + "\n");
} catch(IOException e) {
System.err.format("IOException: %s%n", e);
}
}
private static void Home() {
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, 350);
frameHome.setVisible(true);
}
public static void main(String[] args) {
//Creez GUI si il afisez pe ecran
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Home();
}
});
}
}
Is there any method I can add a scroll pane to list, list2 and list3? I really don't want to set another layout type because I'm not used to them and I worked with absolute layout when I started doing this GUI but I ran into some problems and I decided to wrote all the code by hand.
Thank you for providing example code / minimal working example. (One remark - if no Plante.txt is found an exception is thrown. You could improve your code to handle this behavior, e.g., with a warning or message for the user.)
You can add your JList to a JScrollPane like this:
// to ensure single selection in your list
someList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scrollPane = new JScrollPane(someList);
Then, you have to add scollPane to a LayoutManager or (in your example) JPanel.
It's strongly recommended to use a normal layout manager, because layout manager allows to handle components sizes, when Window/Panel is resized. It's also provides better support for different Look and Feels and OS.
To get your code working you need to install scroll pane around your list.
DefaultListModel<String> listaPlante = new DefaultListModel<>();
JList<String> list = new JList<>(citirePlante());
JScrollPane scroller = new JScrollPane(list);
scroller.setBounds(50,75, 75,100); // not list!!!
list.setSelectionBackground(Color.ORANGE);
panelHome.add(scroller); // not list!!!

When my app opens a new java program, how do I prevent my app from repainting itself with a new theme?

Basically what I'm doing is creating a swing application that acts as a launcher. All it does is gives the user 3 options they can choose from to open a new java application. The 3 different java applications all have different themes, and one doesn't have a theme at all. I'm trying to get it so when I select an option, my launcher app doesn't repaint it self to what the new program is. I want the launcher to maintain its theme.
I'm probably not using EventQueue right but I'm not sure which one to use.
package wind;
import java.awt.Desktop;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.text.ParseException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import de.javasoft.plaf.synthetica.SyntheticaAluOxideLookAndFeel;
public class Launcher {
/**
*
*/
private static final long serialVersionUID = 1L;
private JButton btn1, btn2, btn3;
private GridBagConstraints gbc = new GridBagConstraints();
private JMenuBar menuBar;
private JMenu menu, menu2, menu3, menu4;
private JMenuItem menuItem, menuItem2, menuItem3, menuItem4,
menuItem5, menuItem6, menuItem7, menuItem8, menuItem9, menuItem10,
menuItem11, menuItem12, menuItem13, submenu1, submenu2, submenu3, submenu4, submenu5,
submenu6, submenu7, submenu8, submenu9, submenu10;
JFrame frame;
public Launcher() {
JFrame.setDefaultLookAndFeelDecorated(true);
JPopupMenu.setDefaultLightWeightPopupEnabled(false);
try {
UIManager.setLookAndFeel(new SyntheticaAluOxideLookAndFeel());
} catch (UnsupportedLookAndFeelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
frame = new JFrame();
frame.setTitle("Project Wind Client Launcher");
Image icon = getImage("windicon.png");
if (icon != null)
frame.setIconImage(icon);
components();
frame.add(mainPanel());
frame.setJMenuBar(menuBar);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 300);
frame.setResizable(false);
frame.setVisible(true);
}
});
}
private JPanel mainPanel() {
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridBagLayout());
btn1 = new JButton();
try {
Image img = ImageIO.read(getClass().getResource("/resources/gui.png"));
btn1.setIcon(new ImageIcon(img));
} catch (IOException ex) {
}
btn1.setToolTipText("Click here to launch the client with a graphic user interface.");
btn1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
runGUIMode(e);
}
});
//btn1.setBorder(null);
btn1.setOpaque(true);
btn1.setContentAreaFilled(false);
gbc.gridx = 1;
gbc.gridy = 0;
gbc.weightx = 0.25;
mainPanel.add(btn1, gbc);
btn2 = new JButton();
try {
Image img2 = ImageIO.read(getClass().getResource("/resources/nogui.png"));
btn2.setIcon(new ImageIcon(img2));
} catch (IOException ex) {
}
btn2.setToolTipText("This will launch the client without a graphic user interface.");
btn2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
runNoGUI(e);
}
});
btn2.setContentAreaFilled(false);
gbc.gridx = 2;
gbc.gridy = 0;
gbc.weightx = 0.25;
mainPanel.add(btn2, gbc);
btn3 = new JButton();
try {
Image img2 = ImageIO.read(getClass().getResource("/resources/app.png"));
btn3.setIcon(new ImageIcon(img2));
} catch (IOException ex) {
}
btn3.setToolTipText("This will launch the client in application mode.");
btn3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
runApplicationMode(e);
}
});
btn3.setContentAreaFilled(false);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 0.25;
mainPanel.add(btn3, gbc);
return mainPanel;
}
private void runApplicationMode(ActionEvent e) {
new FrameListener(FrameListener.LaunchMode.APPLICATION);
}
private void runNoGUI(ActionEvent e) {
new FrameListener(FrameListener.LaunchMode.NOGUI);
}
private void runGUIMode(ActionEvent e) {
new FrameListener(FrameListener.LaunchMode.GUI);
}
public void components() {
menuBar = new JMenuBar();
menu = new JMenu("File");
menu2 = new JMenu("Links");
menu3 = new JMenu("Guides");
menu4 = new JMenu("Help");
menuBar.add(menu);
menuBar.add(menu2);
menuBar.add(menu3);
menuBar.add(menu4);
menuItem = new JMenuItem("Exit");
menuItem.setToolTipText("Click here to exit the client launcher.");
menuItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
exitClient(e);
}
});
menuItem2 = new JMenuItem("Update");
menuItem2.setToolTipText("Click here to update your client.");
menuItem2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
updateClient(e);
}
});
menuItem3 = new JMenuItem("Check Version");
menuItem3.setToolTipText("Click here to check the version of your client.");
menuItem3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
checkVersion(e);
}
});
menuItem13 = new JMenuItem("Hide Launcher");
menuItem13.setToolTipText("Click here to hide the client launcher.");
menuItem13.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
hideLauncher(e);
}
});
menu.add(menuItem3);
menu.add(menuItem);
menu.add(menuItem13);
menu.add(menuItem2);
menuItem4 = new JMenuItem("Home");
menuItem4.setToolTipText("Click here to open up your homepage.");
menuItem4.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
home(e);
}
});
menuItem5 = new JMenuItem("YouTube");
menuItem5.setToolTipText("Click here to open up YouTube.");
menuItem5.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == menuItem5)
openURL("http://youtube.com");
}
});
menuItem6 = new JMenuItem("Twitter");
menuItem6.setToolTipText("Click here to open up Twitter.");
menuItem6.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == menuItem6)
openURL("http://twitter.com");
}
});
menuItem10 = new JMenuItem("Twitch");
menuItem10.setToolTipText("Click here to open up Twitch.");
menuItem10.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == menuItem10)
openURL("http://twitch.tv");
}
});
menu2.add(menuItem4);
menu2.add(menuItem10);
menu2.add(menuItem6);
menu2.add(menuItem5);
menuItem7 = new JMenu("Combat");
menuItem7.setToolTipText("Click here to view more options related to combat.");
submenu1 = new JMenu("Attack");
submenu2 = new JMenu("Strength");
submenu3 = new JMenu("Defence");
submenu4 = new JMenu("Hitpoints");
submenu5 = new JMenu("Prayer");
submenu6 = new JMenu("Ranged");
submenu7 = new JMenu("Magic");
menuItem7.add(submenu1);
menuItem7.add(submenu3);
menuItem7.add(submenu4);
menuItem7.add(submenu5);
menuItem7.add(submenu7);
menuItem7.add(submenu6);
menuItem7.add(submenu2);
menuItem8 = new JMenu("Skilling");
menuItem8.setToolTipText("Click here to view more options about skilling.");
submenu8 = new JMenu("Cooking");
submenu9 = new JMenu("Fishing");
submenu10 = new JMenu("Fletching");
menuItem8.add(submenu8);
menuItem8.add(submenu9);
menuItem8.add(submenu10);
menuItem9 = new JMenu("Money Making");
menuItem9.setToolTipText("Click here to view more options related to money making.");
menu3.add(menuItem7);
menu3.add(menuItem8);
menu3.add(menuItem9);
menuItem11 = new JMenu("Report a Bug");
menuItem11.setToolTipText("See any bugs? Click here and report them.");
menuItem12 = new JMenu("Commands");
menuItem12.setToolTipText("Click here to see which commands are available.");
menu4.add(menuItem11);
menu4.add(menuItem12);
}
private void exitClient(ActionEvent e) {
System.exit(1);
}
private void updateClient(ActionEvent e) {
JOptionPane.showMessageDialog(null,
"Client will now update.");
}
private void checkVersion(ActionEvent e) {
JOptionPane.showMessageDialog(null,
"Your files are fully updated.");
}
private void hideLauncher(ActionEvent e) {
frame.setState(Frame.ICONIFIED);
}
private void home(ActionEvent e) {
openURL("http://google.com");
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Launcher();
}
});
}
public void openURL(String url) {
try {
Desktop desktop = java.awt.Desktop.getDesktop();
URI oURL = new URI(url);
desktop.browse(oURL);
} catch (Exception e) {
e.printStackTrace();
}
}
private Image getImage(String name) {
String url = "https://dl.dropboxusercontent.com/u/5173165/icons/" + name;
try {
File f = new File(name);
if (f.exists())
return ImageIO.read(f.toURI().toURL());
Image img = ImageIO.read(new URL(url));
if (img != null) {
ImageIO.write((RenderedImage) img, "PNG", f);
return img;
}
} catch (MalformedURLException e) {
System.out.println("Error connecting to image URL: " + url);
} catch (IOException e) {
System.out.println("Error reading file: " + name);
}
return null;
}
}
This is a class that creates the new application the user selects
package wind;
import java.awt.EventQueue;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import wind.gui.Application;
import wind.gui.Gui;
import wind.web.WebClient;
public class FrameListener {
static JLabel image;
LaunchMode mode;
public FrameListener(LaunchMode mode) {
this.mode = mode;
initClient();
}
public enum LaunchMode {
APPLICATION,
GUI,
NOGUI;
}
public void initClient() {
switch(mode) {
case APPLICATION:
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Application();
}
});
break;
case GUI:
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Gui();
}
});
break;
case NOGUI:
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new WebClient(null);
}
});
break;
default:
mode = LaunchMode.GUI;
break;
}
}
}
This Swing based Launcher uses ProcessBuilder to run programs in a separate JVM. You can assess its suitability for your application by running it with a non-default Look & Feel. Note MetalLookAndFeel on the left and AquaLookAndFeel on the right in the illustration below.
$ java -Dswing.defaultlaf=javax.swing.plaf.metal.MetalLookAndFeel \
-cp build/classes gui.Launcher

How to work functionality for all Documents in swing

I want work functionality for all opened Documents not current open Document only. I had created one swing application. I was open an Document. The cut, copy, paste and selectAll operations through menuItem work for currently opened documents; not working for the previous opened Documents. Please help me.
Here is my code:
public class OpenDemo extends javax.swing.JFrame implements ChangeListener{
JTextPane textPane;
JTextPane lnNum;
JScrollPane scrollPane;
int i=0;
JTextField status;
ArrayList<JTextPane> textPanes=new ArrayList<>();
public OpenDemo() {
initComponents();
viewLineNumbers.setSelected(false);
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
tp = new javax.swing.JTabbedPane();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
open = new javax.swing.JMenuItem();
cut = new javax.swing.JMenuItem();
selectAll = new javax.swing.JMenuItem();
viewLineNumbers = new javax.swing.JCheckBoxMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jMenu1.setText("File");
open.setText("Open");
open.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
openActionPerformed(evt);
}
});
jMenu1.add(open);
cut.setText("Cut");
cut.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cutActionPerformed(evt);
}
});
jMenu1.add(cut);
selectAll.setText("SelectAll");
selectAll.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
selectAllActionPerformed(evt);
}
});
jMenu1.add(selectAll);
viewLineNumbers.setSelected(true);
viewLineNumbers.setText("ViewLineNumbers");
viewLineNumbers.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
viewLineNumbersActionPerformed(evt);
}
});
jMenu1.add(viewLineNumbers);
jMenuBar1.add(jMenu1);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tp, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tp, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void updateStatus(int linenumber, int columnnumber) {
status.setText("Line: " + linenumber + " Column: " + columnnumber);
}
private void openActionPerformed(java.awt.event.ActionEvent evt) {
FileDialog fd = new FileDialog(OpenDemo.this, "Select File", FileDialog.LOAD);
fd.show();
String title;
String sts;
File f;
if (fd.getFile() != null) {
sts = fd.getDirectory() + fd.getFile();
title=fd.getFile();
System.out.println(sts);
title=fd.getFile();
BufferedReader br = null;
StringBuffer str = new StringBuffer("");
try {
br = new BufferedReader(new FileReader(sts));
String line;
try {
while ((line = br.readLine()) != null) {
str.append(line + "\n");
}
} catch (IOException ex) {
Logger.getLogger(OpenDemo.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(OpenDemo.class.getName()).log(Level.SEVERE, null, ex);
}
String t = str.toString();
final JInternalFrame internalFrame = new JInternalFrame("",true,true);
textPane = new JTextPane();
textPane.setFont(new java.awt.Font("Miriam Fixed", 0, 13));
internalFrame.add(textPane);
i++;
internalFrame.setName("Doc "+i);
internalFrame.setTitle(title);
try {
internalFrame.setSelected(true);
} catch (PropertyVetoException ex) {
Logger.getLogger(OpenDemo.class.getName()).log(Level.SEVERE, null, ex);
}
textPane.addCaretListener(new CaretListener() {
#Override
public void caretUpdate(CaretEvent e) {
JTextPane editArea = (JTextPane)e.getSource();
int linenum = 1;
int columnnum = 1;
try {
int caretpos = editArea.getCaretPosition();
linenum=getLineAtCaret(editArea)-1;
columnnum=getColumnAtCaret(editArea);
linenum += 1;
}
catch(Exception ex) { }
updateStatus(linenum, columnnum);
}
});
status=new JTextField();
status.setBackground(Color.LIGHT_GRAY);
internalFrame.add(status,BorderLayout.SOUTH);
tp.add(internalFrame);
scrollPane=new JScrollPane(textPane);
tp.setSelectedIndex(i-1);
internalFrame.add(scrollPane);
internalFrame.setVisible(true);
textPane.setText(t);
tp.addChangeListener(this);
textPanes.add(textPane);
textPane.setCaretPosition(0);
}
}
private void cutActionPerformed(java.awt.event.ActionEvent evt) {
textPane.cut();
}
private void selectAllActionPerformed(java.awt.event.ActionEvent evt) {
textPane.selectAll();
}
private void viewLineNumbersActionPerformed(java.awt.event.ActionEvent evt) {
AbstractButton button = (AbstractButton) evt.getSource();
if(button.isSelected()){
lnNum = new JTextPane();
lnNum.setEditable(false);
lnNum.setSize(50,50);
lnNum.setFont(new java.awt.Font("Miriam Fixed", 0, 13));
lnNum.setText(getText());
textPane.getDocument().addDocumentListener(new DocumentListener(){
#Override
public void changedUpdate(DocumentEvent de) {
lnNum.setText(getText());
}
#Override
public void insertUpdate(DocumentEvent de) {
lnNum.setText(getText());
}
#Override
public void removeUpdate(DocumentEvent de) {
lnNum.setText(getText());
}
});
scrollPane.getViewport().add(textPane);
scrollPane.setRowHeaderView(lnNum);
}
else{
scrollPane.setRowHeaderView(null);
}
}
public String getText(){
int caretPosition = textPane.getDocument().getLength();
javax.swing.text.Element root = textPane.getDocument().getDefaultRootElement();
String text = "1" + System.getProperty("line.separator");
for(int i = 2; i <= root.getElementIndex( caretPosition ) + 1; i++){
text += i + System.getProperty("line.separator");
}
return text;
}
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new OpenDemo().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JMenuItem cut;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem open;
private javax.swing.JMenuItem selectAll;
private javax.swing.JTabbedPane tp;
private javax.swing.JCheckBoxMenuItem viewLineNumbers;
// End of variables declaration
#Override
public void stateChanged(ChangeEvent ce) {
JTabbedPane sourceTabbedPane = (JTabbedPane) ce.getSource();
int index = sourceTabbedPane.getSelectedIndex();
try
{
textPane =textPanes.get(index);
}
catch(IndexOutOfBoundsException e1){
}
}
public int getLineAtCaret(JTextComponent component)
{
int caretPosition = component.getCaretPosition();
Element root = component.getDocument().getDefaultRootElement();
return root.getElementIndex( caretPosition ) + 1;
}
public int getColumnAtCaret(JTextComponent component)
{
FontMetrics fm = component.getFontMetrics( component.getFont() );
int characterWidth = fm.stringWidth( "0" );
int column = 0;
try
{
Rectangle r = component.modelToView( component.getCaretPosition() );
int width = r.x - component.getInsets().left;
column = width / characterWidth;
}
catch(BadLocationException ble) {}
return column + 1;
}
}
I think, i managed to answer all your problems, but i needed to create another class which i called 'OInternalFrame', so i will give you both code for those class. Tell me if that's what you were trying to achieve :
OpenDemo :
import java.awt.FileDialog;
import java.awt.FontMetrics;
import java.awt.Rectangle;
import java.beans.PropertyVetoException;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractButton;
import javax.swing.JTabbedPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
import javax.swing.text.BadLocationException;
import javax.swing.text.Element;
import javax.swing.text.JTextComponent;
public class OpenDemo extends javax.swing.JFrame implements ChangeListener{
private ArrayList<OInternalFrame> frames = new ArrayList<OInternalFrame>();
private OInternalFrame currentFrame;
int i=0;
public OpenDemo() {
initComponents();
viewLineNumbers.setSelected(false);
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
tp = new javax.swing.JTabbedPane();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
open = new javax.swing.JMenuItem();
cut = new javax.swing.JMenuItem();
selectAll = new javax.swing.JMenuItem();
viewLineNumbers = new javax.swing.JCheckBoxMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jMenu1.setText("File");
open.setText("Open");
open.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
openActionPerformed(evt);
}
});
jMenu1.add(open);
cut.setText("Cut");
cut.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cutActionPerformed(evt);
}
});
jMenu1.add(cut);
selectAll.setText("SelectAll");
selectAll.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
selectAllActionPerformed(evt);
}
});
jMenu1.add(selectAll);
viewLineNumbers.setSelected(true);
viewLineNumbers.setText("ViewLineNumbers");
viewLineNumbers.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
viewLineNumbersActionPerformed(evt);
}
});
jMenu1.add(viewLineNumbers);
jMenuBar1.add(jMenu1);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tp, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tp, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void openActionPerformed(java.awt.event.ActionEvent evt) {
FileDialog fd = new FileDialog(OpenDemo.this, "Select File", FileDialog.LOAD);
fd.show();
String title;
String sts;
if (fd.getFile() != null) {
sts = fd.getDirectory() + fd.getFile();
title=fd.getFile();
System.out.println(sts);
title=fd.getFile();
BufferedReader br = null;
StringBuffer str = new StringBuffer("");
try {
br = new BufferedReader(new FileReader(sts));
String line;
try {
while ((line = br.readLine()) != null) {
str.append(line + "\n");
}
} catch (IOException ex) {
Logger.getLogger(OpenDemo.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(OpenDemo.class.getName()).log(Level.SEVERE, null, ex);
}
String t = str.toString();
OInternalFrame internalFrame = new OInternalFrame("",true,true);
i++;
internalFrame.setName("Doc "+i);
internalFrame.setTitle(title);
try {
internalFrame.setSelected(true);
} catch (PropertyVetoException ex) {
Logger.getLogger(OpenDemo.class.getName()).log(Level.SEVERE, null, ex);
}
internalFrame.addInternalFrameListener(new InternalFrameAdapter() {
#Override
public void internalFrameClosing(InternalFrameEvent e) {
i--;
frames.remove(currentFrame);
tp.remove(currentFrame);
for(OInternalFrame frame : frames)
{
int index=frames.indexOf(frame);
tp.setTitleAt(index, "Doc "+(index+1));
}
}
});
tp.add(internalFrame);
tp.setSelectedIndex(i-1);
tp.addChangeListener(this);
frames.add(internalFrame);
currentFrame=internalFrame;
currentFrame.setText(t);
currentFrame.setVisible(true);
currentFrame.setLineViewer(viewLineNumbers.isSelected());
}
}
private void cutActionPerformed(java.awt.event.ActionEvent evt) {
currentFrame.cut();
}
private void selectAllActionPerformed(java.awt.event.ActionEvent evt) {
currentFrame.selectAll();
}
private void viewLineNumbersActionPerformed(java.awt.event.ActionEvent evt) {
AbstractButton button = (AbstractButton) evt.getSource();
currentFrame.setLineViewer(viewLineNumbers.isSelected());
}
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new OpenDemo().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JMenuItem cut;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem open;
private javax.swing.JMenuItem selectAll;
private javax.swing.JTabbedPane tp;
private javax.swing.JCheckBoxMenuItem viewLineNumbers;
// End of variables declaration
#Override
public void stateChanged(ChangeEvent ce) {
JTabbedPane sourceTabbedPane = (JTabbedPane) ce.getSource();
int index = sourceTabbedPane.getSelectedIndex();
try
{
currentFrame =frames.get(index);
currentFrame.setLineViewer(viewLineNumbers.isSelected());
}
catch(IndexOutOfBoundsException e1){
}
}
public int getLineAtCaret(JTextComponent component)
{
int caretPosition = component.getCaretPosition();
Element root = component.getDocument().getDefaultRootElement();
return root.getElementIndex( caretPosition ) + 1;
}
public int getColumnAtCaret(JTextComponent component)
{
FontMetrics fm = component.getFontMetrics( component.getFont() );
int characterWidth = fm.stringWidth( "0" );
int column = 0;
try
{
Rectangle r = component.modelToView( component.getCaretPosition() );
int width = r.x - component.getInsets().left;
column = width / characterWidth;
}
catch(BadLocationException ble) {}
return column + 1;
}
}
OInternalFrame :
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.Rectangle;
import javax.swing.JInternalFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Element;
import javax.swing.text.JTextComponent;
public class OInternalFrame extends JInternalFrame
{
private JTextArea textPane;
private JScrollPane scrollPane;
private JTextPane linePane;
private JTextField status;
private DocumentListener listen;
public OInternalFrame(String title,boolean resizable,boolean closable)
{
super(title,resizable,closable);
initComponents();
initListeners();
}
private void initComponents()
{
textPane = new JTextArea();
linePane = new JTextPane();
status = new JTextField();
scrollPane = new JScrollPane();
textPane.setFont(new java.awt.Font("Miriam Fixed", 0, 13));
status.setBackground(Color.LIGHT_GRAY);
linePane.setEditable(false);
linePane.setSize(50,50);
linePane.setFont(new java.awt.Font("Miriam Fixed", 0, 13));
status.setEditable(false);
// add(textPane);
add(scrollPane);
add(status,BorderLayout.SOUTH);
scrollPane.getViewport().add(textPane);
scrollPane.setRowHeaderView(linePane);
setVisible(true);
linePane.setVisible(false);
updateStatus(1,1);
scrollPane.setVisible(true);
}
private void initListeners()
{
textPane.addCaretListener(new CaretListener() {
#Override
public void caretUpdate(CaretEvent e) {
int linenum = 1;
int columnnum = 1;
try {
int caretpos = textPane.getCaretPosition();
linenum=getLineAtCaret()-1;
columnnum=getColumnAtCaret();
linenum += 1;
}
catch(Exception ex) { }
updateStatus(linenum, columnnum);
}
});
listen = new DocumentListener(){
#Override
public void changedUpdate(DocumentEvent de) {
linePane.setText(getText());
}
#Override
public void insertUpdate(DocumentEvent de) {
linePane.setText(getText());
}
#Override
public void removeUpdate(DocumentEvent de) {
linePane.setText(getText());
}
};
}
public int getLineAtCaret()
{
int line = 0;
int caretPosition = textPane.getCaretPosition();
try {
line = textPane.getLineOfOffset(caretPosition);
} catch (BadLocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return line+1;
}
public int getColumnAtCaret()
{
FontMetrics fm = textPane.getFontMetrics( textPane.getFont() );
int characterWidth = fm.stringWidth( "0" );
int column = 0;
try
{
Rectangle r = textPane.modelToView( textPane.getCaretPosition() );
int width = r.x - textPane.getInsets().left;
column = width / characterWidth;
}
catch(BadLocationException ble) {}
return column + 1;
}
private void updateStatus(int linenumber, int columnnumber)
{
status.setText("Line: " + linenumber + " Column: " + columnnumber);
}
public void setText(String t)
{
System.out.println(t);
textPane.setText(t);
textPane.setCaretPosition(0);
textPane.setVisible(true);
textPane.repaint();
}
public void setLineViewer(boolean enabled)
{
if(enabled)
{
linePane.setText(getText());
linePane.setCaretPosition(0);
linePane.revalidate();
linePane.repaint();
textPane.getDocument().addDocumentListener(listen);
}
else
{
linePane.setText("");
textPane.getDocument().removeDocumentListener(listen);
}
linePane.setVisible(enabled);
}
public void cut()
{
textPane.cut();
}
public void selectAll()
{
textPane.selectAll();
}
public String getText(){
int caretPosition = textPane.getLineCount();
String text = "1" + System.getProperty("line.separator");
for(int i = 2; i <= caretPosition-1; i++){
text += i + System.getProperty("line.separator");
}
return text;
}
}
Use the Actions provided by the DefaultEditorKit. For example:
JMenuItem cut = new DefaultEditorKit.CutAction();
For a "SelectAll" Action you will need to create your own by extending TextAction:
class SelectAll extends TextAction
{
public SelectAll()
{
super("Select All");
}
public void actionPerformed(ActionEvent e)
{
JTextComponent component = getFocusedComponent();
component.selectAll();
}
}
These Actions will work on the last text component that had focus.

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";

Java Terminal Only Printing Output From First Command

EDIT: The code now works! Here's how I did it:
package me.nrubin29.jterminal;
import javax.swing.*;
import javax.swing.filechooser.FileSystemView;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.*;
import java.util.ArrayList;
public class JTerminal extends JFrame {
private JTextPane area = new JTextPane();
private JTextField input = new JTextField("Input");
private SimpleAttributeSet inputSAS = new SimpleAttributeSet(), output = new SimpleAttributeSet(), error = new SimpleAttributeSet();
private File workingFolder = FileSystemView.getFileSystemView().getDefaultDirectory();
public JTerminal() throws IOException {
super("JTerminal");
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
StyleConstants.setForeground(inputSAS, Color.GREEN);
StyleConstants.setBackground(inputSAS, Color.BLACK);
StyleConstants.setForeground(output, Color.WHITE);
StyleConstants.setBackground(output, Color.BLACK);
StyleConstants.setForeground(error, Color.RED);
StyleConstants.setBackground(error, Color.BLACK);
input.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
try {
String command = input.getText();
if (command.equals("")) return;
setTitle("JTerminal (" + command.split(" ")[0] + ")");
input.setText("");
input.setEditable(false);
write(inputSAS, command);
Process bash = new ProcessBuilder("bash").directory(workingFolder).start();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(bash.getOutputStream());
outputStreamWriter.write(command);
outputStreamWriter.close();
int code = bash.waitFor();
writeStream(bash.getErrorStream(), error);
writeStream(bash.getInputStream(), output);
input.setEditable(true);
setTitle("JTerminal");
if (code == 0 && command.split(" ").length > 1) workingFolder = new File(command.split(" ")[1]);
} catch (Exception ex) { error(ex); }
}
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
});
area.setBackground(Color.black);
area.setCaretColor(Color.green);
area.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
area.setEditable(false);
JScrollPane pane = new JScrollPane(area);
pane.setBorder(BorderFactory.createLineBorder(Color.GREEN));
pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
pane.setPreferredSize(new Dimension(640, 460));
input.setBackground(Color.black);
input.setForeground(Color.green);
input.setCaretColor(Color.green);
input.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
input.setBorder(BorderFactory.createLineBorder(Color.GREEN));
add(pane);
add(input);
Dimension DIM = new Dimension(640, 480);
setPreferredSize(DIM);
setSize(DIM);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(true);
pack();
setVisible(true);
input.requestFocus();
}
public static void main(String[] args) throws IOException {
new JTerminal();
}
private void write(SimpleAttributeSet attributeSet, String... lines) {
try {
if (lines.length == 0) return;
for (String line : lines) {
area.getStyledDocument().insertString(area.getStyledDocument().getLength(), line + "\n", attributeSet);
}
area.getStyledDocument().insertString(area.getStyledDocument().getLength(), "\n", attributeSet);
}
catch (Exception e) { error(e); }
}
private void error(Exception e) {
write(error, "An error has occured: " + e.getLocalizedMessage());
e.printStackTrace(); //TODO: temp.
}
private void writeStream(InputStream s, SimpleAttributeSet color) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(s));
ArrayList<String> strs = new ArrayList<String>();
while(reader.ready()) strs.add(reader.readLine());
if (strs.size() > 0) write(color, strs.toArray(new String[strs.size()]));
}
catch (Exception e) { error(e); }
}
}
I have been working on a Java terminal application. It works except that it only prints the output of the first command. Here's a picture of the GUI when I try to run ls more than once.
package me.nrubin29.jterminal;
import javax.swing.*;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.*;
import java.util.ArrayList;
public class JTerminal extends JFrame {
private JTextPane area = new JTextPane();
private JTextField input = new JTextField("Input");
private SimpleAttributeSet inputSAS = new SimpleAttributeSet(), output = new SimpleAttributeSet(), error = new SimpleAttributeSet();
public JTerminal() throws IOException {
super("JTerminal");
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
StyleConstants.setForeground(inputSAS, Color.GREEN);
StyleConstants.setBackground(inputSAS, Color.BLACK);
StyleConstants.setForeground(output, Color.WHITE);
StyleConstants.setBackground(output, Color.BLACK);
StyleConstants.setForeground(error, Color.RED);
StyleConstants.setBackground(error, Color.BLACK);
final Process bash = new ProcessBuilder("/bin/bash").start();
input.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
try {
String command = input.getText();
if (command.equals("")) return;
setTitle("JTerminal (" + command.split(" ")[0] + ")");
input.setText("");
input.setEditable(false);
write(inputSAS, command);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(bash.getOutputStream());
outputStreamWriter.write(command);
outputStreamWriter.close();
bash.waitFor();
writeStream(bash.getErrorStream(), error);
writeStream(bash.getInputStream(), output);
input.setEditable(true);
setTitle("JTerminal");
} catch (Exception ex) { error(ex); }
}
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
});
area.setBackground(Color.black);
area.setCaretColor(Color.green);
area.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
area.setEditable(false);
JScrollPane pane = new JScrollPane(area);
pane.setBorder(BorderFactory.createLineBorder(Color.GREEN));
pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
pane.setPreferredSize(new Dimension(640, 460));
input.setBackground(Color.black);
input.setForeground(Color.green);
input.setCaretColor(Color.green);
input.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
input.setBorder(BorderFactory.createLineBorder(Color.GREEN));
add(pane);
add(input);
Dimension DIM = new Dimension(640, 480);
setPreferredSize(DIM);
setSize(DIM);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(true);
pack();
setVisible(true);
input.requestFocus();
}
public static void main(String[] args) throws IOException {
new JTerminal();
}
private void write(SimpleAttributeSet attributeSet, String... lines) {
try {
area.getStyledDocument().insertString(area.getStyledDocument().getLength(), "\n", attributeSet);
for (String line : lines) {
area.getStyledDocument().insertString(area.getStyledDocument().getLength(), line + "\n", attributeSet);
}
}
catch (Exception e) { error(e); }
}
private void error(Exception e) {
write(error, "An error has occured: " + e.getLocalizedMessage());
e.printStackTrace(); //TODO: temp.
}
private void writeStream(InputStream s, SimpleAttributeSet color) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(s));
ArrayList<String> strs = new ArrayList<String>();
while(reader.ready()) strs.add(reader.readLine());
if (strs.size() > 0) write(color, strs.toArray(new String[strs.size()]));
}
catch (Exception e) { error(e); }
}
}
A Process object can be used only once, so subsequent calls to Process.waitFor() just immediately return (as the process is already terminated).
Instead you have to request a new Process each time from your ProcessBuilder.
Here is the correct code:
package me.nrubin29.jterminal;
import javax.swing.*;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.*;
import java.util.ArrayList;
public class JTerminal extends JFrame {
private JTextPane area = new JTextPane();
private JTextField input = new JTextField("Input");
private SimpleAttributeSet inputSAS = new SimpleAttributeSet(), output = new SimpleAttributeSet(), error = new SimpleAttributeSet();
public JTerminal() throws IOException {
super("JTerminal");
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
StyleConstants.setForeground(inputSAS, Color.GREEN);
StyleConstants.setBackground(inputSAS, Color.BLACK);
StyleConstants.setForeground(output, Color.WHITE);
StyleConstants.setBackground(output, Color.BLACK);
StyleConstants.setForeground(error, Color.RED);
StyleConstants.setBackground(error, Color.BLACK);
final ProcessBuilder builder = new ProcessBuilder("/bin/bash");
input.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
try {
String command = input.getText();
if (command.equals("")) return;
setTitle("JTerminal (" + command.split(" ")[0] + ")");
input.setText("");
input.setEditable(false);
write(inputSAS, command);
Process bash = builder.start();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(bash.getOutputStream());
outputStreamWriter.write(command);
outputStreamWriter.close();
bash.waitFor();
writeStream(bash.getErrorStream(), error);
writeStream(bash.getInputStream(), output);
input.setEditable(true);
setTitle("JTerminal");
} catch (Exception ex) { error(ex); }
}
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
});
area.setBackground(Color.black);
area.setCaretColor(Color.green);
area.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
area.setEditable(false);
JScrollPane pane = new JScrollPane(area);
pane.setBorder(BorderFactory.createLineBorder(Color.GREEN));
pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
pane.setPreferredSize(new Dimension(640, 460));
input.setBackground(Color.black);
input.setForeground(Color.green);
input.setCaretColor(Color.green);
input.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
input.setBorder(BorderFactory.createLineBorder(Color.GREEN));
add(pane);
add(input);
Dimension DIM = new Dimension(640, 480);
setPreferredSize(DIM);
setSize(DIM);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(true);
pack();
setVisible(true);
input.requestFocus();
}
public static void main(String[] args) throws IOException {
new JTerminal();
}
private void write(SimpleAttributeSet attributeSet, String... lines) {
try {
area.getStyledDocument().insertString(area.getStyledDocument().getLength(), "\n", attributeSet);
for (String line : lines) {
area.getStyledDocument().insertString(area.getStyledDocument().getLength(), line + "\n", attributeSet);
}
}
catch (Exception e) { error(e); }
}
private void error(Exception e) {
write(error, "An error has occured: " + e.getLocalizedMessage());
e.printStackTrace(); //TODO: temp.
}
private void writeStream(InputStream s, SimpleAttributeSet color) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(s));
ArrayList<String> strs = new ArrayList<String>();
while(reader.ready()) strs.add(reader.readLine());
if (strs.size() > 0) write(color, strs.toArray(new String[strs.size()]));
}
catch (Exception e) { error(e); }
}
}
Once a process has exited, it can not be "read" from or "written" to.
You're code will also block on the "waitFor" method, meaning that your UI won't be updated until the process has completed running. This is really helpful...
Instead, you need to start the process and allow it to continue running, monitoring the state in the background.
Because Swing is a single threaded environment, you need to be careful about how you handle long running/blocking processes and updates to the UI.
To this end, I've used a SwingWorker to read the output of the Process in a background thread and re-sync the updates back to the Event Dispatching Thread. This allows the UI to continue running and remain responsive while the output from the running process is read in...
Also, instead of "running" a new command each time, creating a new process, you will need to write to the Process's input put stream.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestTerminal {
public static void main(String[] args) {
new TestTerminal();
}
public TestTerminal() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextArea output;
private JTextField input;
private Process process;
public TestPane() {
setLayout(new BorderLayout());
output = new JTextArea(20, 20);
input = new JTextField(10);
output.setLineWrap(false);
output.setWrapStyleWord(false);
output.setEditable(false);
output.setFocusable(false);
add(new JScrollPane(output));
add(input, BorderLayout.SOUTH);
input.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String cmd = input.getText() + "\n";
input.setText(null);
output.append("\n" + cmd + "\n\n");
if (process == null) {
ProcessBuilder pb = new ProcessBuilder("bash");
pb.directory(new File("."));
try {
process = pb.start();
InputStreamWorker isw = new InputStreamWorker(output, process.getInputStream());
isw.execute();
} catch (IOException ex) {
ex.printStackTrace();
input.setEnabled(false);
}
new Thread(new Runnable() {
#Override
public void run() {
int exit = -1;
try {
exit = process.waitFor();
} catch (InterruptedException ex) {
}
System.out.println("Exited with " + exit);
input.setEnabled(false);
}
}).start();
}
OutputStream os = process.getOutputStream();
try {
os.write(cmd.getBytes());
os.flush();
} catch (IOException ex) {
ex.printStackTrace();
input.setEnabled(false);
}
}
});
}
}
public class InputStreamWorker extends SwingWorker<Void, Character> {
private InputStream is;
private JTextArea output;
public InputStreamWorker(JTextArea output, InputStream is) {
this.is = is;
this.output = output;
}
#Override
protected void process(List<Character> chunks) {
StringBuilder sb = new StringBuilder(chunks.size());
for (Character c : chunks) {
sb.append(c);
}
output.append(sb.toString());
}
#Override
protected Void doInBackground() throws Exception {
int in = -1;
while ((in = is.read()) != -1) {
publish((char)in);
}
return null;
}
}
}
I would also recommend that you avoid KeyListener where you can. JTextField utilises a ActionListener, which will be called when ever the user presses the "action" key, what ever that might be for the given platform...

Categories