Transferring of data from one JPanel to another - java

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);
}
}

Related

popup JTable when key pressed to Search

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);
}
}

how should i navigate from one window that uses an application window to another frame in another application window?

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);
}
});
}
}
}

JDialog shows empty

I was trying to replace the use of JOptionPane by a new custom dialog here is what I did:
package pk;
import java.util.Enumeration;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import java.awt.Font;
import javax.swing.JTextArea;
import java.awt.SystemColor;
import javax.swing.JPanel;
import java.awt.Color;
import javax.swing.border.LineBorder;
public class SIMessage extends JDialog implements ActionListener{
private static final long serialVersionUID = 1L;
public JButton oui=new JButton("Oui"),btnClose=new JButton(new ImageIcon("images\\logo\\delete.gif")),
non=new JButton("Non"),annuler=new JButton("Annuler"),ok=new JButton("OK");
public JLabel lblImgErr=new JLabel(new ImageIcon("images\\logo\\msgErreur.png")),
lblImgConf=new JLabel(new ImageIcon("images\\logo\\msgQuestion.png")),
lblImgWarning=new JLabel(new ImageIcon("images\\logo\\msgWarning.png")),
lblImgInfo=new JLabel(new ImageIcon("images\\logo\\msgInformation.png")),
lblImgQuestion=new JLabel(new ImageIcon("images\\logo\\msgQuestion.png")),
lblImgIconApp=new JLabel(new ImageIcon("images\\logo\\clntIco.ico"));
public JLabel title=new JLabel(),message=new JLabel();
public enum TypeMessage{
ERROR_MESSAGE,
CONFIRMATION_MESSAGE,
WARNING_MESSAGE,
INFORMATION_MESSAGE,
VALIDATION_MESSAGE
}
public SIMessage(JFrame parent,String title,TypeMessage type,String message) {
super(parent,true);
setUndecorated(true);
getContentPane().setLayout(new GridLayout(1, 1));
JPanel mainDgPanel = new JPanel();
mainDgPanel.setBorder(new LineBorder(new Color(255, 255, 255), 3, true));
mainDgPanel.setBounds(0, 0, 444, 156);
getContentPane().add(mainDgPanel);
mainDgPanel.setLayout(null);
mainDgPanel.setBackground(Color.decode(EcranPrincipal.blueThemeCP));
JTextArea txtrTextarea = new JTextArea(message);
txtrTextarea.setRows(2);
txtrTextarea.setBounds(123, 62, 340, 80);
txtrTextarea.setFont(new Font("Iskoola Pota", Font.PLAIN, 18));
txtrTextarea.setEditable(false);
txtrTextarea.setFocusable(false);
txtrTextarea.setOpaque(false);
txtrTextarea.setBorder(null);
txtrTextarea.setWrapStyleWord(true);
txtrTextarea.setLineWrap(true);
txtrTextarea.setForeground(Color.decode(EcranPrincipal.blueThemeBT));
mainDgPanel.add(txtrTextarea);
JPanel panelButtons = new JPanel();
panelButtons.setBounds(47, 115, 344, 30);
mainDgPanel.add(panelButtons);
switch(type)
{
case ERROR_MESSAGE:
{
JLabel lblNewLabel =lblImgErr;
lblNewLabel.setBounds(10, 69, 79, 14);
mainDgPanel.add(lblNewLabel);
JButton btnOk = ok;
panelButtons.add(btnOk);
break;
}
case CONFIRMATION_MESSAGE:
{
JLabel lblNewLabel =lblImgConf;
lblNewLabel.setBounds(10, 69, 79, 14);
mainDgPanel.add(lblNewLabel);
JButton btnOui = oui;
panelButtons.add(btnOui);
break;
}
case WARNING_MESSAGE:
{
JLabel lblNewLabel =lblImgWarning;
lblNewLabel.setBounds(10, 69, 79, 14);
mainDgPanel.add(lblNewLabel);
JButton btnOk = ok;
panelButtons.add(btnOk);
break;
}
case INFORMATION_MESSAGE:
{
JLabel lblNewLabel =lblImgInfo;
lblNewLabel.setBounds(10, 69, 79, 14);
mainDgPanel.add(lblNewLabel);
JButton btnOk = ok;
panelButtons.add(btnOk);
break;
}
case VALIDATION_MESSAGE:
{
JLabel lblNewLabel =lblImgConf;
lblNewLabel.setBounds(10, 69, 79, 14);
mainDgPanel.add(lblNewLabel);
JButton btnOui = oui;
panelButtons.add(btnOui);
JButton btnNon = non;
panelButtons.add(btnNon);
JButton btnAnnuler = annuler;
panelButtons.add(btnAnnuler);
break;
}
default:
}
ok.addActionListener(this);
oui.addActionListener(this);
JPanel panel = new JPanel();
panel.setBounds(0, 0, 444, 27);
mainDgPanel.add(panel);
panel.setBackground(Color.WHITE);
panel.setLayout(null);
JButton btnCloseDf = btnClose;
btnCloseDf.setBounds(411, 0, 39, 23);
panel.add(btnCloseDf);
JLabel lblIconApp =lblImgIconApp;
lblIconApp.setBounds(10, 4, 77, 14);
panel.add(lblIconApp);
JLabel lblTitle = new JLabel(title);
lblTitle.setBounds(190, 4, 46, 14);
panel.add(lblTitle);
this.pack();
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Object source=e.getSource();
if(source==oui||source==ok)
{
this.dispose();
}
}
Then I call:
SIMessage sm=new SIMessage(this, "Attention", SIMessage.TypeMessage.WARNING_MESSAGE,"You need to change ...");
callMethode2();
The problem is that it executes the call to Methode2 before showing any dialog while it is supposed to force the user to respond before continuing.
I see an empty window side by side with the window generated by callMethod2!, so what is wrong?
You should set the modality for Dialog.
A modal window is a graphical control element subordinate to an application's main window. It creates a mode that disables the main window but keeps it visible with the modal window as a child window in front of it. Users must interact with the modal window before they can return to the parent application.
So, Set the modal flag of the dialog when initializing it.
setModal(True)
edit:
I don't know what you exactly changed in your code, but the code below works fine for me:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author Emad
*/
import java.awt.BorderLayout;
import java.util.Enumeration;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import java.awt.Font;
import javax.swing.JTextArea;
import java.awt.SystemColor;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import javafx.event.ActionEvent;
import javax.swing.border.LineBorder;
public class SIMessage extends JDialog implements ActionListener {
private static final long serialVersionUID = 1L;
public JButton oui = new JButton("Oui"), btnClose = new JButton(new ImageIcon("images\\logo\\delete.gif")),
non = new JButton("Non"), annuler = new JButton("Annuler"), ok = new JButton("OK");
public JLabel lblImgErr = new JLabel(new ImageIcon("images\\logo\\msgErreur.png")),
lblImgConf = new JLabel(new ImageIcon("images\\logo\\msgQuestion.png")),
lblImgWarning = new JLabel(new ImageIcon("images\\logo\\msgWarning.png")),
lblImgInfo = new JLabel(new ImageIcon("images\\logo\\msgInformation.png")),
lblImgQuestion = new JLabel(new ImageIcon("images\\logo\\msgQuestion.png")),
lblImgIconApp = new JLabel(new ImageIcon("images\\logo\\clntIco.ico"));
public JLabel title = new JLabel(), message = new JLabel();
#Override
public void actionPerformed(java.awt.event.ActionEvent e) {
// TODO Auto-generated method stub
Object source = e.getSource();
if (source == oui || source == ok) {
this.dispose();
}
}
public enum TypeMessage {
ERROR_MESSAGE,
CONFIRMATION_MESSAGE,
WARNING_MESSAGE,
INFORMATION_MESSAGE,
VALIDATION_MESSAGE
}
public SIMessage(JFrame parent, String title, TypeMessage type, String message) {
super(parent, true);
setUndecorated(true);
getContentPane().setLayout(new GridLayout(1, 1));
JPanel mainDgPanel = new JPanel();
mainDgPanel.setBorder(new LineBorder(new Color(255, 255, 255), 3, true));
mainDgPanel.setBounds(0, 0, 444, 156);
getContentPane().add(mainDgPanel);
// mainDgPanel.setBackground(Color.decode(EcranPrincipal.blueThemeCP));
JTextArea txtrTextarea = new JTextArea(message);
txtrTextarea.setRows(2);
txtrTextarea.setBounds(123, 62, 340, 80);
txtrTextarea.setFont(new Font("Iskoola Pota", Font.PLAIN, 18));
txtrTextarea.setEditable(false);
txtrTextarea.setFocusable(false);
txtrTextarea.setOpaque(false);
txtrTextarea.setBorder(null);
txtrTextarea.setWrapStyleWord(true);
txtrTextarea.setLineWrap(true);
// txtrTextarea.setForeground(Color.decode(EcranPrincipal.blueThemeBT));
mainDgPanel.add(txtrTextarea);
JPanel panelButtons = new JPanel();
panelButtons.setBounds(47, 115, 344, 30);
mainDgPanel.add(panelButtons);
switch (type) {
case ERROR_MESSAGE: {
JLabel lblNewLabel = lblImgErr;
lblNewLabel.setBounds(10, 69, 79, 14);
mainDgPanel.add(lblNewLabel);
JButton btnOk = ok;
panelButtons.add(btnOk);
break;
}
case CONFIRMATION_MESSAGE: {
JLabel lblNewLabel = lblImgConf;
lblNewLabel.setBounds(10, 69, 79, 14);
mainDgPanel.add(lblNewLabel);
JButton btnOui = oui;
panelButtons.add(btnOui);
break;
}
case WARNING_MESSAGE: {
JLabel lblNewLabel = lblImgWarning;
lblNewLabel.setBounds(10, 69, 79, 14);
mainDgPanel.add(lblNewLabel);
JButton btnOk = ok;
panelButtons.add(btnOk);
break;
}
case INFORMATION_MESSAGE: {
JLabel lblNewLabel = lblImgInfo;
lblNewLabel.setBounds(10, 69, 79, 14);
mainDgPanel.add(lblNewLabel);
JButton btnOk = ok;
panelButtons.add(btnOk);
break;
}
case VALIDATION_MESSAGE: {
JLabel lblNewLabel = lblImgConf;
lblNewLabel.setBounds(10, 69, 79, 14);
mainDgPanel.add(lblNewLabel);
JButton btnOui = oui;
panelButtons.add(btnOui);
JButton btnNon = non;
panelButtons.add(btnNon);
JButton btnAnnuler = annuler;
panelButtons.add(btnAnnuler);
break;
}
default:
}
ok.addActionListener(this);
oui.addActionListener(this);
JPanel panel = new JPanel();
panel.setBounds(0, 0, 444, 27);
mainDgPanel.add(panel);
panel.setBackground(Color.WHITE);
panel.setLayout(null);
JButton btnCloseDf = btnClose;
btnCloseDf.setBounds(411, 0, 39, 23);
panel.add(btnCloseDf);
JLabel lblIconApp = lblImgIconApp;
lblIconApp.setBounds(10, 4, 77, 14);
panel.add(lblIconApp);
JLabel lblTitle = new JLabel(title);
lblTitle.setBounds(190, 4, 46, 14);
panel.add(lblTitle);
this.pack();
this.setVisible(true);
}
public static void main(String[] args)
{
SIMessage sm=new SIMessage(null, "Attention", SIMessage.TypeMessage.WARNING_MESSAGE,"You need to change ...");
System.out.println("hello");
}
}

How to Update JFrame Components?

Well, i have this code.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import javax.swing.SwingConstants;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import java.awt.Font;
import javax.swing.JSeparator;
import javax.swing.JTextPane;
import javax.swing.JButton;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Menu {
private JFrame frmFelps;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Menu window = new Menu();
window.frmFelps.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Menu() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
Funcoes acoes = new Funcoes();
frmFelps = new JFrame();
frmFelps.setResizable(false);
frmFelps.setTitle("Felps");
frmFelps.setBounds(100, 100, 824, 522);
frmFelps.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmFelps.getContentPane().setLayout(null);
JProgressBar progressoSede = new JProgressBar();
progressoSede.setStringPainted(true);
progressoSede.setValue(acoes.getSede());
progressoSede.setBounds(71, 25, 100, 25);
frmFelps.getContentPane().add(progressoSede);
JProgressBar progressoAmor = new JProgressBar();
progressoAmor.setValue(acoes.getAmor());
progressoAmor.setStringPainted(true);
progressoAmor.setBounds(71, 56, 100, 25);
frmFelps.getContentPane().add(progressoAmor);
JProgressBar progressoFeliz = new JProgressBar();
progressoFeliz.setValue(acoes.getFeliz());
progressoFeliz.setStringPainted(true);
progressoFeliz.setBounds(71, 85, 100, 25);
frmFelps.getContentPane().add(progressoFeliz);
JLabel lblSede = new JLabel("Sede:");
lblSede.setToolTipText("Porcentagem de AQUA que voc\u00EA bebeu e gravou nos ultimos tempos.");
lblSede.setFont(new Font("Arial", Font.PLAIN, 16));
lblSede.setBounds(24, 25, 46, 23);
frmFelps.getContentPane().add(lblSede);
JLabel lblAmor = new JLabel("Amor:");
lblAmor.setToolTipText("O Amor n\u00E3o precisa ser descrito com palavras.");
lblAmor.setFont(new Font("Arial", Font.PLAIN, 16));
lblAmor.setBounds(24, 56, 46, 23);
frmFelps.getContentPane().add(lblAmor);
JLabel lblFeliz = new JLabel("Feliz:");
lblFeliz.setToolTipText("Um Felps Feliz \u00E9 um Felps que n\u00E3o esta Triste.");
lblFeliz.setFont(new Font("Arial", Font.PLAIN, 16));
lblFeliz.setBounds(24, 85, 46, 23);
frmFelps.getContentPane().add(lblFeliz);
JLabel lblCamera = new JLabel("Camera:");
lblCamera.setToolTipText("Quanto melhor a Camera mais Video com FaceCam o Felps Faz");
lblCamera.setBounds(24, 168, 74, 14);
frmFelps.getContentPane().add(lblCamera);
JLabel lblPc = new JLabel("PC:");
lblPc.setToolTipText("Quanto melhor seu PC mais o Cellbits vai sentir inveja de voc\u00EA.");
lblPc.setBounds(24, 199, 74, 14);
frmFelps.getContentPane().add(lblPc);
JLabel lblFone = new JLabel("Fone:");
lblFone.setToolTipText("Hey Galera Felps falando e bem vindos ao meu canal.");
lblFone.setBounds(24, 230, 74, 14);
frmFelps.getContentPane().add(lblFone);
JLabel lblInscritos = new JLabel("Inscritos:");
lblInscritos.setToolTipText("Quanto mais melhor. (P.S.: Eles s\u00F3 v\u00E3o te amar se voc\u00EA amar eles)");
lblInscritos.setBounds(50, 290, 83, 14);
frmFelps.getContentPane().add(lblInscritos);
JLabel lblDinheiros = new JLabel("Dinheiros:");
lblDinheiros.setToolTipText("Quantos dinheiros existem dentro do seu bolso Felpastico.");
lblDinheiros.setBounds(10, 432, 60, 14);
frmFelps.getContentPane().add(lblDinheiros);
JTextPane txtpnCamera = new JTextPane();
txtpnCamera.setEditable(false);
txtpnCamera.setText(acoes.getCamera());
txtpnCamera.setBounds(108, 162, 104, 20);
frmFelps.getContentPane().add(txtpnCamera);
JTextPane txtpnPc = new JTextPane();
txtpnPc.setText(acoes.getPc());
txtpnPc.setEditable(false);
txtpnPc.setBounds(108, 193, 104, 20);
frmFelps.getContentPane().add(txtpnPc);
JTextPane txtpnFone = new JTextPane();
txtpnFone.setText(acoes.getFone());
txtpnFone.setEditable(false);
txtpnFone.setBounds(108, 224, 104, 20);
frmFelps.getContentPane().add(txtpnFone);
JTextPane txtpnInscrito = new JTextPane();
txtpnInscrito.setEditable(false);
txtpnInscrito.setText(acoes.getInscritos());
txtpnInscrito.setBounds(24, 315, 130, 20);
frmFelps.getContentPane().add(txtpnInscrito);
JTextPane txtpnDinheiro = new JTextPane();
txtpnDinheiro.setText(acoes.getDinheiro());
txtpnDinheiro.setEditable(false);
txtpnDinheiro.setBounds(80, 426, 91, 20);
frmFelps.getContentPane().add(txtpnDinheiro);
JButton btnYoutube = new JButton("YouTube");
btnYoutube.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
//TODO Fazer Algo
}
});
JSeparator separator = new JSeparator();
separator.setOrientation(SwingConstants.VERTICAL);
separator.setBounds(228, 0, 13, 493);
frmFelps.getContentPane().add(separator);
btnYoutube.setBounds(534, 172, 146, 25);
frmFelps.getContentPane().add(btnYoutube);
JButton btnCasa = new JButton("Casa");
btnCasa.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
//TODO Fazer Algo
acoes.setInscritos(10);
//txtpnInscrito.setText(acoes.getInscritos());
atualizador();
//txtpnInscrito.setText(acoes.getInscritos());
}
});
btnCasa.setBounds(268, 171, 146, 25);
frmFelps.getContentPane().add(btnCasa);
JButton btnCidade = new JButton("Cidade");
btnCidade.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
//TODO Fazer Algo
}
});
btnCidade.setBounds(268, 264, 146, 25);
frmFelps.getContentPane().add(btnCidade);
JButton btnBica = new JButton("Bica");
btnBica.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
//TODO Fazer Algo
}
});
btnBica.setBounds(534, 265, 146, 25);
frmFelps.getContentPane().add(btnBica);
JLabel lblFundo = new JLabel("New label");
lblFundo.setIcon(new ImageIcon("img\\mapa.png"));
lblFundo.setBounds(251, 20, 528, 435);
frmFelps.getContentPane().add(lblFundo);
}
private void atualizador(){
//TODO
}
}
I want to change the text on txtpnInscrito every time that atualizador() runs
But i don't know how to do this.
If i change the text directly in the button btnCasa it changes, but i want to make a refresher by time and utilize the same function to refresh when doing actions on buttons.
Thanks in advance.
And sorry for the horrible english.
You need to make txtpnInscrito field of the class so that it's accessible in all your methods within your class
Have a look at Understanding Class Members for more details

Toggle Java JPanels - each panel deifferent class

I'm a beginer in Java GUI, and i have an issue with trying to toggle between panel in other class.
My main Class "MyBoxGUI" has 2 Panels, "Login" and "UserMenu"
The default is "Login" panel, when pressing "OK" the window moved to "UserMenu" Panel.
So far so good while in the same class.
The issue is, when i set a new panel in new class and setvisibe that panel, i can't go back to "UserMenu" panel - (The actionlistener is working fine).
Can someone help me please?
MyBoxGUI Class
package main;
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.CardLayout;
import java.awt.Component;
//import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.Color;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import java.awt.Toolkit;
import GUIs.*;
//import ocsf.client.*;
public class MyBoxGUI extends JPanel
{
private Mtds mtd;
public JFrame frmMybox;
private static JTextField UserName;
private static JTextField port;
private static JTextField IP;
private static JPasswordField passwordField;
public final JPanel Login = new JPanel();
public final JPanel UserMenu = new JPanel();
/**
* Launch the application.
*/
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
MyBoxGUI window = new MyBoxGUI();
window.frmMybox.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MyBoxGUI()
{
mtd = new Mtds();
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize()
{
frmMybox = new JFrame();
frmMybox.setFont(new Font("Tempus Sans ITC", Font.BOLD, 15));
// frmMybox.setIconImage(Toolkit.getDefaultToolkit().getImage(MyBoxGUI.class.getResource("/images/gift-ideas-gift-card-bridal-gift-baby-shower-gift-gift-box-groom-gift-christmas-gift-party-gift-gift-for-wedding-friend-gift-birthday-gift-baby-gift-good-gift-box-ideas-for-friend-necklace-gift-box.jpg")));
frmMybox.setBounds(100, 100, 800, 500);
frmMybox.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmMybox.getContentPane().setLayout(new CardLayout(0, 0));
frmMybox.setTitle("MyBox");
frmMybox.getContentPane().add(Login);
Login.setLayout(null);
JButton btnNewButton = new JButton("OK");
btnNewButton.addActionListener(new ActionListener()
{
#SuppressWarnings("deprecation")
public void actionPerformed(ActionEvent arg0)
{
Boolean ok = false;
String UName, Pass, Prt, SIP;
UName = UserName.getText();
Pass = passwordField.getText();
Prt = port.getText();
SIP = IP.getText();
if( ( mtd.isUserValid(UName) && mtd.isPasswordValid(Pass) && mtd.isPortValid(Prt) && mtd.isIPValid(SIP))
&& ( !UName.equals("") && !Pass.equals("") && !Prt.equals("") && !SIP.equals("") ) )
ok = true;
else
{
if(!mtd.isUserValid(UName) || UName.equals(""))
JOptionPane.showMessageDialog(frmMybox,"User Name Can Contain Only The Following Characters: ( 0-9 , a-z , A-Z , _ )"
+ " ","Invalid characters",JOptionPane.WARNING_MESSAGE);
else if(!mtd.isPasswordValid(Pass) || Pass.equals(""))
JOptionPane.showMessageDialog(frmMybox,"Invalid characters","Error Message",JOptionPane.WARNING_MESSAGE);
else if(!mtd.isPortValid(Prt) || Prt.equals(""))
JOptionPane.showMessageDialog(frmMybox,"Port Can Contain Only Numbers","Invalid characters",JOptionPane.WARNING_MESSAGE);
else if(!mtd.isIPValid(SIP) || SIP.equals(""))
JOptionPane.showMessageDialog(frmMybox,"IP Address Can Contain Only Numbers seperated By Dots '.' ","Invalid characters",JOptionPane.WARNING_MESSAGE);
}
if(ok)
{
//LoginController user = new LoginController();
//chat= new ClientGUI(IP.getText(),port.getText());
//client = ClientGUI.getClient();
//msg=new Msg("login",user);
//client.handleMessageFromClientUI(msg);
setScreen(Login,UserMenu);
// frmMybox.getContentPane().add(UserMenu, "UserMenu");
// UserMenu.setVisible(true);
// Login.setVisible(false);
}
}
});
btnNewButton.setBounds(344, 313, 82, 48);
Login.add(btnNewButton);
JLabel lblWellcomeToMybox = new JLabel("Wellcome to MyBox");
lblWellcomeToMybox.setForeground(new Color(51, 204, 255));
lblWellcomeToMybox.setFont(new Font("Arial", Font.PLAIN, 36));
lblWellcomeToMybox.setBounds(224, 23, 327, 42);
Login.add(lblWellcomeToMybox);
JLabel lblUserName = new JLabel("User Name:");
lblUserName.setBounds(268, 109, 89, 14);
lblUserName.setFont(new Font("Arial", Font.PLAIN, 14));
Login.add(lblUserName);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setBounds(268, 139, 69, 14);
lblPassword.setFont(new Font("Arial", Font.PLAIN, 14));
Login.add(lblPassword);
JLabel lblServerPort = new JLabel("Server port:");
lblServerPort.setBounds(268, 197, 82, 14);
lblServerPort.setFont(new Font("Arial", Font.PLAIN, 14));
Login.add(lblServerPort);
JLabel lblServerIp = new JLabel("Server IP:");
lblServerIp.setBounds(266, 222, 71, 14);
lblServerIp.setFont(new Font("Arial", Font.PLAIN, 14));
Login.add(lblServerIp);
UserName = new JTextField();
UserName.setBounds(406, 107, 96, 20);
Login.add(UserName);
UserName.setColumns(10);
port = new JTextField();
port.setBounds(406, 195, 96, 20);
Login.add(port);
port.setColumns(10);
IP = new JTextField();
IP.setBounds(406, 220, 96, 20);
Login.add(IP);
IP.setColumns(10);
passwordField = new JPasswordField();
passwordField.setBounds(406, 137, 96, 20);
Login.add(passwordField);
frmMybox.getContentPane().add(UserMenu, "User Menu");
UserMenu.setLayout(null);
JButton LeaveGOI = new JButton("Back");
LeaveGOI.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
setScreen(UserMenu,Login);
}
});
LeaveGOI.setBounds(10, 66, 153, 23);
UserMenu.add(LeaveGOI);
JButton btnJoinAGoi = new JButton("Join a GOI");
btnJoinAGoi.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
}
});
btnJoinAGoi.setBounds(10, 100, 153, 23);
UserMenu.add(btnJoinAGoi);
JButton btnSearchForA = new JButton("Search for a GOI");
btnSearchForA.setBounds(10, 134, 153, 23);
UserMenu.add(btnSearchForA);
JButton btnCreateAGoi = new JButton("Create a GOI");
btnCreateAGoi.setBounds(10, 32, 153, 23);
UserMenu.add(btnCreateAGoi);
JButton btnFilesSharedWith = new JButton("Files shared with you");
btnFilesSharedWith.setBounds(271, 66, 153, 23);
UserMenu.add(btnFilesSharedWith);
JButton btnUploadAFile = new JButton("Upload a file");
btnUploadAFile.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
JPanel UpLoad = new UploadFile();
setScreen(UserMenu,UpLoad);
// frmMybox.getContentPane().add(UpLoad, "UpLoad");
// UserMenu.setVisible(false);
// UpLoad.setVisible(true);
}
});
btnUploadAFile.setBounds(271, 32, 153, 23);
UserMenu.add(btnUploadAFile);
JButton btnSignout = new JButton("Sign-Out");
btnSignout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int dialog=JOptionPane.showConfirmDialog(Login, getUserName()+", are you sure you wants to leave?", "Do you want to leave?", JOptionPane.YES_NO_OPTION);
if(dialog==0){
//client.quit();
}
}
});
btnSignout.setBounds(293, 227, 131, 23);
UserMenu.add(btnSignout);
JButton btnHelpme = new JButton("Help-Me");
btnHelpme.addActionListener(new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
JOptionPane.showMessageDialog(Login,"Hello "+ getUserName()+", wellcom to Mybox!\n"
+ "Inside GOIs buttons you can ask to join, leave and even create a GOI.\n"
+ "Inside Files buttons you can check and edit files people shared with you.\n"
+ "You can even become an uploader and share files you own.\n"
+ "We wish you good luck and have fun using MyBox!");
}
});
btnHelpme.setBounds(10, 227, 131, 23);
UserMenu.add(btnHelpme);
}
public static String getUserName(){
return UserName.getText();
}
#SuppressWarnings("deprecation")
public static String getPassword(){
return passwordField.getText();
}
public static String getIP(){
return IP.getText();
}
public static String getPort(){
return port.getText();
}
public void setScreen(JPanel fls, JPanel tru)
{
frmMybox.getContentPane().add(tru);
tru.setVisible(true);
fls.setVisible(false);
}
}
UploadFile Class
package GUIs;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import main.MyBoxGUI;
public class UploadFile extends MyBoxGUI {
private JTextField textField;
/**
* Create the panel.
*/
public static final JPanel UpLoad = new JPanel();
public UploadFile()
{
setBounds(100, 100, 800, 500);
setLayout(null);
JButton btnNewButton = new JButton("Back");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
setScreen(UpLoad,UserMenu);
System.out.print("A+++");
}
});
btnNewButton.setBounds(126, 145, 205, 30);
add(btnNewButton);
textField = new JTextField();
textField.setBounds(409, 150, 300, 20);
add(textField);
textField.setColumns(10);
JButton btnDone = new JButton("Done");
btnDone.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnDone.setBounds(365, 223, 89, 30);
add(btnDone);
JButton btnHelpMe = new JButton("Help Me");
btnHelpMe.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnHelpMe.setBounds(188, 390, 122, 52);
add(btnHelpMe);
JButton SignOut = new JButton("Sign-Out");
SignOut.setBounds(501, 392, 122, 48);
add(SignOut);
}
}
public void setScreen(JPanel fls, JPanel tru)
{
frmMybox.getContentPane().add(tru);
tru.setVisible(true);
fls.setVisible(false);
frmMybox.getContentPane().revalidate();
frmMybox.getContentPane().repaint();
}
update your setScreen method as above.

Categories

Resources