I made an application that has some TextFields. When I click to search an item it popups JTable that contains a list of items. But the problem is how we can do it. I have tried many times but I failed please help in my project.
this is my code that i have tried
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FocusTraversalPolicy;
import javax.swing.JFrame;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.Font;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.SwingConstants;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import com.alee.laf.WebLookAndFeel;
import com.toedter.calendar.JDateChooser;
import javax.swing.JComboBox;
import javax.swing.JButton;
import java.awt.CardLayout;
import java.awt.Component;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
public class DailySales3 {
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
private JTextField ItemID;
private JTextField ItemName;
private JTextField Stock;
private JTextField Qnty;
private JTextField UnitPrice;
private JTextField Tax;
private JTextField Amount;
private JTextField Discount;
private Connection con;
private String query,auto;
private PreparedStatement PStat;
private ResultSet res;
private DefaultTableModel model,model1;
private JTable table_2;
private JScrollPane scrollPane;
private double AmountGet=0.0,AmountCal=0.0,AmountResult=0.0;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
WebLookAndFeel.install();
DailySales3 window = new DailySales3();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public DailySales3() {
initialize();
con=Database.Database();
}
public void AmountCalculate()
{
AmountGet=Double.parseDouble(UnitPrice.getText());
AmountCal=Double.parseDouble(Qnty.getText());
AmountResult=AmountCal*AmountGet;
Amount.setText(Double.toString(AmountResult));
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setResizable(false);
frame.setBounds(100, 100, 1229, 658);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel panel = new JPanel();
GroupLayout groupLayout = new GroupLayout(frame.getContentPane());
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(panel, GroupLayout.DEFAULT_SIZE, 1213, Short.MAX_VALUE)
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(panel, GroupLayout.DEFAULT_SIZE, 630, Short.MAX_VALUE)
);
panel.setLayout(null);
JLabel label = new JLabel("Bill No");
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setFont(new Font("Georgia", Font.BOLD, 12));
label.setBounds(10, 11, 73, 35);
panel.add(label);
textField = new JTextField();
textField.setFont(new Font("Georgia", Font.BOLD, 15));
textField.setEditable(false);
textField.setColumns(10);
textField.setBounds(82, 11, 132, 35);
panel.add(textField);
JLabel label_1 = new JLabel("Bill Date");
label_1.setHorizontalAlignment(SwingConstants.CENTER);
label_1.setFont(new Font("Georgia", Font.BOLD, 12));
label_1.setBounds(224, 11, 73, 35);
panel.add(label_1);
JDateChooser dateChooser = new JDateChooser();
dateChooser.setFont(new Font("Georgia", Font.BOLD, 15));
dateChooser.setBounds(296, 11, 132, 35);
panel.add(dateChooser);
JLabel label_2 = new JLabel("Sales Type");
label_2.setHorizontalAlignment(SwingConstants.CENTER);
label_2.setFont(new Font("Georgia", Font.BOLD, 12));
label_2.setBounds(438, 11, 73, 35);
panel.add(label_2);
JComboBox comboBox = new JComboBox();
comboBox.setFont(new Font("Georgia", Font.BOLD, 15));
comboBox.setBounds(524, 10, 190, 35);
panel.add(comboBox);
JLabel label_3 = new JLabel("Customers");
label_3.setHorizontalAlignment(SwingConstants.CENTER);
label_3.setFont(new Font("Georgia", Font.BOLD, 12));
label_3.setBounds(724, 11, 73, 35);
panel.add(label_3);
textField_1 = new JTextField();
textField_1.setFont(new Font("Georgia", Font.BOLD, 15));
textField_1.setColumns(10);
textField_1.setBounds(797, 12, 210, 35);
panel.add(textField_1);
JButton button = new JButton("");
button.setBounds(1016, 12, 38, 35);
panel.add(button);
JPanel panel_1 = new JPanel();
panel_1.setBounds(10, 68, 997, 43);
panel.add(panel_1);
JLabel lblItemId = new JLabel("Item ID");
lblItemId.setHorizontalAlignment(SwingConstants.CENTER);
lblItemId.setPreferredSize(new Dimension(91, 35));
lblItemId.setFont(new Font("Georgia", Font.BOLD, 12));
panel_1.add(lblItemId);
JLabel lblItemName = new JLabel("Item Name");
lblItemName.setPreferredSize(new Dimension(273, 35));
lblItemName.setHorizontalAlignment(SwingConstants.CENTER);
lblItemName.setFont(new Font("Georgia", Font.BOLD, 12));
panel_1.add(lblItemName);
JLabel lblStock = new JLabel("Stock");
lblStock.setPreferredSize(new Dimension(86, 35));
lblStock.setHorizontalAlignment(SwingConstants.CENTER);
lblStock.setFont(new Font("Georgia", Font.BOLD, 12));
panel_1.add(lblStock);
JLabel lblQnty = new JLabel("Qnty");
lblQnty.setPreferredSize(new Dimension(86, 35));
lblQnty.setHorizontalAlignment(SwingConstants.CENTER);
lblQnty.setFont(new Font("Georgia", Font.BOLD, 12));
panel_1.add(lblQnty);
JLabel lblUnitPrice = new JLabel("Unit Price");
lblUnitPrice.setPreferredSize(new Dimension(123, 35));
lblUnitPrice.setHorizontalAlignment(SwingConstants.CENTER);
lblUnitPrice.setFont(new Font("Georgia", Font.BOLD, 12));
panel_1.add(lblUnitPrice);
JLabel lblTax = new JLabel("Tax (%)");
lblTax.setPreferredSize(new Dimension(86, 35));
lblTax.setHorizontalAlignment(SwingConstants.CENTER);
lblTax.setFont(new Font("Georgia", Font.BOLD, 12));
panel_1.add(lblTax);
JLabel lblDiscount = new JLabel("Discount (%)");
lblDiscount.setPreferredSize(new Dimension(86, 35));
lblDiscount.setHorizontalAlignment(SwingConstants.CENTER);
lblDiscount.setFont(new Font("Georgia", Font.BOLD, 12));
panel_1.add(lblDiscount);
JLabel lblAmount = new JLabel("Amount");
lblAmount.setPreferredSize(new Dimension(123, 35));
lblAmount.setHorizontalAlignment(SwingConstants.CENTER);
lblAmount.setFont(new Font("Georgia", Font.BOLD, 12));
panel_1.add(lblAmount);
JPanel panel_2 = new JPanel();
panel_2.setBounds(10, 112, 997, 43);
panel.add(panel_2);
panel_2.setLayout(null);
ItemID = new JTextField();
ItemID.setBounds(5, 5, 89, 34);
ItemID.setFont(new Font("Georgia", Font.BOLD, 15));
ItemID.setColumns(10);
panel_2.add(ItemID);
ItemName = new JTextField();
ItemName.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
if(ItemName.getText().equals(""))
{
while(table_2.getRowCount()>0)
{
model.removeRow(0);
}
}
else if(e.getKeyCode()==KeyEvent.VK_ENTER)
{
table_2.requestFocus();
table_2.changeSelection(0, 0, false, false);
}
else
{
try {
while(table_2.getRowCount()>0)
{
model.removeRow(0);
}
query="Select Item_No,Item_Name,Current_Stock,Unit_Price,Tax,Discount from StockEntry where Item_Name like '"+ItemName.getText().trim()+"%'";
PStat=con.prepareStatement(query);
res=PStat.executeQuery();
while(res.next())
{
String ItemNo=res.getString("Item_No");
String ItemName=res.getString("Item_Name");
double CStock=res.getDouble("Current_Stock");
double PRate=res.getDouble("Unit_Price");
double tax=res.getDouble("Tax");
double discount=res.getDouble("Discount");
Object row[]= {ItemNo,ItemName,CStock,PRate,tax,discount};
model.addRow(row);
}
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
});
ItemName.setBounds(98, 5, 276, 34);
ItemName.setFont(new Font("Georgia", Font.BOLD, 15));
ItemName.setColumns(10);
panel_2.add(ItemName);
Stock = new JTextField();
Stock.setBounds(376, 5, 89, 34);
Stock.setFont(new Font("Georgia", Font.BOLD, 15));
Stock.setColumns(10);
panel_2.add(Stock);
Qnty = new JTextField();
Qnty.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_ENTER)
{
model1=(DefaultTableModel)table.getModel();
String itemno=ItemID.getText();
String itemname=ItemName.getText();
String qnty=Qnty.getText();
String unitprice=UnitPrice.getText();
String tax=Tax.getText();
String discount=Discount.getText();
String amount=Amount.getText();
Object rows[]= {itemno,itemname,qnty,unitprice,tax,discount,amount};
model1.addRow(rows);
}
}
});
Qnty.setBounds(469, 5, 89, 34);
Qnty.setFont(new Font("Georgia", Font.BOLD, 15));
Qnty.getDocument().addDocumentListener(new DocumentListener()
{
#Override
public void changedUpdate(DocumentEvent arg0) {
AmountCalculate();
}
#Override
public void insertUpdate(DocumentEvent arg0) {
AmountCalculate();
}
#Override
public void removeUpdate(DocumentEvent arg0) {
}
});
Qnty.setColumns(10);
panel_2.add(Qnty);
UnitPrice = new JTextField();
UnitPrice.setBounds(561, 5, 122, 34);
UnitPrice.setFont(new Font("Georgia", Font.BOLD, 15));
UnitPrice.setColumns(10);
panel_2.add(UnitPrice);
Tax = new JTextField();
Tax.setBounds(687, 5, 89, 34);
Tax.setFont(new Font("Georgia", Font.BOLD, 15));
Tax.setColumns(10);
panel_2.add(Tax);
Discount = new JTextField();
Discount.setBounds(778, 5, 89, 34);
Discount.setFont(new Font("Georgia", Font.BOLD, 15));
Discount.setColumns(10);
panel_2.add(Discount);
Amount = new JTextField();
Amount.setBounds(869, 5, 122, 34);
Amount.setFont(new Font("Georgia", Font.BOLD, 15));
Amount.setColumns(10);
panel_2.add(Amount);
scrollPane = new JScrollPane();
scrollPane.setBounds(10, 156, 997, 412);
panel.add(scrollPane);
table_2 = new JTable();
table_2.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_ENTER)
{
try
{
int row=table_2.getSelectedRow();
String TableClicked=(table_2.getModel().getValueAt(row, 0).toString());
query="Select * from StockEntry where Item_No='"+TableClicked+"'";
PStat=con.prepareStatement(query);
res=PStat.executeQuery();
if(res.next())
{
String Itemno=res.getString("Item_No");
ItemID.setText(Itemno);
String itemName=res.getString("Item_Name");
ItemName.setText(itemName);
String PurchaseRate=Double.toString(res.getDouble("Unit_Price"));
UnitPrice.setText(PurchaseRate);
String stock=Double.toString(res.getDouble("Current_Stock"));
Stock.setText(stock);
String tax=Double.toString(res.getDouble("Tax"));
Tax.setText(tax);
String disc=Double.toString(res.getDouble("Discount"));
Discount.setText(disc);
}
}
catch(Exception e1)
{
e1.printStackTrace();
}
finally
{
try
{
PStat.close();
res.close();
}
catch(Exception e2)
{
e2.printStackTrace();
}
}
while(table_2.getRowCount()>0)
{
model.removeRow(0);
}
Qnty.requestFocus();
}
}
});
model=(DefaultTableModel)table_2.getModel();
model.addColumn("Item ID");
model.addColumn("Item Name");
model.addColumn("Qnty");
model.addColumn("Unit Price");
model.addColumn("Tax (%)");
model.addColumn("Discount (%)");
model.addColumn("Amount");
table_2.setRowHeight(30);
table_2.getTableHeader().setFont(new Font("Georgia", Font.BOLD, 14));
table_2.setFont(new Font("Georgia", Font.BOLD, 17));
scrollPane.setViewportView(table_2);
JScrollPane scrollPane_1 = new JScrollPane();
scrollPane_1.setBounds(10, 156, 997, 412);
panel.add(scrollPane_1);
table = new JTable();
model1=(DefaultTableModel)table.getModel();
model1.addColumn("Item ID");
model1.addColumn("Item Name");
model1.addColumn("Qnty");
model1.addColumn("Unit Price");
model1.addColumn("Tax (%)");
model1.addColumn("Discount (%)");
model1.addColumn("Amount");
table.setRowHeight(30);
table.setFont(new Font("Georgia", Font.BOLD, 17));
scrollPane_1.setViewportView(table);
frame.getContentPane().setLayout(groupLayout);
}
}
Related
i am developing an application for which i have created different application windows. Now i'm in a confusion on how i can link one to another using a button, that is when i click a button, it has to navigate to the other application window. I have tried it with frames from same file, but that doesnt satisfy my need.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.Font;
import javax.swing.SwingConstants;
import java.awt.Color;
import java.awt.SystemColor;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.UIManager;
import java.awt.event.*;
public class Start {
private JFrame frame;
private JTextField txtLogInTo;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Start window = new Start();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private void initialize() {
frame = new JFrame();
frame.getContentPane().setBackground(SystemColor.inactiveCaption);
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewButton = new JButton("USER");
btnNewButton.setBackground(SystemColor.activeCaption);
btnNewButton.setBounds(152, 81, 132, 23);
frame.getContentPane().add(btnNewButton);
JButton btnNewButton_1 = new JButton("BUS ADMIN");
btnNewButton_1.setBackground(SystemColor.activeCaption);
btnNewButton_1.setBounds(152, 131, 132, 23);
frame.getContentPane().add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("SYSTEM ADMIN");
btnNewButton_2.setBackground(SystemColor.activeCaption);
btnNewButton_2.setBounds(152, 179, 132, 23);
frame.getContentPane().add(btnNewButton_2);
txtLogInTo = new JTextField();
txtLogInTo.setBounds(95, 27, 252, 36);
txtLogInTo.setBackground(SystemColor.inactiveCaption);
txtLogInTo.setHorizontalAlignment(SwingConstants.CENTER);
txtLogInTo.setFont(new Font("Tekton Pro Cond", Font.BOLD | Font.ITALIC, 20));
txtLogInTo.setText("LOG IN TO ENTER THE SYSTEM");
frame.getContentPane().add(txtLogInTo);
txtLogInTo.setColumns(10);
class handler implements ActionListener
{
//must implement method
//This is triggered whenever the user clicks the login button
public void actionPerformed(ActionEvent ae)
{
if(btnNewButton.isEnabled())
{User u;
}
}//if
}//method
}//inner class
}
and this above program is where i have to navigate when i click a button from the below program
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import java.awt.Font;
import javax.swing.JTextArea;
import javax.swing.JSplitPane;
import javax.swing.JScrollPane;
import javax.swing.JInternalFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import java.awt.SystemColor;
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JPopupMenu;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class User {
private JFrame frame,frame2;
private JTextField txtWelcomeUser;
private JTextField txtEnterYourDetails;
private JTextField txtName;
private JTextField txtAge;
private JTextField txtPhoneNo;
private JTextField txtMailId;
private JTextField txtStart;
private JTextField txtDestination;
private JTextArea textArea_4;
private JTextArea textArea_5;
private JTextField txtEn;
private ActionListener action;
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
User window = new User();
window.frame.setVisible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
public User() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(0, 0, 750, 550);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
txtWelcomeUser = new JTextField();
txtWelcomeUser.setBackground(SystemColor.inactiveCaption);
txtWelcomeUser.setFont(new Font("Tahoma", Font.PLAIN, 26));
txtWelcomeUser.setText("Welcome user");
txtWelcomeUser.setBounds(176, 11, 173, 52);
frame.getContentPane().add(txtWelcomeUser);
txtWelcomeUser.setColumns(10);
txtEnterYourDetails = new JTextField();
txtEnterYourDetails.setBackground(SystemColor.activeCaption);
txtEnterYourDetails.setFont(new Font("Tahoma", Font.PLAIN, 20));
txtEnterYourDetails.setText("Enter your details");
txtEnterYourDetails.setBounds(176, 74, 173, 36);
frame.getContentPane().add(txtEnterYourDetails);
txtEnterYourDetails.setColumns(10);
txtName = new JTextField();
txtName.setBackground(SystemColor.inactiveCaption);
txtName.setText("Name");
txtName.setBounds(93, 136, 86, 20);
frame.getContentPane().add(txtName);
txtName.setColumns(10);
txtAge = new JTextField();
txtAge.setBackground(SystemColor.inactiveCaption);
txtAge.setText("Age");
txtAge.setBounds(93, 167, 86, 20);
frame.getContentPane().add(txtAge);
txtAge.setColumns(10);
txtPhoneNo = new JTextField();
txtPhoneNo.setBackground(SystemColor.inactiveCaption);
txtPhoneNo.setText("Phone No");
txtPhoneNo.setBounds(93, 198, 86, 20);
frame.getContentPane().add(txtPhoneNo);
txtPhoneNo.setColumns(10);
txtMailId = new JTextField();
txtMailId.setBackground(SystemColor.inactiveCaption);
txtMailId.setText("Mail id");
txtMailId.setBounds(93, 229, 86, 20);
frame.getContentPane().add(txtMailId);
txtMailId.setColumns(10);
JTextArea textArea = new JTextArea();
textArea.setBounds(236, 134, 124, 20);
frame.getContentPane().add(textArea);
JTextArea textArea_1 = new JTextArea();
textArea_1.setBounds(236, 165, 124, 20);
frame.getContentPane().add(textArea_1);
JTextArea textArea_2 = new JTextArea();
textArea_2.setBounds(236, 196, 124, 20);
frame.getContentPane().add(textArea_2);
JTextArea textArea_3 = new JTextArea();
textArea_3.setBounds(236, 227, 124, 20);
frame.getContentPane().add(textArea_3);
txtStart = new JTextField();
txtStart.setBackground(SystemColor.inactiveCaption);
txtStart.setText("Start ");
txtStart.setBounds(93, 260, 86, 20);
frame.getContentPane().add(txtStart);
txtStart.setColumns(10);
txtDestination = new JTextField();
txtDestination.setBackground(SystemColor.inactiveCaption);
txtDestination.setText("Destination");
txtDestination.setBounds(93, 291, 86, 20);
frame.getContentPane().add(txtDestination);
txtDestination.setColumns(10);
textArea_4 = new JTextArea();
textArea_4.setBounds(236, 258, 124, 20);
frame.getContentPane().add(textArea_4);
textArea_5 = new JTextArea();
textArea_5.setBounds(236, 289, 124, 20);
frame.getContentPane().add(textArea_5);
JPanel panel = new JPanel();
panel.setForeground(new Color(0, 0, 0));
panel.setBackground(SystemColor.inactiveCaption);
panel.setBounds(433, 213, 124, 115);
frame.getContentPane().add(panel);
txtEn = new JTextField();
txtEn.setBackground(SystemColor.inactiveCaption);
txtEn.setText("Enter Bus No");
txtEn.setBounds(93, 322, 86, 20);
frame.getContentPane().add(txtEn);
txtEn.setColumns(10);
JTextArea textArea_6 = new JTextArea();
textArea_6.setBounds(236, 320, 124, 20);
frame.getContentPane().add(textArea_6);
JButton btnBookTicket = new JButton("Book Ticket");
btnBookTicket.setBackground(SystemColor.activeCaption);
btnBookTicket.setBounds(176, 376, 116, 23);
frame.getContentPane().add(btnBookTicket);
JPopupMenu popupMenu_1 = new JPopupMenu();
popupMenu_1.setBounds(327, 376, 200, 50);
frame.getContentPane().add(popupMenu_1);
if(!textArea.isEnabled()||!textArea_2.isEnabled()||!textArea_3.isEnabled()||!textArea_3.isEnabled()||!textArea_4.isEnabled()||!textArea_5.isEnabled()||!textArea_6.isEnabled())
{
JOptionPane.showMessageDialog(null, "You have not entered a few details","UnSuccessful",
JOptionPane.INFORMATION_MESSAGE);
}
if(btnBookTicket.isEnabled())
{
btnBookTicket.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "You have booked successfully","Success",
JOptionPane.INFORMATION_MESSAGE);
JButton button = (JButton) e.getSource();
if (button == btnBookTicket)
{
frame2 = new JFrame("FRAME 2");
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame2.setLocationByPlatform(true);
JPanel contentPane2 = new JPanel();
contentPane2.setBackground(Color.DARK_GRAY);
JButton btnBookTicket1 = new JButton("Cancel Ticket");
btnBookTicket1.setBackground(SystemColor.activeCaption);
btnBookTicket1.setBounds(0, 30, 35, 23);
contentPane2.add(btnBookTicket1);
frame2.getContentPane().add(contentPane2);
frame2.setSize(600, 600);
frame2.setVisible(true);
frame.setVisible(false);
}
btnBookTicket.addActionListener(action);
}
});
}
}
}
I am curious to ask that is it possible to transfer a data from one JPanel to another. I'm currently doing a swing java project which has a profile page and a profile edit page. I wanted to try out creating a method to get the text in a textfield in the profile edit page and then return the textfield.getText();. Then I will follow by calling the exact method from the profile page and setting it as a JLabel. However, I wasn't sure how to do this...
I updated the codes below.
Here is the Profile Edit Page:
package Project;
import java.awt.Color;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.border.LineBorder;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class ProfileEdit extends MasterPanel {
private JTextField txtbxFullName;
private JTextField txtAdmissionNo;
private JTextField txtbxContactNo;
private JTextField txtFieldDiploma;
/**
* Create the panel.
*/
public ProfileEdit(JFrame mf) {
super(mf);
JLabel lblUserProfile = new JLabel("");
lblUserProfile.setBorder(BorderFactory.createTitledBorder(null,"User Profile",0,0, new Font("Tahoma", Font.PLAIN, 15), Color.WHITE));
lblUserProfile.setForeground(Color.WHITE);
lblUserProfile.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblUserProfile.setBounds(60, 103, 514, 297);
add(lblUserProfile);
JLabel lblDisplayPic = new JLabel("");
lblDisplayPic.setBorder(new LineBorder(Color.WHITE));
lblDisplayPic.setIcon(new ImageIcon(ProfileEdit.class.getResource("/javaProject/images/default-avatar.png")));
lblDisplayPic.setBounds(100, 132, 90, 100);
add(lblDisplayPic);
JLabel lblFullName = new JLabel("Full Name:");
lblFullName.setForeground(Color.WHITE);
lblFullName.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblFullName.setBounds(235, 132, 76, 14);
add(lblFullName);
JLabel lblGender = new JLabel("Gender: ");
lblGender.setForeground(Color.WHITE);
lblGender.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblGender.setBounds(235, 168, 60, 14);
add(lblGender);
JRadioButton rdbtnMale = new JRadioButton("Male");
rdbtnMale.setBackground(Color.DARK_GRAY);
rdbtnMale.setFont(new Font("Tahoma", Font.PLAIN, 13));
rdbtnMale.setForeground(Color.WHITE);
rdbtnMale.setBounds(326, 164, 68, 23);
add(rdbtnMale);
JRadioButton rdbtnFemale = new JRadioButton("Female");
rdbtnFemale.setBackground(Color.DARK_GRAY);
rdbtnFemale.setFont(new Font("Tahoma", Font.PLAIN, 13));
rdbtnFemale.setForeground(Color.WHITE);
rdbtnFemale.setBounds(396, 164, 77, 23);
add(rdbtnFemale);
ButtonGroup genderRdBtn = new ButtonGroup();
genderRdBtn.add(rdbtnFemale);
genderRdBtn.add(rdbtnMale);
JLabel lblAdmissionNo = new JLabel("Admission No:");
lblAdmissionNo.setForeground(Color.WHITE);
lblAdmissionNo.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblAdmissionNo.setBounds(235, 203, 97, 14);
add(lblAdmissionNo);
JLabel lblContactNo = new JLabel("Contact No:");
lblContactNo.setForeground(Color.WHITE);
lblContactNo.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblContactNo.setBounds(235, 240, 77, 14);
add(lblContactNo);
JLabel lblDiploma = new JLabel("Diploma In:");
lblDiploma.setForeground(Color.WHITE);
lblDiploma.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblDiploma.setBounds(235, 275, 76, 14);
add(lblDiploma);
txtbxFullName = new JTextField();
txtbxFullName.setBounds(326, 130, 147, 20);
add(txtbxFullName);
txtbxFullName.setColumns(10);
txtAdmissionNo = new JTextField();
txtAdmissionNo.setBounds(326, 201, 147, 20);
add(txtAdmissionNo);
txtAdmissionNo.setColumns(10);
txtbxContactNo = new JTextField();
txtbxContactNo.setBounds(326, 238, 147, 20);
add(txtbxContactNo);
txtbxContactNo.setColumns(10);
txtFieldDiploma = new JTextField();
txtFieldDiploma.setBounds(326, 273, 147, 20);
add(txtFieldDiploma);
txtFieldDiploma.setColumns(10);
JButton btnSubmit = new JButton("SUBMIT");
btnSubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Home home = new Home(mf);
mf.setContentPane(home);
mf.setVisible(true);
}
});
btnSubmit.setBounds(235, 336, 114, 23);
add(btnSubmit);
JButton btnCancel = new JButton("CANCEL");
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Home home = new Home(mf);
mf.setContentPane(home);
mf.setVisible(true);
}
});
btnCancel.setBounds(359, 336, 114, 23);
add(btnCancel);
JButton btnBrowse = new JButton("Browse");
btnBrowse.setBounds(101, 247, 89, 23);
add(btnBrowse);
}
}
Here is the Profile Page :
package Project;
import java.awt.Color;
import Project.ProfileEdit;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.border.LineBorder;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import Project.ProfileEdit;
public class Home extends MasterPanel {
/**
* Create the panel.
*/
public Home(JFrame mf) {
super(mf);
JLabel lblUserProfile = new JLabel("");
//createTitledBorder(border, string, int, int, font, color)
lblUserProfile.setBorder(BorderFactory.createTitledBorder(null,"User Profile",0,0, new Font("Tahoma", Font.PLAIN, 15), Color.WHITE));
//setBounds(left, top, right, bottom)
lblUserProfile.setBounds(60, 103, 510, 267);
add(lblUserProfile);
JLabel lblDisplayPic = new JLabel("");
lblDisplayPic.setBorder(new LineBorder(Color.WHITE));
lblDisplayPic.setIcon(new ImageIcon(Home.class.getResource("/javaProject/images/default-avatar.png")));
lblDisplayPic.setBounds(108, 142, 90, 100);
add(lblDisplayPic);
JLabel lblFullName = new JLabel("Full Name:");
lblFullName.setForeground(Color.WHITE);
lblFullName.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblFullName.setBounds(251, 131, 76, 14);
add(lblFullName);
JLabel lblGender = new JLabel("Gender: ");
lblGender.setForeground(Color.WHITE);
lblGender.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblGender.setBounds(251, 151, 60, 14);
add(lblGender);
JLabel lblAdmissionNo = new JLabel("Admission No:");
lblAdmissionNo.setForeground(Color.WHITE);
lblAdmissionNo.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblAdmissionNo.setBounds(251, 176, 97, 14);
add(lblAdmissionNo);
JLabel lblContactNo = new JLabel("Contact No:");
lblContactNo.setForeground(Color.WHITE);
lblContactNo.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblContactNo.setBounds(251, 195, 77, 14);
add(lblContactNo);
JLabel lblDiploma = new JLabel("Diploma In:");
lblDiploma.setForeground(Color.WHITE);
lblDiploma.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblDiploma.setBounds(251, 218, 76, 14);
add(lblDiploma);
JButton btnEdit = new JButton("Edit ");
btnEdit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
ProfileEdit ProfileEdit = new ProfileEdit(mf);
mf.setContentPane(ProfileEdit);
mf.setVisible(true);
}
});
btnEdit.setBounds(251, 309, 89, 23);
add(btnEdit);
}
}
and Lastly, here is the Master Panel if you guys need it :
package Project;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import java.awt.Color;
import javax.swing.JSeparator;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.FlowLayout;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JLabel;
import javax.swing.BoxLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class MasterPanel extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
protected JFrame myFrame = null;
/**
* Create the panel.
*/
public MasterPanel(JFrame mf) {
myFrame = mf;
setBackground(Color.DARK_GRAY);
setLayout(null);
//set a new menubar for home
JMenuBar menuBarHome = new JMenuBar();
menuBarHome.setForeground(Color.BLACK);
menuBarHome.setBackground(Color.WHITE);
// x,y,width,height
// >x = right, <x = left
// >y = bottom, <y = up
menuBarHome.setBounds(80, 40, 97, 21);
//length and height
menuBarHome.setSize(48, 20);
add(menuBarHome);
JMenu home = new JMenu("HOME");
home.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
Home home = new Home(mf);
mf.setContentPane(home);
mf.setVisible(true);
}
});
menuBarHome.add(home);
//set a new menubar for calendar
JMenuBar menuBarCalendar = new JMenuBar();
menuBarCalendar.setForeground(Color.BLACK);
menuBarCalendar.setBackground(Color.WHITE);
menuBarCalendar.setBounds(145, 40, 97, 21);
menuBarCalendar.setSize(75, 20);
add(menuBarCalendar);
JMenu calendar = new JMenu("CALENDAR");
calendar.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
Calendar calendar = new Calendar(mf);
mf.setContentPane(calendar);
mf.setVisible(true);
}
});
menuBarCalendar.add(calendar);
JMenuBar menuBarAcademic = new JMenuBar();
menuBarAcademic.setForeground(Color.BLACK);
menuBarAcademic.setBackground(Color.WHITE);
menuBarAcademic.setBounds(235, 40, 220, 21);
menuBarAcademic.setSize(72, 20);
add(menuBarAcademic);
JMenu academic = new JMenu("ACADEMIC");
menuBarAcademic.add(academic);
//add sub menu into the academic
JMenuItem lectureNotes = new JMenuItem("Lecture Notes");
lectureNotes.setForeground(Color.BLACK);
lectureNotes.setBackground(Color.WHITE);
lectureNotes.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
LectureNotes LectureNotes = new LectureNotes(mf);
mf.setContentPane(LectureNotes);
mf.setVisible(true);
}
});
academic.add(lectureNotes);
JMenuItem resulttracker = new JMenuItem("Result Tracker");
resulttracker.setForeground(Color.BLACK);
resulttracker.setBackground(Color.WHITE);
resulttracker.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
ResultTracker resulttracker = new ResultTracker(mf);
mf.setContentPane(resulttracker);
mf.setVisible(true);
}
});
academic.add(resulttracker);
JMenuItem studyplan = new JMenuItem("Study Planner");
studyplan.setForeground(Color.BLACK);
studyplan.setBackground(Color.WHITE);
studyplan.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
StudyPlanner studyplanner = new StudyPlanner(mf);
mf.setContentPane(studyplanner);
mf.setVisible(true);
}
});
academic.add(studyplan);
JMenuItem timetable = new JMenuItem("Timetable");
timetable.setForeground(Color.BLACK);
timetable.setBackground(Color.WHITE);
timetable.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
TimeTable timetable = new TimeTable(mf);
mf.setContentPane(timetable);
mf.setVisible(true);
}
});
academic.add(timetable);
JMenuBar menuBarEmail = new JMenuBar();
menuBarEmail.setForeground(Color.BLACK);
menuBarEmail.setBackground(Color.WHITE);
menuBarEmail.setBounds(320, 40, 97, 21);
menuBarEmail.setSize(47, 20);
add(menuBarEmail);
JMenu email = new JMenu("EMAIL");
menuBarEmail.add(email);
JMenuItem composeemail = new JMenuItem("Compose");
composeemail.setForeground(Color.BLACK);
composeemail.setBackground(Color.WHITE);
composeemail.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Email email = new Email(mf);
mf.setContentPane(email);
mf.setVisible(true);
}
});
email.add(composeemail);
JMenuItem inboxemail = new JMenuItem("Inbox");
inboxemail.setForeground(Color.BLACK);
inboxemail.setBackground(Color.WHITE);
email.add(inboxemail);
JMenuBar menuBarContactus = new JMenuBar();
menuBarContactus.setForeground(Color.BLACK);
menuBarContactus.setBackground(Color.WHITE);
menuBarContactus.setBounds(380, 40, 97, 21);
menuBarContactus.setSize(85, 20);
add(menuBarContactus);
JMenu contactus= new JMenu("CONTACT US");
contactus.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
ContactUs contactus = new ContactUs(mf);
mf.setContentPane(contactus);
mf.setVisible(true);
}
});
menuBarContactus.add(contactus);
JMenuBar menuBarLogout = new JMenuBar();
menuBarLogout.setForeground(Color.BLACK);
menuBarLogout.setBackground(Color.WHITE);
menuBarLogout.setBounds(480, 40, 97, 21);
menuBarLogout.setSize(60, 20);
add(menuBarLogout);
JMenu logout = new JMenu("LOGOUT");
logout.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
Login login = new Login(mf);
mf.setContentPane(login);
mf.setVisible(true);
}
});
menuBarLogout.add(logout);
JSeparator separatorTop = new JSeparator();
separatorTop.setBounds(50, 23, 524, 2);
add(separatorTop);
JSeparator separatorBottom = new JSeparator();
separatorBottom.setBounds(50, 79, 524, 2);
add(separatorBottom);
}
}
i write a convert temperature code using radiobutton, but when i use actionListener to print the value to a label, it show "Cannot refer to the non-final local variable valueto defined in an enclosing scope"
can some one show me the problem and how to fix it? (also sorry for my English)
the Radiobutton
JRadioButton Cbutton = new JRadioButton("Celsius");
Fbutton.setFont(new Font("Tahoma", Font.PLAIN, 12));
Fbutton.setBounds(10, 40, 109, 23);
contentPane.add(Cbutton);
JRadioButton Fbutton2 = new JRadioButton("Fahrenheit");
Fbutton2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
label.setText(String.valueOf(valueto));
}
});
i use this to convert
if(Fbutton.isSelected()&&Cbutton2.isSelected()){
value=F;
valueto=(F-32)/1.8;
}else if(Fbutton.isSelected()&&Kbutton2.isSelected()){
value=F;
valueto=(F+459.67)*5/9;
}else if(Cbutton.isSelected()&&Fbutton2.isSelected()){
value=C;
valueto=C*1.8+32;
}else if(Cbutton.isSelected()&&Kbutton2.isSelected()){
value=C;
valueto=C+273.15;
}else if(Kbutton.isSelected()&&Cbutton2.isSelected()){
value=K;
valueto=K-273.15;
}else if(Kbutton.isSelected()&&Fbutton2.isSelected()){
value=K;
valueto=K*9.5-459.67;
}
Edit : i declare valueto at the bottom of the class
double value = 0;
double valueto = 0;
double F = 0, C = 0, K = 0;
it ask me to add final to "double valueto", but when i add it the valueto in "if" become error
The Whole code
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class CtoKtoF extends JFrame {
private JPanel contentPane;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
CtoKtoF frame = new CtoKtoF();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
* #return
*/
public CtoKtoF() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 303);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
double value = 0 ;
double valueto = 0;
double F = 0, C = 0, K = 0;
Border border = LineBorder.createGrayLineBorder();//make border for Jlabel
final JLabel label = new JLabel("New label");
label.setFont(new Font("Tahoma", Font.PLAIN, 12));
label.setBounds(10, 228, 220, 22);
label.setBorder(border);
contentPane.add(label);
JLabel lblNewLabel = new JLabel("Convert from");
lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 12));
lblNewLabel.setBounds(10, 11, 92, 22);
contentPane.add(lblNewLabel);
JRadioButton Fbutton = new JRadioButton("Fahrenheit");
Fbutton.setFont(new Font("Tahoma", Font.PLAIN, 12));
Fbutton.setBounds(10, 40, 109, 23);
//Fbutton.setActionCommand("F");
contentPane.add(Fbutton);
JRadioButton Cbutton = new JRadioButton("Celcius");
Cbutton.setFont(new Font("Tahoma", Font.PLAIN, 12));
Cbutton.setBounds(121, 40, 109, 23);
//Cbutton.setActionCommand("C");
contentPane.add(Cbutton);
JRadioButton Kbutton = new JRadioButton("Kelvin");
Kbutton.setFont(new Font("Tahoma", Font.PLAIN, 12));
Kbutton.setBounds(232, 40, 109, 23);
//Kbutton.setActionCommand("K");
contentPane.add(Kbutton);
JLabel lblEnterNumericTemperature = new JLabel("Enter Numeric Temperature");
lblEnterNumericTemperature.setFont(new Font("Tahoma", Font.PLAIN, 12));
lblEnterNumericTemperature.setBounds(10, 70, 238, 22);
contentPane.add(lblEnterNumericTemperature);
textField = new JTextField();
textField.setFont(new Font("Tahoma", Font.PLAIN, 12));
textField.setBounds(10, 103, 220, 22);
textField.setText(String.valueOf(value));
contentPane.add(textField);
textField.setColumns(10);
JRadioButton Fbutton2 = new JRadioButton("Fahrenheit");
Fbutton2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
label.setText(String.valueOf(valueto));
}
});
Fbutton2.setFont(new Font("Tahoma", Font.PLAIN, 12));
Fbutton2.setBounds(10, 165, 109, 23);
//Fbutton2.setActionCommand("F2");
contentPane.add(Fbutton2);
JRadioButton Cbutton2 = new JRadioButton("Celcius");
Cbutton2.setFont(new Font("Tahoma", Font.PLAIN, 12));
Cbutton2.setBounds(121, 165, 109, 23);
//Cbutton2.setActionCommand("C2");
contentPane.add(Cbutton2);
JRadioButton Kbutton2 = new JRadioButton("Kelvin");
Kbutton2.setFont(new Font("Tahoma", Font.PLAIN, 12));
Kbutton2.setBounds(232, 165, 109, 23);
//Kbutton2.setActionCommand("K2");
contentPane.add(Kbutton2);
ButtonGroup group1 = new ButtonGroup();
group1.add(Fbutton);
group1.add(Kbutton);
group1.add(Cbutton);
ButtonGroup group2 = new ButtonGroup();
group2.add(Fbutton2);
group2.add(Cbutton2);
group2.add(Kbutton2);
/*Fbutton.addActionListener(this);
Cbutton.addActionListener(this);
Kbutton.addActionListener(this);
Fbutton2.addActionListener(this);
Cbutton2.addActionListener(this);
Kbutton2.addActionListener(this);*/
//boolean checked = Fbutton.getState();
JLabel lblConvertTo = new JLabel("Convert to");
lblConvertTo.setFont(new Font("Tahoma", Font.PLAIN, 12));
lblConvertTo.setBounds(10, 136, 92, 22);
contentPane.add(lblConvertTo);
JLabel lblComparableTemperatureIs = new JLabel("Comparable Temperature is");
lblComparableTemperatureIs.setFont(new Font("Tahoma", Font.PLAIN, 12));
lblComparableTemperatureIs.setBounds(10, 195, 238, 22);
contentPane.add(lblComparableTemperatureIs);
if(Fbutton.isSelected()&&Cbutton2.isSelected()){
value=F;
valueto=(F-32)/1.8;
}else if(Fbutton.isSelected()&&Kbutton2.isSelected()){
value=F;
valueto=(F+459.67)*5/9;
}else if(Cbutton.isSelected()&&Fbutton2.isSelected()){
value=C;
valueto=C*1.8+32;
}else if(Cbutton.isSelected()&&Kbutton2.isSelected()){
value=C;
valueto=C+273.15;
}else if(Kbutton.isSelected()&&Cbutton2.isSelected()){
value=K;
valueto=K-273.15;
}else if(Kbutton.isSelected()&&Fbutton2.isSelected()){
value=K;
valueto=K*9.5-459.67;
}
}
}
I am making a program for my friend. I ran into an error while trying to create a write and save text into a .txt file. I should note this is the first time I have ever created something in Java Swing.
The error is marked with an asterisk.
package com.laganstoop.me;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Scanner;
import java.awt.event.ActionEvent;
import java.awt.Color;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JCheckBox;
// Created by: Laganstoop (David L. Perez)
// Do Not Distribute!
public class Main implements ActionListener {
private JFrame frame;
public static String infoBox(String infoMessage, String titleBar)
{
JOptionPane.showMessageDialog(null, infoMessage, "" + titleBar, JOptionPane.INFORMATION_MESSAGE);
return "";
}
public static void errorMessage(String errorMessage, String titleBar)
{
JOptionPane.showMessageDialog(null, errorMessage, "" + titleBar, JOptionPane.INFORMATION_MESSAGE);
}
public static final int HEIGHT = 800;
public static final int WIDTH = 600;
public static final int nHEIGHT = 400;
public static final int nWIDTH = 300;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
private JTextField textField_4;
private JTextField textField_5;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main window = new Main();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Main() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setBackground(Color.LIGHT_GRAY);
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(HEIGHT, WIDTH);
JButton btnNewButton = new JButton("Click To Add New");
btnNewButton.setBounds(10, 11, 132, 23);
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (InstantiationException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
} catch (UnsupportedLookAndFeelException e1) {
e1.printStackTrace();
}
frame.getContentPane().setLayout(null);
frame.getContentPane().add(btnNewButton);
JPanel panel = new JPanel();
panel.setBounds(10, 11, 764, 181);
panel.setBackground(Color.WHITE);
panel.setForeground(Color.WHITE);
frame.getContentPane().add(panel);
panel.setLayout(null);
panel.hide();
JLabel lblName = new JLabel("Name:");
lblName.setFont(new Font("Yu Gothic", Font.BOLD, 13));
lblName.setBounds(10, 11, 46, 14);
panel.add(lblName);
JLabel lblDate = new JLabel("Date:");
lblDate.setFont(new Font("Yu Gothic", Font.BOLD, 13));
lblDate.setBounds(10, 36, 46, 14);
panel.add(lblDate);
JLabel lblLocation = new JLabel("Time:\r\n");
lblLocation.setFont(new Font("Yu Gothic", Font.BOLD, 13));
lblLocation.setBounds(10, 61, 60, 14);
panel.add(lblLocation);
JLabel lblLocation_1 = new JLabel("Location:");
lblLocation_1.setFont(new Font("Yu Gothic", Font.BOLD, 13));
lblLocation_1.setBounds(10, 86, 60, 14);
panel.add(lblLocation_1);
JLabel lblRe = new JLabel("Referee");
lblRe.setFont(new Font("Yu Gothic", Font.BOLD, 13));
lblRe.setBounds(10, 111, 60, 14);
panel.add(lblRe);
textField = new JTextField();
textField.setBounds(76, 8, 127, 20);
panel.add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setColumns(10);
textField_1.setBounds(76, 33, 127, 20);
panel.add(textField_1);
textField_2 = new JTextField();
textField_2.setColumns(10);
textField_2.setBounds(76, 58, 127, 20);
panel.add(textField_2);
textField_3 = new JTextField();
textField_3.setColumns(10);
textField_3.setBounds(76, 86, 127, 20);
panel.add(textField_3);
textField_4 = new JTextField();
textField_4.setColumns(10);
textField_4.setBounds(76, 108, 127, 20);
panel.add(textField_4);
JCheckBox checkBox = new JCheckBox("");
checkBox.setBounds(209, 7, 21, 23);
panel.add(checkBox);
JCheckBox checkBox_1 = new JCheckBox("");
checkBox_1.setBounds(209, 32, 21, 23);
panel.add(checkBox_1);
JCheckBox checkBox_2 = new JCheckBox("");
checkBox_2.setBounds(209, 57, 21, 23);
panel.add(checkBox_2);
JCheckBox checkBox_3 = new JCheckBox("");
checkBox_3.setBounds(209, 82, 21, 23);
panel.add(checkBox_3);
JCheckBox checkBox_4 = new JCheckBox("");
checkBox_4.setBounds(209, 107, 21, 23);
panel.add(checkBox_4);
JPanel panel_2 = new JPanel();
panel_2.setBounds(20, 290, 358, 210);
panel_2.setLayout(null);
JButton btnNewNote = new JButton("New Note");
btnNewNote.setFont(new Font("Yu Gothic", Font.BOLD, 16));
btnNewNote.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFrame noteFrame = new JFrame();
noteFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
noteFrame.setLocationRelativeTo(panel);
noteFrame.pack();
noteFrame.setSize(nHEIGHT, nWIDTH);
noteFrame.getContentPane().add(panel_2);
noteFrame.setVisible(true);
}
});
btnNewNote.setBounds(293, 16, 461, 151);
panel.add(btnNewNote);
JLabel lblNotes = new JLabel("Notes:");
lblNotes.setBounds(10, 0, 46, 23);
panel_2.add(lblNotes);
lblNotes.setFont(new Font("Yu Gothic", Font.BOLD, 13));
JButton btnSaveCreate = new JButton("Create & Save");
btnSaveCreate.setBounds(237, 177, 131, 23);
panel_2.add(btnSaveCreate);
JCheckBox checkBox_5 = new JCheckBox("");
checkBox_5.setBounds(210, 177, 21, 23);
panel_2.add(checkBox_5);
btnSaveCreate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String NAME = textField.getText();
String DATE = textField_1.getText();
String TIME = textField_2.getText();
String LOCATION = textField_3.getText();
String Referee = textField_4.getText();
if(checkBox.isSelected() && checkBox_1.isSelected() && checkBox_2.isSelected() && checkBox_2.isSelected() && checkBox_3.isSelected() && checkBox_4.isSelected() && checkBox_5.isSelected())
{
infoBox("Met with " + NAME + " on " + DATE + " #" + TIME + ", and went to " + LOCATION + ", then I was introduced by " + Referee, "Paragraph");
}
else {
errorMessage("Error: Please validate entries!", "Error!");
}
}
});
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
btnNewButton.hide();
panel.setVisible(true);
}
});
try {
String content = textField_5.getText();
File file = new File("/users/David/filename.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content); //step2: write it
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace(); **** *****
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
Any Help is greatly appreciated!
You just forgot to add the } in this statement:
catch (IOException e) {
e.printStackTrace();
}
Just as Andrew Thompson said: simple indentation would have made this error a lot easier to spot if done properly, and should be used as common practice.
I created a database in xml and I want to create a register form in Jframe to add object to the db. So I build up the code, but every time I click the button Registra, it overwrites me that file. How can I keep the file and simply add elements without deleting the others? Here's the code:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.*;
import java.text.Format;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
public class Registrati extends JFrame {
private JPanel contentPane;
private static JTextField textField;
private static JTextField textField_1;
private static JTextField textField_2;
private static JTextField textField_3;
private static JTextField textField_4;
private static JTextField textField_5;
private static JTextField textField_6;
private static JPasswordField passwordField;
private static JTextField textField_7;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Registrati frame = new Registrati();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Registrati() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 463, 460);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblInserisciITuoi = new JLabel("Inserisci i tuoi dati per registrarti");
lblInserisciITuoi.setFont(new Font("Tahoma", Font.PLAIN, 12));
lblInserisciITuoi.setBounds(156, 23, 215, 14);
contentPane.add(lblInserisciITuoi);
JLabel lblNome = new JLabel("Nome");
lblNome.setFont(new Font("Tahoma", Font.PLAIN, 12));
lblNome.setBounds(38, 58, 46, 14);
contentPane.add(lblNome);
textField = new JTextField();
textField.setBounds(127, 56, 229, 20);
contentPane.add(textField);
textField.setColumns(10);
JLabel lblCognome = new JLabel("Cognome");
lblCognome.setFont(new Font("Tahoma", Font.PLAIN, 12));
lblCognome.setBounds(38, 89, 64, 14);
contentPane.add(lblCognome);
textField_1 = new JTextField();
textField_1.setColumns(10);
textField_1.setBounds(127, 87, 229, 20);
contentPane.add(textField_1);
JLabel lblDataDiNascita = new JLabel("Data di Nascita");
lblDataDiNascita.setFont(new Font("Tahoma", Font.PLAIN, 12));
lblDataDiNascita.setBounds(38, 120, 98, 14);
contentPane.add(lblDataDiNascita);
textField_2 = new JTextField();
textField_2.setColumns(10);
textField_2.setBounds(127, 118, 229, 20);
contentPane.add(textField_2);
JLabel lblAltezza = new JLabel("Altezza");
lblAltezza.setFont(new Font("Tahoma", Font.PLAIN, 12));
lblAltezza.setBounds(38, 171, 64, 14);
contentPane.add(lblAltezza);
textField_3 = new JTextField();
textField_3.setColumns(10);
textField_3.setBounds(127, 169, 229, 20);
contentPane.add(textField_3);
textField_4 = new JTextField();
textField_4.setColumns(10);
textField_4.setBounds(127, 200, 229, 20);
contentPane.add(textField_4);
JLabel lblPeso = new JLabel("Peso");
lblPeso.setFont(new Font("Tahoma", Font.PLAIN, 12));
lblPeso.setBounds(38, 203, 46, 14);
contentPane.add(lblPeso);
JLabel lblSesso = new JLabel("Sesso");
lblSesso.setFont(new Font("Tahoma", Font.PLAIN, 12));
lblSesso.setBounds(38, 233, 46, 14);
contentPane.add(lblSesso);
textField_5 = new JTextField();
textField_5.setColumns(10);
textField_5.setBounds(127, 231, 229, 20);
contentPane.add(textField_5);
JLabel lblEmail = new JLabel("email");
lblEmail.setFont(new Font("Tahoma", Font.PLAIN, 12));
lblEmail.setBounds(38, 283, 46, 14);
contentPane.add(lblEmail);
textField_6 = new JTextField();
textField_6.setColumns(10);
textField_6.setBounds(127, 281, 229, 20);
contentPane.add(textField_6);
JLabel lblPassword = new JLabel("Password");
lblPassword.setFont(new Font("Tahoma", Font.PLAIN, 12));
lblPassword.setBounds(38, 343, 64, 14);
contentPane.add(lblPassword);
passwordField = new JPasswordField();
passwordField.setBounds(127, 341, 229, 20);
contentPane.add(passwordField);
textField_7 = new JTextField();
textField_7.setColumns(10);
textField_7.setBounds(127, 312, 229, 20);
contentPane.add(textField_7);
JLabel lblUsername = new JLabel("Username");
lblUsername.setFont(new Font("Tahoma", Font.PLAIN, 12));
lblUsername.setBounds(38, 314, 64, 14);
contentPane.add(lblUsername);
JButton btnRegistrami = new JButton("Registrami");
btnRegistrami.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Atleta atleta= new Atleta();
try {
Writer(atleta);
} catch (JDOMException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btnRegistrami.setBounds(186, 387, 110, 23);
contentPane.add(btnRegistrami);
}
public static void Writer(Atleta atleta) throws JDOMException, IOException {
Document document = null;
Element root = null;
File xmlFile = new File("db.xml");
if(xmlFile.exists()) {
// try to load document from xml file if it exist
// create a file input stream
FileInputStream fis = new FileInputStream(xmlFile);
// create a sax builder to parse the document
SAXBuilder sb = new SAXBuilder();
// parse the xml content provided by the file input stream and create a Document object
document = sb.build(fis);
// get the root element of the document
root = document.getRootElement();
fis.close();
} else {
// if it does not exist create a new document and new root
document = new Document();
root = new Element("Ercole");
}
String nome = textField.getText();
String cognome = textField_1.getText();
#SuppressWarnings("deprecation")
String password = passwordField.getText();
String username = textField_7.getText();
String email = textField_6.getText();
String nascita = textField_2.getText();
String peso = textField_4.getText();
String sesso = textField_5.getText();
String altezza = textField_3.getText();
Element child = new Element("Atleta");
child.addContent(new Element("Password").setText(password));
child.addContent(new Element("Username").setText(username));
child.addContent(new Element("email").setText(email));
child.addContent(new Element("Nome").setText(nome));
child.addContent(new Element("Cognome").setText(cognome));
child.addContent(new Element("ID").setText("da modificare!"));
child.addContent(new Element("Nascita").setText(nascita));
child.addContent(new Element("Peso").setText(peso));
child.addContent(new Element("Sesso").setText(sesso));
child.addContent(new Element("Altezza").setText(altezza));
root.addContent(child);
document.setContent(root);
try {
FileWriter writer = new FileWriter("c:\\db.xml");
XMLOutputter outputter = new XMLOutputter();
//outputter.setFormat(Format.getPrettyFormat());
outputter.output(document, writer);
outputter.output(document, System.out);
writer.close(); // close writer
} catch (IOException e) {
e.printStackTrace();
}
}
}
I think the file you are reading is not the file you are writing
You read "db.xml"
You write "c:\\db.xml"
The first one probably never exists, so it has no content to append your new registration to, so you just end up writing your new registration to the c:\db.xml file