JTable doesn't update after SQL insert - java

I'm struggeling the whole day with a stupid problem. I insert with executeupdate a row in my database. I tried it with fireTableDataChanged, setModel and every hint i could find here.
But nothing changes. The data is inserted and only if i reopen my app i can see my insert.
I hope this class is enough to solve my problem. Otherwise i could paste my executeupdate statement or my mainclass.
I really hope you can help me.
Table
public TabelleErfasst()
{
super(new GridLayout(1, 0));
JTable table = new JTable();
table.setPreferredScrollableViewportSize(new Dimension(950, 300));
table.setFillsViewportHeight(true);
DefaultTableModel model = new DefaultTableModel();
model.setRowCount(0);
table.setModel(model);
Object[] columnsName = new Object[7];
columnsName[0] = "Vorname";
columnsName[1] = "Nachname";
columnsName[2] = "Straße";
columnsName[3] = "Stadt";
columnsName[4] = "Hat abgestimmt für";
columnsName[5] = "ID";
columnsName[6] = "Sterne";
model.setColumnIdentifiers(columnsName);
Object[] rowData = new Object[8];
ArrayList<Stimmzettel> stimmzettel = ErfasstDatabase.getStimmzettel();
for (int i = 0; i < stimmzettel.size(); i++) {
rowData[0] = stimmzettel.get(i).getVorName();
rowData[1] = stimmzettel.get(i).getNachName();
rowData[2] = stimmzettel.get(i).getStrasse();
rowData[3] = stimmzettel.get(i).getStadt();
rowData[4] = stimmzettel.get(i).getAbgestimmtFuer();
rowData[5] = stimmzettel.get(i).getProjektId();
rowData[6] = stimmzettel.get(i).getSterne();
model.addRow(rowData);
}
// Ändere Spaltenbreite, wenn i == 1 -> breiter
TableColumn column = null;
for (int i = 0; i < 7; i++) {
column = table.getColumnModel().getColumn(i);
if (i == 1) {
column.setPreferredWidth(150); //
} else if (i == 4) {
column.setPreferredWidth(200);
} else if (i == 5) {
column.setPreferredWidth(45);
} else if (i == 6) {
column.setPreferredWidth(45);
} else {
column.setPreferredWidth(150);
}
}
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);
}
}
Statement
public class DBProjektController {
public void insert(String f1, String f2, String f3, String f4, String f5, String f6, String f7) {
if (f1.isEmpty()) {
System.out.println("The ID cannot be null!");
} else {
try {
Connection con;
con = DriverManager.getConnection("jdbc:ucanaccess://C:/Projekt/DB/erfasst.accdb");
Statement statement = con.createStatement();
statement.executeUpdate("INSERT INTO ERFASST(VORNAME, NAME, STRASSE, ORT, ABGESTIMMT_PROJEKT, PROJEKTID, STERNE) VALUES('" + f1 + "','" + f2 + "','" + f3 + "','" + f4 + "','" + f5 + "','" + f6 + "','" + f7 + "')");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Snippet from my MainClass (I deleteted some parts that doesn't really concern my problem)
public class Gui extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
// Frame
JFrame frame = new JFrame();
// Erstelle JTabbedPane
JTabbedPane jtp = new JTabbedPane();
// Panel
JPanel panel = new JPanel();
public Gui() {
frame.getContentPane().add(jtp);
JPanel pAbstimmung = new JPanel(null);
TabelleErfasst tabelleErfasst = new TabelleErfasst();
tabelleErfasst.setSize(950, 350);
tabelleErfasst.setLocation(35, 80);
JButton bSterneExport = new JButton("Sterne exportieren");
bSterneExport.setSize(300, 60);
bSterneExport.setLocation(682, 480);
JButton bEintragNeu = new JButton("Ausgewählten Eintrag löschen");
bEintragNeu.setSize(300, 60);
bEintragNeu.setLocation(358, 480);
JButton bEintragLoeschen = new JButton("Alle Einträge löschen");
bEintragLoeschen.setSize(300, 60);
bEintragLoeschen.setLocation(35, 480);
JLabel lZettelSession = new JLabel("Alle eingetragenen Stimmzettel der aktuellen Session");
// Inhalte zu Abstimmungsergebnis
pAbstimmung.add(tabelleErfasst);
pAbstimmung.add(bEintragLoeschen);
pAbstimmung.add(bEintragNeu);
pAbstimmung.add(bSterneExport);
pAbstimmung.add(lZettelSession);
jtp.addTab("Abstimmungsergebnis", pAbstimmung);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
bStimmeKontrolle.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new Thread(new Runnable() {
public void run() {
new DBProjektController().insert(erfasstVorname.getText(), erfasstNachname.getText(),
erfasstStrasse.getText(), erfasstStadt.getText(), projektAuswahl.getText(),
erfasstId.getText(), sterneGruppe.getSelection().getActionCommand());
}
}).start();
TabelleErfasst tabelleErfasst = new TabelleErfasst();
jtp.setSelectedIndex(3);
}
});
// Titel des Fensters
frame.setTitle("AfVF");
// Gr��e des Fensters
frame.setResizable(false);
frame.pack();
frame.setSize(1024, 650);
frame.setVisible(true);
}
}

Related

JAVA jframe.remove(panel) doesn't work as expected

I have a Jframe with two panels and i am trying to change the panels/views using jmenu items.
The first panel adds data to a database. User can then switch to the view panel by clicking the JMenuBarItem.
The Second panel fetches data from the database and displays the results in a JTable.
Everything works fine but when i switch back and forth to the second panel it adds another panel instead of removing it/replacing it. See linked images below to better understand
First Panel
Second Panel
Second Panel after switching back and forth
package employeerecords3;
import java.awt.*;
import java.awt.event.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import javax.swing.*;
public class EmployeeRecords3 extends JFrame {
JLabel empnolb, empnamelb, empdptlb, basicsallb, hseallowancelb;
JTextField empnotf, empnametf, empdpttf, basicsaltf, hseallowancetf;
JButton submitbtn, cancelbtn;
String host = "jdbc:mysql://localhost:3306/employee";
String username = "root";
String password = "";
EmployeeRecords3() {
setTitle("Employee Records");
final JPanel addpanel = new JPanel();
final JPanel viewpanel = new JPanel();
setTitle("Employee Records");
JMenuBar menubar = new JMenuBar();
setJMenuBar(menubar);
JMenu file = new JMenu("File");
menubar.add(file);
JMenuItem add = new JMenuItem("Add Employee");
JMenuItem view = new JMenuItem("View Employees");
file.add(add);
file.add(view);
add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (viewpanel.isShowing()) {
remove(viewpanel);
add(addpanel);
}
revalidate();
repaint();
}
});
view.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
java.util.List<String[]> datalist = new ArrayList<>();
String[] columnNames = {"Emp ID", "Emp Name", "Department", "Basic Pay", "House Allowance", "Payee", "NHIF", "NSSF", "Pension", "NetPay"};
try {
String query = "SELECT * FROM payroll";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(host, username, password);
Statement st = con.prepareStatement(query);
ResultSet rs = st.executeQuery(query);
while (rs.next()) {
String[] results = {rs.getString(1), rs.getString(2), rs.getString(3), Double.toString(rs.getDouble(4)), Double.toString(rs.getDouble(5)), Double.toString(rs.getDouble(6)), Double.toString(rs.getDouble(7)), Double.toString(rs.getDouble(8)), Double.toString(rs.getDouble(9)), Double.toString(rs.getDouble(10))};
datalist.add(results);
}
con.close();
String[][] data = new String[datalist.size()][];
data = datalist.toArray(data);
JTable table = new JTable(data, columnNames);
JScrollPane sp = new JScrollPane(table);
viewpanel.add(sp);
} catch (Exception ex) {
ex.printStackTrace();
}
if (addpanel.isShowing()) {
remove(addpanel);
add(viewpanel);
} else if (viewpanel.isShowing()) {
remove(viewpanel);
add(viewpanel);
}
revalidate();
repaint();
}
});
empnolb = new JLabel("Emp No");
empnamelb = new JLabel("Name");
empdptlb = new JLabel("Department");
basicsallb = new JLabel("Basic Pay");
hseallowancelb = new JLabel("House Allowance");
empnotf = new JTextField();
empnametf = new JTextField();
empdpttf = new JTextField();
basicsaltf = new JTextField();
hseallowancetf = new JTextField();
submitbtn = new JButton("Submit");
cancelbtn = new JButton("Cancel");
Submit submithandler = new Submit();
submitbtn.addActionListener(submithandler);
Cancel cancelhandler = new Cancel();
cancelbtn.addActionListener(cancelhandler);
addpanel.add(empnolb);
addpanel.add(empnotf);
addpanel.add(empnamelb);
addpanel.add(empnametf);
addpanel.add(empdptlb);
addpanel.add(empdpttf);
addpanel.add(basicsallb);
addpanel.add(basicsaltf);
addpanel.add(hseallowancelb);
addpanel.add(hseallowancetf);
addpanel.add(submitbtn);
addpanel.add(cancelbtn);
addpanel.setLayout(new GridLayout(6, 2));
viewpanel.setLayout(new GridLayout(1, 1));
add(addpanel);
setSize(300, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private class Submit implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
String empNo, empName, department;
double grossPay, basicPay, hseAllowance, payee, nhif, nssf, pension, netPay;
empNo = empnotf.getText();
empName = empnametf.getText();
department = empdpttf.getText();
basicPay = Double.parseDouble(basicsaltf.getText());
hseAllowance = Double.parseDouble(hseallowancetf.getText());
grossPay = basicPay + hseAllowance;
payee = 0.3 * grossPay;
if (grossPay > 100000) {
nhif = 1200;
} else {
nhif = 320;
}
nssf = 200;
pension = 0.05 * basicPay;
netPay = grossPay - (payee - nhif - nssf - pension);
String query = "INSERT INTO payroll(EmpID,EmpName,Department,BasicPay,HouseAllowance,Payee,NHIF,NSSF,Pension,NetPay) VALUES('" + empNo + "','" + empName + "','" + department + "','" + basicPay + "','" + hseAllowance + "','" + payee + "','" + nhif + "','" + nssf + "','" + pension + "','" + netPay + "')";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(host, username, password);
Statement st = con.prepareStatement(query);
int count = st.executeUpdate(query);
boolean action = (count > 0);
if (action) {
empnotf.setText(null);
empnametf.setText(null);
empdpttf.setText(null);
basicsaltf.setText(null);
hseallowancetf.setText(null);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
private class Cancel implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
public static void main(String[] args) {
EmployeeRecords3 er = new EmployeeRecords3();
}
}
The mistake you made is that you create a new JTable every time you open the viewpanel. You not only create a new one, you add it to your view-JPanel. This is why you get the weird behaviour.
This code snippet fixes your problem. I just added the removeAll() method call to the add-JPanel ActionListener. When the add-JPanel is opened, the old JTable is removed from the view-JPanel. I had to comment out your database interactions.
// ...
// ...
// ...
add.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
if (viewpanel.isShowing())
{
remove(viewpanel);
/*
* I basically just added this one line.
* Since you want to make a fresh query after
* you come back to the viewpanel, we can delete
* all the elements (which is only the JTable).
*/
viewpanel.removeAll();
add(addpanel);
}
revalidate();
repaint();
}
});
view.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
java.util.List<String[]> datalist = new ArrayList<>();
String[] columnNames = {"Emp ID", "Emp Name", "Department",
"Basic Pay", "House Allowance", "Payee", "NHIF", "NSSF",
"Pension", "NetPay"};
try
{
// String query = "SELECT * FROM payroll";
// Class.forName("com.mysql.jdbc.Driver");
// Connection con = DriverManager.getConnection(host, username,
// password);
// Statement st = con.prepareStatement(query);
// ResultSet rs = st.executeQuery(query);
String[] results = {"a", "b", "c", "d", "e", "f", "g", "h",
"i", "j"};
datalist.add(results);
// con.close();
String[][] data = new String[datalist.size()][];
data = datalist.toArray(data);
JTable table = new JTable(data, columnNames);
JScrollPane sp = new JScrollPane(table);
viewpanel.add(sp);
}
catch (Exception ex)
{
ex.printStackTrace();
}
if (addpanel.isShowing())
{
remove(addpanel);
add(viewpanel);
}
else if (viewpanel.isShowing())
{
remove(viewpanel);
add(viewpanel);
}
revalidate();
repaint();
}
});
// ...
// ...
// ...
The solution on top is not the only one of course. I don't know where you wanna go with this UI, but you can just remove the contents of the table and refill them as soon as you open the view-JPanel again.
Another solution would be to remove the JTable specifically (but in this case you probably need to have it as a field, because you create the table in a block that you can't reference from your add.addActionListener-Block)
The third solution would be to add a boolean flag, that checks if the table has been loaded and only create a new JTable, if it hasn't.

JLabel and JTextField don't appper in the swing form

Iwould like to create a form using java eclipse. The problem is i cannot obtain the total added JLabel and JTextField.this is my code:
class gestiontache extends JFrame{
JFrame f;
JPanel p1, p2, p3;
JTabbedPane tp;
JLabel l1, l2, l3,l4,l5;
JComboBox tf3categor;
JComboBox tf4Affiliation;
JComboBox tf5montant;
JTextField tf1, tf2;
JScrollPane sp1;
JButton savebtn, resetbtn, editbtn;
private static String FILE = "c:/temp/DocumentPdf.pdf";
private static Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18,
Font.BOLD);
private static Font redFont = new Font(Font.FontFamily.TIMES_ROMAN, 12,
Font.NORMAL, BaseColor.RED);
private static Font subFont = new Font(Font.FontFamily.TIMES_ROMAN, 16,
Font.BOLD);
private static Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12,
Font.BOLD);
gestiontache() {
f = new JFrame("Form");
GridLayout lay1= new GridLayout(12, 2);
GridLayout lay2= new GridLayout(5, 2);
p1 = new JPanel(lay1);
p2 = new JPanel(lay2);
lay1.setHgap(5); //Cinq pixels d'espace entre les colonnes (H comme Horizontal)
lay1.setVgap(5); //Cinq pixels d'espace entre les lignes (V comme Vertical)
lay2.setHgap(5);
lay2.setVgap(5);
tp = new JTabbedPane();
l1 = new JLabel("Nom");
l2 = new JLabel("Prénom");
l3 = new JLabel("Catégorie");
l4 = new JLabel("Affiliation");
l5 = new JLabel("Montant à payer");
tf1 = new JTextField(12);
tf2 = new JTextField(12);
tf3categor = new JComboBox( new String[] { "Medecin", "Technicien", "Pharmacien","Autre" });
tf4Affiliation =new JComboBox( new String[] { "K", "T", "Sf","Gab","Toze","Med","Tat","Na","B","G","Si","Ga","Ke","Kr" });
tf5montant = new JComboBox( new String[] { "15 Dinars", "30 Dinars"});
savebtn = new JButton(" Ajouter ");
resetbtn = new JButton(" Annuler");
editbtn = new JButton(" Imprimer");
p1.add(l1);
p1.add(tf1);
p1.add(l2);
p1.add(tf2);
p1.add(l3);
p1.add(tf3categor);
p1.add(l4);
p1.add(tf4Affiliation);
p1.add(l5);
p1.add(tf5montant);
p1.add(savebtn);
p1.add(resetbtn);
p2.add(l1);
p2.add(tf1);
p2.add(l2);
p2.add(tf2);
p2.add(editbtn);
resetbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
clear();
}
});
savebtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String nom, prenom,categorie, affiliation, montant;
nom = tf1.getText();
prenom = tf2.getText();
categorie=(String) tf3categor.getSelectedItem();
affiliation=(String) tf4Affiliation.getSelectedItem();
montant=(String) tf5montant.getSelectedItem();
String url = "jdbc:mysql://localhost:3306/seminaire";
String userid = "root";
String password = "";
try {
Connection connection = DriverManager.getConnection(url,
userid, password);
Statement st = connection.createStatement();
if (nom != "" && prenom != ""&& categorie!= ""&& affiliation!= ""&& montant!= "") {
st.executeUpdate("insert into participant values('" + nom
+ "','" + prenom + "','" + categorie + "','"+affiliation+"','"+montant+"')");
JOptionPane.showMessageDialog(null,"Données insérées avec succès");
clear();
} else {
JOptionPane.showMessageDialog(null, "merci de saisir vos données");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
editbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String nom, prenom,categorie, affiliation, montant;
nom = tf1.getText();
prenom = tf2.getText();
String url = "jdbc:mysql://localhost:3306/seminaire";
String userid = "root";
String password = "";
try {
Connection connection = DriverManager.getConnection(url,
userid, password);
Statement st = connection.createStatement();
if (nom != "" && prenom != "") {
ResultSet rs= st.executeQuery("SELECT * FROM participant
WHERE nom=nom && prenom=prenom");
while (rs.next())
{
String nm = rs.getString("nom");
String prnm = rs.getString("prenom");
String cat = rs.getString("categorie");
String afl=rs.getString("affiliation");
String mnt=rs.getString("montant");
// print the results
Document document = new Document();
try {
PdfWriter.getInstance(document, new FileOutputStream(FILE));
//open
document.open();
Paragraph p = new Paragraph();
p.add("Reçu");
p.setAlignment(Element.ALIGN_CENTER);
document.add(p);
Paragraph p2 = new Paragraph();
p2.add(nm); //no alignment
document.add(p2);
Font f = new Font();
f.setStyle(Font.BOLD);
f.setSize(8);
document.add(new Paragraph("This is my paragraph 3", f));
//close
document.close();
System.out.println("Done");
} catch (FileNotFoundException | DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
else {
JOptionPane.showMessageDialog(null, "merci de saisir vos données");
}
}
catch (Exception e)
{
System.err.println(e.getMessage());
}
}});
}
void dis() {
f.getContentPane().add(tp);
tp.addTab("Ajouter participant", p1);
tp.addTab("Imprimer attestation", p2);
f.setSize(500, 400);
f.setVisible(true);
f.setResizable(true);
}
void clear()
{
tf1.setText("");
tf2.setText("");
tf3categor.setSelectedItem("");
tf4Affiliation.setSelectedItem("");
tf5montant.setSelectedItem("");
}
public static void main(String z[]) {
gestiontache data = new gestiontache();
data.dis();
}
}
`
The problem here is the JLabel and JTextField(nom, prenom)don't appear in the form in order to insert or select from database. Have any idea how can i correct it please. Thank you
p2.add(l1);
p2.add(tf1);
p2.add(l2);
p2.add(tf2);
These above fields are added in both p1(Tab1) and p2(Tab2) Panels.
Thats why its not showing.
You must create seperate controls for both p1 and p2 panels. Don't reuse same controls in two panels.
For example:
l7 = new JLabel("Normal");
p2.add(l7);

JtextField Settext and static type

I have a Swing Form (Java). In this form I have field, for example Name1. I initialize it so:
private JTextField Name1;
In this code i'm adding JTextField Name1 into my Form:
tabbedPane.addTab("T6", null, panel, "T6");
panel.setLayout(null);
Name1.setBounds(73, 11, 674, 20);
panel.add(Name1);
Additionaly I have Button1 on my form. The event in this button is changing the value of Name1. Its work normaly.
Moreover I have a Button 2 that hiding the Tab with Name1:
tabbedPane.remove(1);
tabbedPane.repaint();
tabbedPane.revalidate();
frame.repaint();
frame.revalidate();
(And, of course, I turn on my tabpane again after this)
After all that, by the pressing the Button 4 I want to change the vlue of Name1 to some text.
But it doesn't work!!!!!! SetTex doesnt work. The field is empty.
So, if I change the Name1 declaration from
private JTextField Name1;
to
static JTextField Name1;
Yes, it works. BUT! Then I can't change the value of Name1 by using
Name1.Settext("Example");
What i have to do to make Name1 available after Button 4 pressed and changable ????
The all code is:
public class GUI {
public JTextField Name_textField;
public static void main(String[] args) {
DB_Initialize();
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUI window = new GUI();
window.frame.setVisible(true);
window.frame.setResizable(false);
FirstConnect FC = window.new FirstConnect();
ConnectStatus = true;
FC.FirstEntry();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public GUI() {
CurrentEnty_textField = new JTextField();
Name_textField = new JTextField();
EntriesCountlbl = new JLabel("New label");
initialize();
EntriesCountlbl.setText(Integer.toString(EC1));
if (LoginStatus == true) {
System.out.println("LoginStatus == true");
AdminPartOn();
btnNewButton.setEnabled(false);
} else {
btnNewButton_3.setEnabled(false);
tabbedPane.setEnabledAt(1, false);
// UnableForm();
AdminPartOff();
}
}
public static void DB_Initialize() {
conn3 = con3.DoConnect();
int ID;
ArrayList<String> list = new ArrayList<String>();
String l;
String p;
list = con3.LoginFileRead();
if (list.size() == 2) {
l = list.get(0);
p = list.get(1);
System.out.println("Логин из файла = " + l);
System.out.println("Пароль из файла = " + p);
ID = con3.CRMUserRequest(conn3, l, p);
AdminPanelData = con3.CRMUserFullData(conn3, l, p);
if (ID != 0) {
System.out.println("ID Юзера = " + ID);
LoginStatus = true;
}
}
EC1 = con3.CRMQuery_EntriesCount(conn3); // запрашиваем кол-во записей
StatusTableEntriesCount = con3.CRMQueryStatus_EntriesCount(conn3);
StatusTableFromCount = con3.CRMQueryFRom_EntriesCount(conn3);
System.out.println("Entries count(Из модуля GYU): " + EC1);
if (EC1 > 0) {
CurrentEntry = 1;
System.out.println("Все ОК, текущая запись - " + CurrentEntry);
} else {
System.out.println("Выскакивает обработчик ошибок");
}
con3.Ini();
con3.CRMQuery2(conn3, EC1 + 1);
StatusColumn = con3.CRMQueryStatus(conn3, StatusTableEntriesCount);
FromColumn = con3.CRMQueryFrom(conn3, StatusTableFromCount);
}
public class FirstConnect {
public void FirstEntry() {
int CurStatus = F.GetStatus(CurrentEntry - 1);
int CurFrom = F.GetFrom(CurrentEntry - 1);
if (LoginStatus != false) {
Name_textField.setText(F.GetName(CurrentEntry - 1));
} else {
Name_textField.setText("-");
}
}
}
private void initialize() {
frame = new JFrame();
panel = new JPanel();
frame.setBounds(100, 100, 816, 649);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setBounds(10, 250, 780, 361);
frame.getContentPane().add(tabbedPane);
JPanel panel_1 = new JPanel();
tabbedPane.addTab("\u0412\u0445\u043E\u0434", null, panel_1, null);
btnNewButton = new JButton("\u0412\u0445\u043E\u0434");
btnNewButton.setBounds(263, 285, 226, 37);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int ID;
ID = con3.CRMUserRequest(conn3, LoginField.getText(), PasswordField.getText());
if (ID == 0) {
} else {
MainTab();
FirstEntry3();
}
}
});
panel_1.setLayout(null);
panel_1.add(btnNewButton);
tabbedPane.addTab("\u041A\u043B\u0438\u0435\u043D\u0442", null, panel,
"\u041A\u043E\u043D\u0442\u0430\u043A\u0442\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435 \u043A\u043B\u0438\u0435\u043D\u0442\u0430");
panel.setLayout(null);
// Name_textField = new JTextField();
Name_textField.setBounds(73, 11, 674, 20);
panel.add(Name_textField);
Name_textField.setHorizontalAlignment(SwingConstants.CENTER);
Name_textField.setColumns(10);
NextEntryButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (NextEntryButton.isEnabled() != false) {
if (CurrentEntry < EC1) {
CurrentEntry = CurrentEntry + 1;
int CurStatus = F.GetStatus(CurrentEntry - 1);
int CurFrom = F.GetFrom(CurrentEntry - 1);
Name_textField.setText(F.GetName(CurrentEntry - 1));
} else {
}
}
}
});
}
public void MainTab() {
tabbedPane.addTab("1", null, panel,
"1");
tabbedPane.setEnabledAt(1, true);
panel.setLayout(null);
}
public void FirstEntry3() {
Name_textField.setText(F.GetName(CurrentEntry - 1));
}
}

Java application with multiple jframe-threads

Hello all I am building a java application where i want to select a users from a list of users and create a new JFrame to chat with(for example a new user-to-user chatbox). I have created the new JFrame into a thread i called it ChatGUI.
I am working with Smack so each of my ChatGUI object should have a MessageListener. When i exit a chatGUI thread it should delete everyting the thread created(for example the MessegeListener) and exit without interrupting any of the other threads(with their own MessegeListeners).
public class ChatGUI extends Thread {
volatile String remoteEndJID, remoteEndName, localEndJID, localEndName;
JFrame newFrame = new JFrame();
JButton sendMessage;
JTextField messageBox;
JTextPane chatBox;
Chat chat;
ChatMessageListener cMsgListener;
XMPPConnection connection;
StyleContext sContext;
volatile LinkedList<String> msgList;
DefaultStyledDocument sDoc;
public ChatGUI(String remoteEndJID, String remoteEndName, String localEndJID, String localEndName,
XMPPConnection connection, Chat chat, boolean createdLocaly, LinkedList<String> msgList) {
this.localEndName = localEndName;
this.remoteEndJID = remoteEndJID;
this.remoteEndName = remoteEndName;
this.localEndJID = localEndJID;
this.connection = connection;
this.chat = chat;
this.msgList = msgList;
if(createdLocaly==true)
cMsgListener = new ChatMessageListener();
start();
}
public void run() {
// Set title
newFrame.setTitle(remoteEndName);
newFrame.addWindowListener( new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
JFrame frame = (JFrame)e.getSource();
stop();
}
});
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
JPanel southPanel = new JPanel();
southPanel.setLayout(new GridBagLayout());
messageBox = new JTextField(30);
messageBox.requestFocusInWindow();
sendMessage = new JButton("Invia");
sendMessage.addActionListener(new sendMessageButtonListener());
sendMessage.setContentAreaFilled(false);
newFrame.getRootPane().setDefaultButton(sendMessage);
sContext = new StyleContext();
sDoc = new DefaultStyledDocument(sContext);
chatBox = new JTextPane(sDoc);
chatBox.setEditable(false);
mainPanel.add(new JScrollPane(chatBox), BorderLayout.CENTER);
GridBagConstraints left = new GridBagConstraints();
left.anchor = GridBagConstraints.LINE_START;
left.fill = GridBagConstraints.HORIZONTAL;
left.weightx = 512.0D;
left.weighty = 1.0D;
GridBagConstraints right = new GridBagConstraints();
right.insets = new Insets(0, 10, 0, 0);
right.anchor = GridBagConstraints.LINE_END;
right.fill = GridBagConstraints.NONE;
right.weightx = 1.0D;
right.weighty = 1.0D;
southPanel.add(messageBox, left);
southPanel.add(sendMessage, right);
mainPanel.add(BorderLayout.SOUTH, southPanel);
newFrame.add(mainPanel);
newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
newFrame.setSize(470, 300);
newFrame.setVisible(true);
if(msgList != null) {
startMessageManager();
}
// Start the actual XMPP conversation
if (cMsgListener != null)
chat = connection.getChatManager().createChat(remoteEndJID, cMsgListener);
System.out.println("New chat created : " + chat.getThreadID() + " " + chat.getParticipant());
}
class sendMessageButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (messageBox.getText().length() < 1) {
// Do nothing
} else if (messageBox.getText().equals(".clear")) {
chatBox.setText("Cleared all messages\n");
messageBox.setText("");
} else {
addMessage(new ChatMessage(localEndName, remoteEndName, messageBox.getText(), true));
}
messageBox.requestFocusInWindow();
}
}
public void addMessage(ChatMessage message) {
Style style = sContext.getStyle(StyleContext.DEFAULT_STYLE);
if (message.isMine == true) {
// StyleConstants.setAlignment(style, StyleConstants.ALIGN_RIGHT);
StyleConstants.setFontSize(style, 14);
StyleConstants.setSpaceAbove(style, 4);
StyleConstants.setSpaceBelow(style, 4);
StyleConstants.setForeground(style, Color.BLUE);
try {
sDoc.insertString(sDoc.getLength(),
"(" + message.Time + ") " + message.senderName + ": " + message.body + "\n", style);
} catch (BadLocationException e1) {
e1.printStackTrace();
}
// Send the msg to the RemoteEnd
try {
chat.sendMessage(message.body);
} catch (XMPPException e) {
e.printStackTrace();
}
messageBox.setText("");
}
if (message.isMine == false) {
// StyleConstants.setAlignment(lStyle, StyleConstants.ALIGN_LEFT);
StyleConstants.setFontSize(style, 14);
StyleConstants.setSpaceAbove(style, 4);
StyleConstants.setSpaceBelow(style, 4);
StyleConstants.setForeground(style, Color.RED);
try {
sDoc.insertString(sDoc.getLength(),
"(" + message.Time + ") " + message.senderName + ": " + message.body + "\n", style);
} catch (BadLocationException e) {
e.printStackTrace();
}
}
}
class ChatMessageListener implements MessageListener {
#Override
public void processMessage(Chat chat, Message msg) {
if (msg.getType() == Message.Type.chat) {
addMessage(new ChatMessage(remoteEndName, localEndName, msg.getBody(), false));
System.out.println("The chat with threadID " + chat.getThreadID()
+ " recevied a message from the remoteEnd " + " " + chat.getParticipant());
}
}
}
public void startMessageManager() {
Thread t = new Thread() {
public void run() {
while(true){
if(msgList.size() > 0) {
for(int i=0; i<msgList.size();i++)
addMessage(new ChatMessage(remoteEndName, localEndName, msgList.removeFirst(), false));
}
}
}
};
t.setPriority(Thread.NORM_PRIORITY);
t.start();
}
}
Problem: For now i can create a new ChatGUI for each user but when i click exit in any of the created chatGUI-threads it closes the main process and all other chatGUIs.
Apologize for bad English.
I found the solution:
Since I am using Smack 3.2.2 it does not have the capability to stop a Chat.
My JFrame exited well after using newFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); instead of using newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Change Title of JFrame in my program

I am having trouble with one part of my code. I have been working for so long on this and I am exhausted and missing something easy. I need to have a text box to enter a new title for the JFrame, a button that says "Set New Name" and an "Exit Button.
Can someone look at this code and give me some info so I can go to bed.
Thank you
//Good One
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.text.*;
import java.util.*;
import javax.swing.*;
public class Pool {
public static void main(String[] args) {
new poolCalc();
}
}
class poolCalc extends JFrame {
private static final long serialVersionUID = 1L;
public static final double MILLIMETER = 1;
public static final double METER = 1000 * MILLIMETER;
public static final double INCH = 25.4 * MILLIMETER;
public static final double FOOT = 304.8 * MILLIMETER;
public static final double YARD = 914.4 * MILLIMETER;
private static final DecimalFormat df = new DecimalFormat("#,##0.###");
private JTabbedPane tabs;
private JPanel generalPanel;
private JPanel optionsPanel;
private JPanel customerPanel;
private JPanel contractorPanel;
private JPanel poolPanel;
private JPanel hotTubPanel;
private JPanel tempCalPanel;
private JPanel lengthCalPanel;
public poolCalc() {
super("The Pool Calculator");
setSize(340, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(true);
initializeComponents();
setLocationRelativeTo(null);
setVisible(true);
}
private void initializeComponents() {
Container pane = getContentPane();
tabs = new JTabbedPane();
generalTab();
optionsTab();
customerTab();
contractorTab();
poolsTab();
hotTubsTab();
tempCalTab();
lengthCalTab();
tabs.add("General", generalPanel);
tabs.add("Options", optionsPanel);
tabs.add("Customers", customerPanel);
tabs.add("Contractors", contractorPanel);
tabs.add("Pools", poolPanel);
tabs.add("Hot Tubs", hotTubPanel);
tabs.add("Temp Calc", tempCalPanel);
tabs.add("Length Calc", lengthCalPanel);
pane.add(tabs);
}
private JButton createExitButton() {
JButton exitButton = new JButton("Exit");
exitButton.setMnemonic('x');
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
return exitButton;
}
private void generalTab() {
generalPanel = new JPanel(new FlowLayout());
String currentTime = SimpleDateFormat.getInstance().format(
Calendar.getInstance().getTime());
generalPanel.add(new JLabel("Today's Date: " + currentTime));
generalPanel.add(createExitButton());
}
private JTextField createTitleField(String text, int length) {
JTextField tf = new JTextField(length);
tf.setEditable(false);
tf.setFocusable(false);
tf.setText(text);
return tf;
}
// FIX
private void optionsTab() {
optionsPanel = new JPanel(new FlowLayout());
//optionsPanel.setLayout(null);
JLabel labelOptions = new JLabel("Change Company Name:");
labelOptions.setBounds(120, 10, 150, 20);
optionsPanel.add(labelOptions);
final JTextField newTitle = new JTextField("Some Title");
newTitle.setBounds(80, 40, 225, 20);
optionsPanel.add(newTitle);
final JTextField myTitle = new JTextField("My Title...");
myTitle.setBounds(80, 40, 225, 20);
myTitle.add(labelOptions);
JButton newName = new JButton("Set New Name");
newName.setBounds(60, 80, 150, 20);
//newName.addActionListener(this);
optionsPanel.add(newName);
optionsPanel.add(createExitButton());
}
private void customerTab() {
customerPanel = createContactPanel("Customer", "customer.txt");
}
private void contractorTab() {
contractorPanel = createContactPanel("Contractor", "contractor.txt");
}
private void poolsTab() {
poolPanel = new JPanel(new FlowLayout());
final JRadioButton roundPool = new JRadioButton("Round Pool");
final JRadioButton ovalPool = new JRadioButton("Oval Pool");
final JRadioButton rectangularPool = new JRadioButton("Rectangle Pool");
roundPool.setSelected(true);
ButtonGroup group = new ButtonGroup();
group.add(roundPool);
group.add(rectangularPool);
poolPanel.add(roundPool);
poolPanel.add(rectangularPool);
poolPanel.add(new JLabel("Enter the pool's length (ft): "));
final JTextField lengthField = new JTextField(10);
poolPanel.add(lengthField);
final JLabel widthLabel = new JLabel("Enter the pool's width (ft): ");
widthLabel.setEnabled(false);
poolPanel.add(widthLabel);
final JTextField widthField = new JTextField(10);
widthField.setEnabled(false);
poolPanel.add(widthField);
poolPanel.add(new JLabel("Enter the pool's depth (ft): "));
final JTextField depthField = new JTextField(10);
poolPanel.add(depthField);
JButton calculateVolume = new JButton("Calculate Volume");
calculateVolume.setMnemonic('C');
poolPanel.add(calculateVolume);
poolPanel.add(createExitButton());
poolPanel.add(new JLabel("The pool's volume is (ft^3): "));
final JTextField volumeField = new JTextField(10);
volumeField.setEditable(false);
poolPanel.add(volumeField);
final JTextArea messageArea = createMessageArea(2, 20, "");
poolPanel.add(messageArea);
calculateVolume.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (roundPool.isSelected()) {
widthField.setText(lengthField.getText());
}
ValidationResult result = validateFields(new JTextField[] {
lengthField, widthField, depthField });
String errors = "";
if (result.filled != 3) {
errors += "Please fill out all fields! ";
}
if (result.valid != 3 && result.filled != result.valid) {
errors += "Please enter valid numbers!";
}
if (errors != "") {
messageArea.setText(errors);
messageArea.setVisible(true);
}
else {
messageArea.setVisible(false);
double length = Double.parseDouble(lengthField.getText());
double width = Double.parseDouble(widthField.getText());
double depth = Double.parseDouble(depthField.getText());
double volume;
if (roundPool.isSelected()) {
volume = Math.PI * Math.pow(length / 2.0, 2) * depth;
}
if (rectangularPool.isSelected()) {
volume = length * width * depth * 5.9;
}
else {
volume = length * width * depth * 7.5;
}
volumeField.setText(df.format(volume));
}
}
});
ActionListener poolsListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == roundPool) {
widthLabel.setEnabled(false);
widthField.setEnabled(false);
widthField.setText(lengthField.getText());
}
else if (e.getSource() == rectangularPool) {
widthLabel.setEnabled(true);
widthField.setEnabled(true);
messageArea.setVisible(false);
}
}
};
roundPool.addActionListener(poolsListener);
ovalPool.addActionListener(poolsListener);
rectangularPool.addActionListener(poolsListener);
}
private void hotTubsTab() {
hotTubPanel = new JPanel(new FlowLayout());
final JRadioButton roundTub = new JRadioButton("Round Tub");
final JRadioButton ovalTub = new JRadioButton("Oval Tub");
roundTub.setSelected(true);
ButtonGroup group = new ButtonGroup();
group.add(roundTub);
group.add(ovalTub);
hotTubPanel.add(roundTub);
hotTubPanel.add(ovalTub);
hotTubPanel.add(new JLabel("Enter the tub's length (ft): "));
final JTextField lengthField = new JTextField(10);
hotTubPanel.add(lengthField);
final JLabel widthLabel = new JLabel("Enter the tub's width (ft): ");
widthLabel.setEnabled(false);
hotTubPanel.add(widthLabel);
final JTextField widthField = new JTextField(10);
widthField.setEnabled(false);
hotTubPanel.add(widthField);
hotTubPanel.add(new JLabel("Enter the tub's depth (ft): "));
final JTextField depthField = new JTextField(10);
hotTubPanel.add(depthField);
JButton calculateVolume = new JButton("Calculate Volume");
calculateVolume.setMnemonic('C');
hotTubPanel.add(calculateVolume);
hotTubPanel.add(createExitButton());
hotTubPanel.add(new JLabel("The tub's volume is (ft^3): "));
final JTextField volumeField = new JTextField(10);
volumeField.setEditable(false);
hotTubPanel.add(volumeField);
final JTextArea messageArea = createMessageArea(1, 25,
"Width will be set to the same value as length");
hotTubPanel.add(messageArea);
calculateVolume.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (roundTub.isSelected()) {
widthField.setText(lengthField.getText());
}
ValidationResult result = validateFields(new JTextField[] {
lengthField, widthField, depthField });
String errors = "";
if (result.filled != 3) {
errors += "Please fill out all fields! ";
}
if (result.valid != 3 && result.filled != result.valid) {
errors += "Please enter valid numbers!";
}
if (errors != "") {
messageArea.setText(errors);
messageArea.setVisible(true);
}
else {
messageArea.setVisible(false);
double length = Double.parseDouble(lengthField.getText());
double width = Double.parseDouble(widthField.getText());
double depth = Double.parseDouble(depthField.getText());
double volume;
if (roundTub.isSelected()) {
volume = Math.PI * Math.pow(length / 2.0,2) * depth;
}
if (ovalTub.isSelected()) {
volume = Math.PI * ((length * width)*2) * depth;
}
else {
volume = length * width * depth * 7.5;
}
volumeField.setText(df.format(volume));
}
}
});
ActionListener tubsListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == roundTub) {
widthLabel.setEnabled(false);
widthField.setEnabled(false);
widthField.setText(lengthField.getText());
}
else if (e.getSource() == ovalTub) {
widthLabel.setEnabled(true);
widthField.setEnabled(true);
messageArea.setVisible(false);}
}
};
roundTub.addActionListener(tubsListener);
ovalTub.addActionListener(tubsListener);}
private void tempCalTab() {
tempCalPanel = new JPanel(new FlowLayout());
tempCalPanel.add(new JLabel("Enter temperature: "));
final JTextField temperatureField = new JTextField(10);
tempCalPanel.add(temperatureField);
final JComboBox optionComboBox = new JComboBox(
new String[] { "C", "F" });
tempCalPanel.add(optionComboBox);
tempCalPanel.add(new JLabel("Result: "));
final JTextField resultField = new JTextField(18);
resultField.setEditable(false);
tempCalPanel.add(resultField);
final JLabel oppositeLabel = new JLabel("F");
tempCalPanel.add(oppositeLabel);
JButton convertButton = new JButton("Convert");
convertButton.setMnemonic('C');
tempCalPanel.add(convertButton);
tempCalPanel.add(createExitButton());
final JTextArea messageArea = createMessageArea(1, 20,
"System Messages");
tempCalPanel.add(messageArea);
optionComboBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
if ("F".equals(e.getItem())) {
oppositeLabel.setText("C");}
else {
oppositeLabel.setText("F");}}}
});
convertButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ValidationResult result = validateFields(new JTextField[] { temperatureField });
String errors = "";
if (result.filled != 1 || result.valid != 1) {
errors += "Value set to zero";}
if (errors != "") {
messageArea.setText(errors);
messageArea.setVisible(true);
temperatureField.setText("0");}
else {
messageArea.setVisible(false);}
double temperature = Double.parseDouble(temperatureField
.getText());
double resultValue = 0;
if (oppositeLabel.getText().equals("C")) {
resultValue = (temperature - 32.0) / 9.0 * 5.0;}
else if (oppositeLabel.getText().equals("F")) {
resultValue = ((temperature * 9.0) / 5.0) + 32.0;}
resultField.setText(df.format(resultValue));}
});
}
private void lengthCalTab() {
lengthCalPanel = new JPanel(new FlowLayout());
lengthCalPanel.add(createTitleField("Millimeters", 6));
lengthCalPanel.add(createTitleField("Meters", 4));
lengthCalPanel.add(createTitleField("Yards", 4));
lengthCalPanel.add(createTitleField("Feet", 3));
lengthCalPanel.add(createTitleField("Inches", 6));
final JTextField millimetersField = new JTextField(6);
final JTextField metersField = new JTextField(4);
final JTextField yardsField = new JTextField(4);
final JTextField feetField = new JTextField(3);
final JTextField inchesField = new JTextField(6);
lengthCalPanel.add(millimetersField);
lengthCalPanel.add(metersField);
lengthCalPanel.add(yardsField);
lengthCalPanel.add(feetField);
lengthCalPanel.add(inchesField);
JButton convertButton = new JButton("Convert");
convertButton.setMnemonic('C');
convertButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double millimeters = convertToDouble(millimetersField.getText());
double meters = convertToDouble(metersField.getText());
double yards = convertToDouble(yardsField.getText());
double feet = convertToDouble(feetField.getText());
double inches = convertToDouble(inchesField.getText());
double value = 0;
if (millimeters != 0) {
value = millimeters * MILLIMETER;}
else if (meters != 0) {
value = meters * METER;}
else if (yards != 0) {
value = yards * YARD;}
else if (feet != 0) {
value = feet * FOOT;}
else if (inches != 0) {
value = inches * INCH;}
millimeters = value / MILLIMETER;
meters = value / METER;
yards = value / YARD;
feet = value / FOOT;
inches = value / INCH;
millimetersField.setText(df.format(millimeters));
metersField.setText(df.format(meters));
yardsField.setText(df.format(yards));
feetField.setText(df.format(feet));
inchesField.setText(df.format(inches));}
private double convertToDouble(String s) {
try {
return Double.parseDouble(s);}
catch (Exception e) {
return 0;}}
});
JButton clearButton = new JButton("Clear");
clearButton.setMnemonic('l');
clearButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
millimetersField.setText(null);
metersField.setText(null);
yardsField.setText(null);
feetField.setText(null);
inchesField.setText(null);}
});
lengthCalPanel.add(convertButton);
lengthCalPanel.add(clearButton);
lengthCalPanel.add(createExitButton());}
private String loadDataFromFile(String fileName) {
String data = "";
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
while (reader.ready()) {
data += reader.readLine() + "\n";}
reader.close();}
catch (IOException e){
}
return data;}
private JPanel createContactPanel(final String contactName,
final String fileName) {
JPanel pane = new JPanel(new FlowLayout());
final JTextArea customerDisplay = new JTextArea(8, 25);
customerDisplay.setLineWrap(true);
customerDisplay.setEditable(false);
pane.add(new JScrollPane(customerDisplay));
pane.add(createExitButton());
JButton addCustomerButton = new JButton("Add " + contactName);
addCustomerButton.setMnemonic('A');
pane.add(addCustomerButton);
JButton refreshButton = new JButton("Refresh");
refreshButton.setMnemonic('R');
pane.add(refreshButton);
final JTextArea messageArea = createMessageArea(2, 25, "");
messageArea.setBackground(Color.white);
pane.add(messageArea);
addCustomerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new EditContact(contactName, fileName);}
});
refreshButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = loadDataFromFile(fileName);
if (data != "") {
customerDisplay.setText(data);
customerDisplay.setEnabled(true);
messageArea.setText("File " + fileName
+ " can be read from!");
}
else {
customerDisplay.setText("Click Add "
+ contactName
+ " button to add "
+ contactName.toLowerCase()
+ ". And click Refresh button to update this pane.");
customerDisplay.setEnabled(false);
messageArea.setText("File " + fileName + " is not "
+ "there yet! It will be created "
+ "when you add " + contactName.toLowerCase()
+ "s!");
}
}
});
refreshButton.doClick();
return pane;
}
private JTextArea createMessageArea(int rows, int cols, String text) {
final JTextArea messageArea = new JTextArea(rows, cols);
messageArea.setBorder(BorderFactory.createEmptyBorder());
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setFont(new Font("System", Font.PLAIN, 12));
messageArea.setText(text);
messageArea.setBackground(null);
messageArea.setForeground(Color.GRAY);
messageArea.setEnabled(true);
messageArea.setFocusable(false);
return messageArea;
}
private class ValidationResult {
int filled;
int valid;
}
private ValidationResult validateFields(JTextField[] fields) {
ValidationResult result = new ValidationResult();
for (int i = 0; i < fields.length; i++) {
JTextField field = fields[i];
if ((field.getText() != null) && (field.getText().length() > 0)) {
result.filled++;
}
try {
Double.parseDouble(field.getText());
field.setBackground(Color.white);
result.valid++;
}
catch (Exception e) {
field.setBackground(Color.orange);
}
}
return result;
}
private class EditContact extends JDialog {
private static final long serialVersionUID = 1L;
private final String contactName;
private final String fileName;
private File file;
private JTextField nameField;
private JTextField addressField;
private JTextField cityField;
private JComboBox stateComboBox;
private JTextField zipField;
private JTextField phoneField;
private JTextArea messageArea;
public EditContact(String contactName, String fileName) {
super(poolCalc.this, contactName + "s");
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setModalityType(ModalityType.APPLICATION_MODAL);
setSize(418, 300);
this.contactName = contactName;
this.fileName = fileName;
initializeComponents();
if (openFile()) {
displayMessage(null);
}
else {
displayMessage("File " + fileName + " does not exist yet! "
+ "Will be created when you add a "
+ contactName.toLowerCase() + "!");
}
setLocationRelativeTo(null);
setVisible(true);
}
private void displayMessage(String message) {
if (message != null) {
messageArea.setVisible(true);
messageArea.setText(message);
}
else {
messageArea.setVisible(false);
}
}
private boolean openFile() {
file = new File(fileName);
return file.exists();
}
private boolean deleteFile() {
return file.exists() && file.delete();
}
private boolean saveToFile() {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(file,
true));
writer.write("Name: " + nameField.getText() + "\n");
writer.write("Address: " + addressField.getText() + "\n");
writer.write("City: " + cityField.getText() + "\n");
writer.write("State: "
+ stateComboBox.getSelectedItem().toString() + "\n");
writer.write("ZIP: " + zipField.getText() + "\n");
writer.write("Phone: " + phoneField.getText() + "\n");
writer.write("\n");
writer.close();
return true;
}
catch (IOException e) {
return false;
}
}
private void initializeComponents() {
Container pane = getContentPane();
pane.setLayout(new FlowLayout());
pane.add(new JLabel(contactName + " Name "));
nameField = new JTextField(25);
pane.add(nameField);
pane.add(new JLabel("Address "));
addressField = new JTextField(28);
pane.add(addressField);
pane.add(new JLabel("City "));
cityField = new JTextField(32);
pane.add(cityField);
pane.add(new JLabel("State "));
stateComboBox = new JComboBox(new String[] { "AL", "AK", "AZ",
"AR", "CA", "CO", "CT", "DE", "FL", "GA", "HI", "ID", "IL",
"IN", "IA", "KS", "KY", "LA", "ME", "MD", "MA", "MI", "MN",
"MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC",
"ND", "OH", "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX",
"UT", "VT", "VA", "WA", "WV", "WI", "WY" });
pane.add(stateComboBox);
pane.add(new JLabel("ZIP "));
zipField = new JTextField(5);
pane.add(zipField);
pane.add(new JLabel("Phone "));
phoneField = new JTextField(10);
pane.add(phoneField);
JButton addContactButton = new JButton("Add " + this.contactName);
addContactButton.setMnemonic('A');
addContactButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (saveToFile()) {
displayMessage(contactName + " added");
}
else {
displayMessage("File saving error!");
}
}
});
pane.add(addContactButton);
JButton closeButton = new JButton("Close");
closeButton.setMnemonic('C');
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
});
pane.add(closeButton);
JButton deleteFileButton = new JButton("Delete File");
deleteFileButton.setMnemonic('D');
deleteFileButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (deleteFile()) {
displayMessage("File " + fileName + " deleted!");
}
}
});
pane.add(deleteFileButton);
messageArea = createMessageArea(2, 30, "");
messageArea.setBackground(Color.white);
pane.add(messageArea);
}
}
}
Let's start with this (which I assume is where you create the details)...
private void optionsTab() {
optionsPanel = new JPanel(new FlowLayout());
//optionsPanel.setLayout(null);
JLabel labelOptions = new JLabel("Change Company Name:");
labelOptions.setBounds(120, 10, 150, 20);
optionsPanel.add(labelOptions);
final JTextField newTitle = new JTextField("Some Title");
newTitle.setBounds(80, 40, 225, 20);
optionsPanel.add(newTitle);
final JTextField myTitle = new JTextField("My Title...");
myTitle.setBounds(80, 40, 225, 20);
myTitle.add(labelOptions);
JButton newName = new JButton("Set New Name");
newName.setBounds(60, 80, 150, 20);
//newName.addActionListener(this);
optionsPanel.add(newName);
optionsPanel.add(createExitButton());
}
The newTitle field is a local variable, so once the method exists, you will not be able to access the field (easily)...
You seem to have tried adding a actionListener to the newName button, which isn't a bad idea, but because you can't actually access the newTitle field, isn't going to help...
The use of setBounds is not only ill advised, but probably won't result in the results you are expecting, because the optionsPane is under the control a layout manager...
And while I was digging around, I noticed this if (errors != "") {...This is not how String comparison is done in Java. This is comparing the memory references of both Strings which will never be true, instead you should if (!"".equals(errors)) {...
But back to the problem at hand...
You are really close to having a solution. You could make the newTitle field a class instance variable, which would allow you to access the field within other parts of your program, but because you've made it final, there's something else you can try...
You can use an anonymous inner class instead...
newName.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setTitle(newTitle.getText());
}
});
Which should get a good nights sleep :D
It is a little unclear what you want, but if I understand you right you want the JButton newName to set the title of the JFrame to the text in some textbox?
In that case you would write
setTitle(someTextbox.getText());
inside the function of the button.
First, you need to create a JTextField that has public access. Then, create a JButton that implements ActionListener. After that you must implement the abstract method actionPerformed() in the JButton Subclass. Then in the run method say JFrame.setTitle(JTextfield.getText()).
Subclass Method:
public class main extends JFrame{
// Construct and setVisible()
}
class textfield extends JTextField{
// create field then add to JFrame
}
class button extends JButton implements ActionListener{
// create button
public void actionPerformed(ActionEvent e){
main.setTitle(textfield.getText());
}
Instance Method:
public class main implements ActionListener{
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JTextField field = new JTextField();
JButton button = new JButtone();
button.addActionListener(this);
panel.add(field);
panel.add(button);
frame.add(panel);
public void actionPerformed(ActionEvent e){
frame.setTitle(field.getText);
}
}
Try This
private void optionsTab() {
optionsPanel = new JPanel(new FlowLayout());
// optionsPanel.setLayout(null);
JLabel labelOptions = new JLabel("Change Company Name:");
labelOptions.setBounds(120, 10, 150, 20);
optionsPanel.add(labelOptions);
final JTextField newTitle = new JTextField("Some Title");
newTitle.setBounds(80, 40, 225, 20);
optionsPanel.add(newTitle);
final JTextField myTitle = new JTextField("My Title...");
myTitle.setBounds(80, 40, 225, 20);
myTitle.add(labelOptions);
JButton newName = new JButton("Set New Name");
newName.setBounds(60, 80, 150, 20);
newName.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setTitle(newTitle.getText());
}
});
// newName.addActionListener(this);
optionsPanel.add(newName);
optionsPanel.add(createExitButton());
}

Categories