java INSERT query doesn't work (java.lang.NullPointerException) - java-7

When I run this code I get an null pointer Exception.
try {
String sql = "INSERT INTO viwa(name,tele,surname) VALUES(?,?,?)";
pst = conn.prepareStatement(sql);
pst.setString(1, jTextField_name.getText());
pst.setString(2, jTextField_age.getText());
pst.setString(3, jTextField_tele.getText());
pst.execute();
JOptionPane.showMessageDialog(null, "Saved");
} catch (Exception e) {
e.printStackTrace();
}
*This's the full code*
` import java.sql.Connection; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.Statement; import
javax.swing.JOptionPane;
public class go extends javax.swing.JFrame {
Connection conn = null;
ResultSet rs = null; PreparedStatement pst = null;
public go() {
try {
initComponents();
connect.getMyConn();
} catch (Exception e) {
e.printStackTrace();
}
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jTextField_Tele = new javax.swing.JTextField();
jTextField_Surname = new javax.swing.JTextField();
jTextField_Name = new javax.swing.JTextField();
jButton_search = new javax.swing.JButton();
jButton_Update = new javax.swing.JButton();
jButton_Delete = new javax.swing.JButton();
jButton_save = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel1.setText("Tele");
getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 140, -1, -1));
jLabel2.setText("Surname");
getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 210, -1, -1));
jLabel3.setText("Name");
getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 70, -1, -1));
jTextField_Tele.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField_TeleActionPerformed(evt);
}
});
getContentPane().add(jTextField_Tele, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 140, 170, -1));
getContentPane().add(jTextField_Surname, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 210, 170, -1));
getContentPane().add(jTextField_Name, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 70, 170, -1));
jButton_search.setText("Search");
getContentPane().add(jButton_search, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 310, 120, -1));
jButton_Update.setText("Update");
getContentPane().add(jButton_Update, new org.netbeans.lib.awtextra.AbsoluteConstraints(390, 310, 120, -1));
jButton_Delete.setText("Delete");
getContentPane().add(jButton_Delete, new org.netbeans.lib.awtextra.AbsoluteConstraints(540, 310, 120, -1));
jButton_save.setText("Save");
jButton_save.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_saveActionPerformed(evt);
}
});
getContentPane().add(jButton_save, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 310, 120, -1));
pack();
}// </editor-fold>
private void jTextField_TeleActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton_saveActionPerformed(java.awt.event.ActionEvent evt) {
try {
String sql = "INSERT INTO viwa (name,tele,surname) VALUES(?,?,?)";
pst = conn.prepareStatement(sql);
pst.setString(1, jTextField_Name.getText());
pst.setString(2, jTextField_Tele.getText());
pst.setString(3, jTextField_Surname.getText());
pst.execute();
JOptionPane.showMessageDialog(this, "Saved");
} catch (Exception e) {
e.printStackTrace();
}
} `

Using your IDE, put a breakpoint at the start of this code and step through it watching all variables. One of your variables holds the unexpected null value. There is no other obvious reason for NPE in your code.

Related

How to fix runtime error in netbeans of Gui with search option?

I am creating a gui where I will take some info of people and store/append it in a file.
Then I created a textarea1 where i will show/display the stored info by name.
Lastly, I created a search option where when I input either name or phone number, I should get matched results shown/displayed in the other textarea2 below.
However, My gui is giving error and won't run at all eversince I wrote the code for the search option, which is button3 in the code. How can I fix it? btw, I'm using java frame form so, that is why the code is a lil lenthy.
package address.book;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
class Students {
private String name;
private String phoneNo;
private String email;
private String streetAddress;
public Students(String name, String phoneNo, String email, String streetAddress) {
this.name = name;
this.phoneNo = phoneNo;
this.email = email;
this.streetAddress = streetAddress;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getStreetAddress() {
return streetAddress;
}
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
}
public class AddressBook extends javax.swing.JFrame {
private Object jTextArea2;
private JLabel jLabel7;
private JTextArea jTextArea1;
private JTextField jTextField1;
private JTextField jTextField2;
private JTextField jTextField3;
private JTextField jTextField4;
private JTextField jTextField5;
private JTextField jTextField6;
/**
* Creates new form AddressBook
*/
public AddressBook() {
initComponents();
this.setTitle("Address Book");
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jTextField3 = new javax.swing.JTextField();
jTextField4 = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jButton2 = new javax.swing.JButton();
jTextField5 = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
jTextField6 = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
jButton3 = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
jTextArea2 = new javax.swing.JTextArea();
jLabel7 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField1ActionPerformed(evt);
}
});
jTextField3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField3ActionPerformed(evt);
}
});
jTextField4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField4ActionPerformed(evt);
}
});
jLabel1.setText("Name :");
jLabel2.setText("Phone No# :");
jLabel3.setText("Email :");
jLabel4.setText("Street Address :");
jButton1.setText("Register");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
jButton2.setText("Show");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jTextField5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField5ActionPerformed(evt);
}
});
jLabel5.setText("Name :");
jTextField6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField6ActionPerformed(evt);
}
});
jLabel6.setText("Phone No# :");
jButton3.setText("Search");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jTextArea2.setColumns(20);
jTextArea2.setRows(5);
jScrollPane2.setViewportView(jTextArea2);
jLabel7.setFont(new java.awt.Font("Courier New", 3, 18)); // NOI18N
jLabel7.setText(" <Search a person by their name or phone number>");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(182, 182, 182)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 208, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(39, 39, 39)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
.addComponent(jScrollPane2)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4)
.addGroup(layout.createSequentialGroup()
.addGap(2, 2, 2)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jLabel1)
.addComponent(jLabel3))))
.addGap(42, 42, 42)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 232, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jTextField1)
.addComponent(jTextField2)
.addComponent(jTextField3)
.addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 367, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel6)
.addGap(56, 56, 56)
.addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, 355, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel5)
.addGap(81, 81, 81)
.addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 355, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 0, Short.MAX_VALUE)))))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(30, 30, 30)
.addComponent(jLabel7))
.addGroup(layout.createSequentialGroup()
.addGap(181, 181, 181)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 209, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(96, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(29, 29, 29)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addGap(18, 18, 18)
.addComponent(jButton1)
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 237, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton2)
.addGap(29, 29, 29)
.addComponent(jLabel7)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(20, 20, 20)
.addComponent(jButton3)
.addGap(18, 18, 18)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 203, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jTextField3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jTextField4ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String name = jTextField1.getText();
String phoneNo = jTextField2.getText();
String email = jTextField3.getText();
String streetAddress = jTextField4.getText();
try{
FileWriter fw = new FileWriter("Registration.txt", true);
PrintWriter pw = new PrintWriter(fw);
pw.println(name+" "+phoneNo+" "+email+" "+streetAddress+" ");
pw.close();
}
catch(IOException e){
e.printStackTrace();
}
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
try{
File f = new File("Registration.txt");
Scanner sc = new Scanner(f);
jTextArea1.setText("");
while(sc.hasNext()){
String name = sc.next();
String phoneNo = sc.next();
String email = sc.next();
String streetAddress = sc.nextLine();
String data = "Name: "+name+"\n "+" PhoneNo: "+phoneNo+"\n "+" Email: "+email+"\n "+" StreetAddress: "+streetAddress+"\n\n";
jTextArea1.append(data);
}
sc.close();
}
catch(IOException e){
e.printStackTrace();
}
}
private void jTextField5ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jTextField6ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
try{
File f = new File("Registration.txt");
Scanner sc = new Scanner(f);
FileWriter fw = new FileWriter("Registration.txt", true);
PrintWriter pw = new PrintWriter(fw);
jTextArea2.append("");
Students [] students = new Students[10];
int index = 0;
while(sc.hasNext()){
String namex = jTextField5.getText();
String phoneNox = jTextField6.getText();
String name = sc.next();
String phoneNo = sc.next();
String email = sc.next();
String streetAddress = sc.next();
if(namex.equals(name)||phoneNox.equals(phoneNo)){
Students st = new Students(name, phoneNo, email, streetAddress);
students[index] = st;
}
index++;
}
for(int i = 0; i < index; i++){
Students st = students[i];
String data = "Results:\n\nName: "+st.getName()+"\n "+" PhoneNo: "+st.getPhoneNo()+"\n "+" Email: "+st.getEmail()+"\n "+" StreetAddress: "+st.getStreetAddress()+"\n\n";
jTextArea2.append(data);
}
sc.close();
pw.close();
}
catch(IOException e){
e.printStackTrace();
}
}
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
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(AddressBook.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(AddressBook.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(AddressBook.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(AddressBook.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new AddressBook().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextArea jTextArea2;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField3;
private javax.swing.JTextField jTextField4;
private javax.swing.JTextField jTextField5;
private javax.swing.JTextField jTextField6;
// End of variables declaration
}```
also I tried to run it with a new code for button 3 and without the students class:
it still didn't work as planned. WHen I run it they say that the public main class is not in the package address book and the private labels all of the red in the code.
try{
File f = new File("Registration");
Scanner sc = new Scanner(f);
jTextArea2.append("");
while(sc.hasNext()){
String namex = jTextField5.getText();
String phoneNox = jTextField6.getText();
String name = sc.next();
String phoneNo = sc.next();
String email = sc.next();
String streetAddress = sc.next();
if(namex.equals(name)||phoneNox.equals(phoneNo)){
String data = "Name: "+name+"\n "+" PhoneNo: "+phoneNo+"\n "+" Email: "+email+"\n "+" StreetAddress: "+streetAddress+"\n\n";
jTextArea2.append(data);
}
}
sc.close();
}
catch(IOException e){
e.printStackTrace();
}
}

Replace current JScrollPane to another JScrollPane in JPanel

I would like to change my current JScrollpane to a new one. I would like it to change after I pressed my button and the method actionPerformed is called.
The problem I currently have is that it only paints the Jscroll at the beginning of the application, when i want to change it, it dosent work.(When the application is running).
What I do is:
In the beginning of the application I make a new JscrollPane and this one is empty. If the button is pressed: Show another JscrollPane with content.
if(btnPressed == true){
//set current empty jscroll pane to a filled one.
jscrollpane = View.createScrollPlane();
//View.createScrollPlane = This method fills the JscrollPane with text.
}
else { //show a empty one
jscrollpane = new JscrollPane();
}
I have tried:
- remove
- add
- revalidate
- repaint
And also:
JscrollPane.setViewPortView(JscrollPane);
I've looked to CardLayout but I would rather not and it dosent allow me since only empty containers can be changed to CardLayout. Currently its on GridBagLayout.
Thanks in advance
RE-edit: the Create-UI method dosent change the current empty Jscrollpanel to the new one. It only initialise it once (at the beginning) but dosent update the Jscroll panel. (when i tried to put it on false) it worked, the boolean did change to true but dosent update the jscroll panel.
package readDataPluginPackage;
import com.change_vision.jude.api.inf.AstahAPI;
import com.change_vision.jude.api.inf.project.ProjectAccessor;
import javafx.embed.swing.JFXPanel;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.PropertyChangeListener;
public class Application {
JPanel mainJPanel;
private JPanel leftJPanel;
private JPanel rightJPanel;
private JButton btnSynchronise;
private JButton btnPreview;
private JScrollPane JScrollPaneReport;
public JScrollPane JScrollPanePreview;
private boolean btnPreviewClicked = false;
public Application() {
$$$setupUI$$$();
btnPreview.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
btnPreviewClicked = true;
JOptionPane.showMessageDialog(null, "Showing..." + btnPreviewClicked);
// ShowXMLFileView showXMLFileView = new ShowXMLFileView();
// JScrollPanePreview = showXMLFileView.createLabelPane();
// if (btnPreview.isEnabled()) {
// ShowXMLFileView showXMLFileView = new ShowXMLFileView();
// JScrollPanePreview = showXMLFileView.createLabelPane();
JOptionPane.showMessageDialog(null, "XML File Preview has been updated.");
createUIComponents();
// JScrollPanePreview.revalidate();
// JScrollPanePreview.repaint();
JOptionPane.showMessageDialog(null, "Components are created again.");
}
// }
});
btnSynchronise.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Synchronising...");
}
});
}
public static void main(String[] args) {
try {
//Save Astah Project as XML File
ProjectAccessor prjAccessor = AstahAPI.getAstahAPI().getProjectAccessor();
prjAccessor.open("C:\\Users\\delina\\generated\\test.asta");
prjAccessor.exportXMI("C:\\Users\\delina\\generatedXMI\\temp.xml");
prjAccessor.close();
//Show the most recent version of the xml file of the Astah Project
ReadXMLFile rd = new ReadXMLFile();
rd.showXMLFileLines();
} catch (Exception e) {
e.printStackTrace();
}
JFrame frame = new JFrame("Application");
frame.setContentPane(new Application().mainJPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private void createUIComponents() {
if (btnPreviewClicked == true) {
// ShowXMLFileView showXMLFileView = new ShowXMLFileView();
// JScrollPanePreview = showXMLFileView.createLabelPane();
// JScrollPanePreview.setViewportView(JScrollPanePreview);
leftJPanel.remove(JScrollPanePreview);
ShowXMLFileView showXMLFileView = new ShowXMLFileView();
JScrollPane JScrollPanePreview = showXMLFileView.createLabelPane();
leftJPanel.add(JScrollPanePreview);
JScrollPanePreview.revalidate();
JScrollPanePreview.repaint();
JOptionPane.showMessageDialog(null, "JScrollPanel changed");
} else {
JScrollPanePreview = new JScrollPane();
}
}
/**
* Method generated by IntelliJ IDEA GUI Designer
* >>> IMPORTANT!! <<<
* DO NOT edit this method OR call it in your code!
*
* #noinspection ALL
*/
private void $$$setupUI$$$() {
createUIComponents();
mainJPanel = new JPanel();
mainJPanel.setLayout(new GridBagLayout());
leftJPanel = new JPanel();
leftJPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc;
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
mainJPanel.add(leftJPanel, gbc);
btnSynchronise = new JButton();
btnSynchronise.setText("Synchronise");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 2;
gbc.weightx = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
leftJPanel.add(btnSynchronise, gbc);
btnPreview = new JButton();
btnPreview.setText("Preview");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
gbc.weightx = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
leftJPanel.add(btnPreview, gbc);
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
leftJPanel.add(JScrollPanePreview, gbc);
JScrollPanePreview.setBorder(BorderFactory.createTitledBorder("XML File Preview"));
rightJPanel = new JPanel();
rightJPanel.setLayout(new GridBagLayout());
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
mainJPanel.add(rightJPanel, gbc);
JScrollPaneReport = new JScrollPane();
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
rightJPanel.add(JScrollPaneReport, gbc);
JScrollPaneReport.setBorder(BorderFactory.createTitledBorder("Synchronise report"));
}
/**
* #noinspection ALL
*/
public JComponent $$$getRootComponent$$$() {
return mainJPanel;
}
}
package readDataPluginPackage;
import com.change_vision.jude.api.inf.project.ProjectAccessor;
import com.change_vision.jude.api.inf.project.ProjectAccessorFactory;
import com.change_vision.jude.api.inf.project.ProjectEvent;
import com.change_vision.jude.api.inf.project.ProjectEventListener;
import com.change_vision.jude.api.inf.ui.IPluginExtraTabView;
import com.change_vision.jude.api.inf.ui.ISelectionListener;
import javax.swing.*;
import java.awt.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ShowUserInterface extends JPanel implements IPluginExtraTabView, ProjectEventListener {
public ShowUserInterface() {
initComponents();
}
private void initComponents() {
setLayout(new BorderLayout());
add(createLabelPane());
addProjectEventListener();
}
private void addProjectEventListener() {
try {
ProjectAccessor projectAccessor = ProjectAccessorFactory.getProjectAccessor();
projectAccessor.addProjectEventListener(this);
} catch (ClassNotFoundException e) {
e.getMessage();
}
}
private Container createLabelPane() {
JLabel label = new JLabel("AuguSoft Synchronise");
JScrollPane pane = new JScrollPane(label);
Method privateMethod = null;
Application app = null;
Object o = null;
JComponent jComponent = null;
try {
app = new Application();
privateMethod = Application.class.getDeclaredMethod("$$$setupUI$$$");
privateMethod.setAccessible(true);
o = privateMethod.invoke(app);
jComponent = app.$$$getRootComponent$$$();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return jComponent;
}
#Override
public void projectChanged(ProjectEvent e) {
}
#Override
public void projectClosed(ProjectEvent e) {
}
#Override
public void projectOpened(ProjectEvent e) {
}
#Override
public void addSelectionListener(ISelectionListener listener) {
}
#Override
public Component getComponent() {
return this;
}
#Override
public String getDescription() {
return "Show AuguSoft Synchronise here";
}
#Override
public String getTitle() {
return "AuguSoft View";
}
public void activated() {
}
public void deactivated() {
}
}
So, with doing nothing else but looking at you code, I noticed that in your createUIComponents method, you are shadowing the JScrollPanePreview property...
public class Application {
//...
public JScrollPane JScrollPanePreview;
//...
public Application() {..}
private void createUIComponents() {
if (btnPreviewClicked == true) {
//...
leftJPanel.remove(JScrollPanePreview);
ShowXMLFileView showXMLFileView = new ShowXMLFileView();
JScrollPane JScrollPanePreview = showXMLFileView.createLabelPane();
//...
} else {
JScrollPanePreview = new JScrollPane();
}
}
This means that the next time you come to replace the JScrollPanePreview, you won't have the correct reference to remove it.
To my mind (and I don't have you full code base or intention), I'd simply replace the JScrollPanePreview view port (besides, I'm not sure how you can assign a Container to a JScrollPane anyway :P)
private void createUIComponents() {
if (btnPreviewClicked == true) {
JScrollPanePreview.setViewportView(showXMLFileView.createLabelPane());
} else {
JScrollPanePreview = new JScrollPane();
}
}
Just as an observation ;)

JPanel animation

Hy there.
I am trying to make a JPanel which reacts to certain events and plays a little animation. For example if I click on a button, it should flash red.(I need this to indicate when a file was successfully saved(green flash), or a error occurred(red flash).
I found some tutorials on animations, but I'm having a hard time changing it to fit my needs. For example most of the tutorials instantiate a Timer at the beginning. But I only need the timer to be active for that short amount of time where the flash is played and than stop. Also I need different animation types.(red flash, green flash...)
This is what I have got so far, which is basically nothing:
package MainPackage;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import javax.swing.Timer;
public class StatusBar extends JPanel implements ActionListener{
Timer t = new Timer(10, this);
boolean stop = false;
Color color;
public void paintComponent (Graphics g) {
super.paintComponent(g);
setBackground(color);
}
public void confirm(){
color = new Color(46, 204, 113);
t.start();
}
public void warning(){
color = Color.red;
t.start();
}
#Override
public void actionPerformed(ActionEvent e) {
repaint();
}
}
Thanks in advance!
public class flashclass extends JFrame{
Thread th;
Color defaultColor, flashColor;
int i;
boolean success;
JPanel p;
public flashclass(){
setSize(200, 200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
success = false;
defaultColor = new Color(214,217,223);
p = new JPanel();
JButton rbtn = new JButton("Red flash");
JButton gbtn = new JButton("Green flash");
rbtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
success = false;
flash(success);
}
});
gbtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
success = true;
flash(success);
}
});
p.add(rbtn);
p.add(gbtn);
getContentPane().add(p);
}
public void flash(boolean success){
i=0;
if(!success){
flashColor = Color.red;
}
else{
flashColor = Color.green;
}
th = new Thread(new Runnable() {
#Override
public void run() {
while(i<10){
p.setBackground(flashColor);
i++;
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
p.setBackground(defaultColor);
}
}
});
th.start();
}
}
public static void main(String args[]){
new flashclass();
}
}
So here is the finished class:
New animations can be added easily. And they also do not interfere with each other. So multiple states can be triggered simultaneously.
The StatusBar.java
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import javax.swing.JComponent;
import javax.swing.Timer;
public class StatusBar extends JComponent implements ActionListener{
int width;
int height;
boolean bLoad, bWarn, bConfirm, bError;
Timer timer;
Color bgColor;
int xPosLoad, alphaWarn, alphaConfirm, alphaError;
float cntWarn, cntConfirm, cntError;
int cntLoad;
final int barLength = 200;
public StatusBar(Color bg){
width = getWidth();
height = getHeight();
xPosLoad = -barLength;
alphaWarn = 0;
alphaConfirm = 0;
alphaError = 0;
bgColor = bg;
timer = new Timer(10, this);
this.addComponentListener(new ComponentAdapter() {
#Override
public void componentResized(ComponentEvent event) {
width = getWidth();
height = getHeight();
}
});
}
#Override
protected void paintComponent(Graphics g) {
// Background
g.setColor(bgColor);
g.fillRect(0, 0, width, height);
// loading
Graphics2D g2d = (Graphics2D)g;
GradientPaint gp = new GradientPaint(xPosLoad,0, new Color(0,0,0,0), xPosLoad+barLength, 0, new Color(200, 200, 255));
g2d.setPaint(gp);
g2d.fillRect(xPosLoad, 0, barLength, height);
// Green
g.setColor(new Color(20, 210, 60, alphaConfirm));
g.fillRect(0, 0, width, height);
// Yellow
g.setColor(new Color(255, 223, 0, alphaWarn));
g.fillRect(0, 0, width, height);
// Red
g.setColor(new Color(255, 0, 0, alphaError));
g.fillRect(0, 0, width, height);
}
#Override
public void actionPerformed(ActionEvent e) {
// step increase for all active components
boolean toggle = false;
if (bConfirm){
if(cntConfirm < 1){
cntConfirm += 0.01f;
alphaConfirm = lerp(cntConfirm, 255, true);
}else{
bConfirm = false;
cntConfirm = 0;
alphaConfirm = 0;
}
toggle = true;
}
if (bWarn){
if(cntWarn < 1){
cntWarn += 0.01f;
alphaWarn = lerp(cntWarn, 255, true);
}else{
bWarn = false;
cntWarn = 0;
alphaWarn = 0;
}
toggle = true;
}
if (bError){
if(cntError < 1){
cntError += 0.01f;
alphaError = lerp(cntError, 255, true);
}else{
bError = false;
cntError = 0;
alphaError = 0;
}
toggle = true;
}
if (bLoad){
if(cntLoad < 100){
cntLoad += 1;
xPosLoad = (cntLoad * (width + barLength)) / 100 - barLength;
}else{
cntLoad = 0;
xPosLoad = -barLength;
}
toggle = true;
}
repaint();
if (!toggle){
timer.stop();
}
}
private void startTimer(){
if (!timer.isRunning())
timer.start();
}
public void setBG(Color bg){
bgColor = bg;
System.out.println("Color: " + bgColor);
repaint();
}
// Green flash
public void confirm(){
// set values
bConfirm = true;
alphaConfirm = 255;
cntConfirm = 0;
startTimer();
}
//Yellow flash
public void warning(){
// restart values
bWarn = true;
alphaWarn = 255;
cntWarn = 0;
startTimer();
}
//Red Flash
public void error(){
// restart values
bError = true;
alphaError = 255;
cntError = 0;
startTimer();
}
//Blue load
public void loadStart(){
// restart values
bLoad = true;
xPosLoad = -barLength;
cntLoad = 0;
startTimer();
}
public void loadEnd(){
bLoad = false;
xPosLoad = -barLength;
}
private int lerp(float progress, int max, boolean inverse){
float x = progress;
float x2 = (float) Math.pow(x, 4);
float g = x + (1 - x);
float y = (float) ((float) x2 / (float)(Math.pow(g, 4)));
y = Math.min(y, 1);
y = Math.max(y, 0);
int res = (int) (y * max);
if (inverse){
res = max - res;
}
return res;
}
}
And the Example.java
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Example extends JFrame{
public static void main(String[] args){
new Example("Stat Example");
}
public Example(String title){
super(title);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
StatusBar stat = new StatusBar(Color.black);
stat.setPreferredSize(new Dimension(0, 10));
JPanel panel = new JPanel();
JButton bConfirm = new JButton("Confirm");
JButton bWarn = new JButton("Warning");
JButton bErr = new JButton("Error");
JButton bLoadS = new JButton("Start Loading");
JButton bLoadE = new JButton("End Loading");
panel.add(bConfirm);
panel.add(bWarn);
panel.add(bErr);
panel.add(bLoadS);
panel.add(bLoadE);
this.getContentPane().add(stat, BorderLayout.CENTER);
this.getContentPane().add(panel, BorderLayout.SOUTH);
this.pack();
this.setVisible(true);
// Listener
bConfirm.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
stat.confirm();
}
});
bWarn.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
stat.warning();
}
});
bErr.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
stat.error();
}
});
bLoadS.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
stat.loadStart();
}
});
bLoadE.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
stat.loadEnd();
}
});
}
}

JDBC database java using vector of vectors

Does someone can help my by creating an database query with vectors?
I want to query the Lieferranten Table of the nordwind database and showing it on a JTable.
My problem is how to show data sets in the jTable1?
This is my previous code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.sql.*;
import java.util.*;
public class Anzeige extends JFrame {
private JTable jTable1 = new JTable(5, 5);
private DefaultTableModel jTable1Model = (DefaultTableModel) jTable1.getModel();
private JScrollPane jTable1ScrollPane = new JScrollPane(jTable1);
public Anzeige (String title) {
super (title);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
int frameWidth = 676;
int frameHeight = 467;
setSize(frameWidth, frameHeight);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int x = (d.width - getSize().width) / 2;
int y = (d.height - getSize().height) / 2;
setLocation(x, y);
Container cp = getContentPane();
cp.setLayout(null);
// Anfang Komponenten
jTable1ScrollPane.setBounds(72, 56, 521, 289);
jTable1.getColumnModel().getColumn(0).setHeaderValue("Title 1");
jTable1.getColumnModel().getColumn(1).setHeaderValue("Title 2");
jTable1.getColumnModel().getColumn(2).setHeaderValue("Title 3");
jTable1.getColumnModel().getColumn(3).setHeaderValue("Title 4");
jTable1.getColumnModel().getColumn(4).setHeaderValue("Title 5");
cp.add(jTable1ScrollPane);
// Ende Komponenten
setResizable(false);
setVisible(true);
}
public static void main(String[] args) {
new Anzeige("Anzeige");
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection dbConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/nordwind", "root", "");
Statement statement = dbConn.createStatement();
ResultSet results = statement.executeQuery("SELECT * FROM Lieferranten");
Vector vector = new Vector();
while (results.next()) {
String s1 = results.getString(2);
String s2 = results.getString(5);
System.out.println(s1 + "\n" + s2);
System.out.println(results.getString(2) + " " + results.getString(5));
Vector data = new Vector();
data.add(results.getString(1));
data.add(results.getString(2));
vector.add(data);
}
//results.close();
statement.close();
dbConn.close();
}
catch (InstantiationException e) {
System.err.println("Error in Instantiation!");
}
catch (ClassNotFoundException e) {
System.err.println("Class not found!");
}
catch (IllegalAccessException e) {
System.err.println("Access denied!");
}
catch (SQLException e) {
System.err.println("SQL Error!");
}
}
}
I assume that you will get five column values as you had added five column titles. After that use addRow(java.util.Vector) method of DefaultTableModel to insert row in jTable1.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.sql.*;
import java.util.*;
public class Anzeige extends JFrame {
private JTable jTable1 = new JTable(5, 5);
private DefaultTableModel jTable1Model = (DefaultTableModel) jTable1.getModel();
private JScrollPane jTable1ScrollPane = new JScrollPane(jTable1);
public Anzeige (String title) {
super (title);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
int frameWidth = 676;
int frameHeight = 467;
setSize(frameWidth, frameHeight);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int x = (d.width - getSize().width) / 2;
int y = (d.height - getSize().height) / 2;
setLocation(x, y);
Container cp = getContentPane();
cp.setLayout(null);
// Anfang Komponenten
jTable1ScrollPane.setBounds(72, 56, 521, 289);
jTable1.getColumnModel().getColumn(0).setHeaderValue("Title 1");
jTable1.getColumnModel().getColumn(1).setHeaderValue("Title 2");
jTable1.getColumnModel().getColumn(2).setHeaderValue("Title 3");
jTable1.getColumnModel().getColumn(3).setHeaderValue("Title 4");
jTable1.getColumnModel().getColumn(4).setHeaderValue("Title 5");
cp.add(jTable1ScrollPane);
// Ende Komponenten
setResizable(false);
setVisible(true);
}
public static void main(String[] args) {
new Anzeige("Anzeige");
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection dbConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/nordwind", "root", "");
Statement statement = dbConn.createStatement();
ResultSet results = statement.executeQuery("SELECT * FROM Lieferranten");
while (results.next()) {
String s1 = results.getString(2);
String s2 = results.getString(5);
System.out.println(s1 + "\n" + s2);
System.out.println(results.getString(2) + " " + results.getString(5));
Vector data = new Vector();
data.add(results.getString(1));
data.add(results.getString(2));
data.add(results.getString(3));
data.add(results.getString(4));
data.add(results.getString(5));
jTable1Model.addRow(data);
}
//results.close();
statement.close();
dbConn.close();
}
catch (InstantiationException e) {
System.err.println("Error in Instantiation!");
}
catch (ClassNotFoundException e) {
System.err.println("Class not found!");
}
catch (IllegalAccessException e) {
System.err.println("Access denied!");
}
catch (SQLException e) {
System.err.println("SQL Error!");
}
}
}

isSelected method for jRadioButton doesnt work

my isSelected method for the radio buttons are not working, even if i select them when i run the program, i am new to java gui coding so plz explain according to that, i am posting the whole gui's class code.And i am using eclipse swing designer
public class gui {
private JFrame frame;
private final ButtonGroup buttonGroup = new ButtonGroup();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
gui window = new gui();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
* #throws FileNotFoundException
*/
public gui() throws FileNotFoundException {
initialize();
}
/**
* Initialize the contents of the frame.
* #throws FileNotFoundException
*/
private void initialize() throws FileNotFoundException {
FileReader reader=new FileReader("C:\\Users\\kkj\\workspace\\javaproject\\src\\Database.txt");
Scanner in=new Scanner(reader);
BList Restaurant=new BList();
BList ATM=new BList();
BList Hospital=new BList();
BList Hotels=new BList();
BList Petrol=new BList();
final Llist locations=new Llist();
System.out.println("Loading");
while(in.hasNextLine())
{
BNode bnode=new BNode();
bnode.name=in.nextLine();
//System.out.println(bnode.name);
String type=in.nextLine();
bnode.loc=in.nextLine();
if(type.equals("Restaurant"))
{
Restaurant.insert(bnode);
}
if(type.equals("ATM"))
{
ATM.insert(bnode);
}
if(type.equals("Hospital"))
{
Hospital.insert(bnode);
}
if(type.equals("Hotels"))
{
Hotels.insert(bnode);
}
if(type.equals("Petrol"))
{
Petrol.insert(bnode);
}
}
FileReader reader2=new FileReader("C:\\Users\\kkj\\workspace\\javaproject\\src\\locations.txt");
Scanner inL=new Scanner(reader2);
int s=0;
while(inL.hasNextLine())
{
LNode loc=new LNode();
loc.Name=inL.nextLine();
loc.dist=s++;
BNode temp;
temp=Restaurant.head;
while(temp.next!=null)
{ if(temp.loc.equals(loc.Name))
{loc.rest=temp;break;}
temp=temp.next;
}
temp=Hospital.head;
while(temp.next!=null)
{ if(temp.loc.equals(loc.Name))
{loc.Hospital=temp;break;}
temp=temp.next;
}
temp=Hotels.head;
while(temp.next!=null)
{ if(temp.loc.equals(loc.Name))
{loc.Hotels=temp;break;}
temp=temp.next;
}
//loc.hotels=temp;
temp=ATM.head;
while(temp.next!=null)
{ if(temp.loc.equals(loc.Name))
{loc.ATM=temp;break;}
temp=temp.next;
}
locations.insert(loc);
}
System.out.println("Loaded");
System.out.println(">>>>>>>>>>>Restaurants<<<<<<<<<<<<");
Restaurant.disp();
System.out.println(">>>>>>>>>>>Hotels<<<<<<<<<<<<");
Hotels.disp();
System.out.println(">>>>>>>>>>>Hospital<<<<<<<<<<<<");
Hospital.disp();
System.out.println(">>>>>>>>>>>ATM's<<<<<<<<<<<<");
ATM.disp();
System.out.println(">>>>>>>>>>>Locations<<<<<<<<<<<<");
locations.disp();
final String curr="Bsk";
String locin;
final String typein="Hospital";
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JRadioButton rdbtnBsk = new JRadioButton("Bsk");
buttonGroup.add(rdbtnBsk);
rdbtnBsk.setBounds(26, 35, 109, 23);
frame.getContentPane().add(rdbtnBsk);
JRadioButton rdbtnKoramangala = new JRadioButton("Koramangala");
buttonGroup.add(rdbtnKoramangala);
rdbtnKoramangala.setBounds(26, 72, 109, 23);
frame.getContentPane().add(rdbtnKoramangala);
JRadioButton rdbtnMgRoad = new JRadioButton("MG Road");
buttonGroup.add(rdbtnMgRoad);
rdbtnMgRoad.setBounds(26, 125, 109, 23);
frame.getContentPane().add(rdbtnMgRoad);
if(rdbtnBsk.isSelected())
{
locin="Bsk";
}
if(rdbtnKoramangala.isSelected())
{
locin="Koramangala";
}
if(rdbtnMgRoad.isSelected())
{
locin="MG Road";
}
else System.exit(2);
final String locinn=locin;
JButton btnOutput = new JButton("output");
btnOutput.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
Output out1=new Output();
System.out.println(">>>>>>>>>>>"+typein+" in "+locinn+"<<<<<<<<<<<<");
out1.display(locations, locinn, typein,curr);
}
});
btnOutput.setBounds(182, 193, 89, 23);
frame.getContentPane().add(btnOutput);
}
private class SwingAction extends AbstractAction {
public SwingAction() {
putValue(NAME, "SwingAction");
putValue(SHORT_DESCRIPTION, "Some short description");
}
public void actionPerformed(ActionEvent e) {
}
}
}
Am also new to Java Programming, but this might work, it worked for me.
Put the whole if/else block inside the actionPerformed() method of the "output" Button, like this :
JButton btnOutput = new JButton("output");
btnOutput.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{ if(rdbtnBsk.isSelected())
{
locin="Bsk";
}
else if(rdbtnKoramangala.isSelected())
{
locin="Koramangala";
}
else if(rdbtnMgRoad.isSelected())
{
locin="MG Road";
}
final String locinn=locin;
Output out1=new Output();
System.out.println(">>>>>>>>>>>"+typein+" in "+locinn+"<<<<<<<<<<<<");
out1.display(locations, locinn, typein,curr);
}
});
btnOutput.setBounds(182, 193, 89, 23);
frame.getContentPane().add(btnOutput);
}

Resources