I'm currently a beginner in programming and I'm kind of having a hard time right now. Currently I'm making a simple shopping lister using java. Before I go to the problem, I would like to share my code first:
This is the main page of my list:
package com.main;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class MainPage extends JFrame implements ActionListener{
JTextPane txtpnListName, txtpnTotal, txtpnSubtotal, txtpnShoppingLists;
JTextField txtfNewItem, txtfPrice, txtItemAmount;
JTextArea textItemList, textAmountList, textPriceList;
JButton btnNewButton, btnNewButton_1, btnLogout, btnMakeNewList;
JScrollPane scrollPane1, scrollPane2,scrollPane3;
JTabbedPane tabPane;
public MainPage(){
super("List n\' Go");
setResizable(false);
getContentPane().setBackground(Color.WHITE);
setBounds(100, 100, 600, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(null);
tabPane = new JTabbedPane(JTabbedPane.LEFT);
add(tabPane);
txtpnListName = new JTextPane();
txtpnListName.setBackground(Color.WHITE);
txtpnListName.setEditable(false);
txtpnListName.setFont(new Font("Tahoma", Font.BOLD, 30));
txtpnListName.setText("LIST NAME");
txtpnListName.setBounds(175, 25, 175, 38);
getContentPane().add(txtpnListName);
//Buttons
btnNewButton = new JButton("Save");
btnNewButton.setBounds(375, 25, 75, 21);
getContentPane().add(btnNewButton);
btnNewButton_1 = new JButton("Add Item");
btnNewButton_1.setBounds(375, 59, 75, 21);
getContentPane().add(btnNewButton_1);
btnNewButton_1.addActionListener(this);
btnLogout = new JButton("Logout");
btnLogout.setBounds(463, 25, 75, 21);
getContentPane().add(btnLogout);
btnLogout.addActionListener(this);
txtfNewItem = new JTextField();
txtfNewItem.setBackground(Color.WHITE);
txtfNewItem.setEditable(false);
txtfNewItem.setFont(new Font("Tahoma", Font.PLAIN, 16));
txtfNewItem.setText("New Item");
txtfNewItem.setBounds(185, 99, 200, 28);
getContentPane().add(txtfNewItem);
txtfPrice = new JTextField();
txtfPrice.setBackground(Color.WHITE);
txtfPrice.setEditable(false);
txtfPrice.setFont(new Font("Tahoma", Font.PLAIN, 16));
txtfPrice.setText("Price");
txtfPrice.setBounds(490, 99, 75, 28);
getContentPane().add(txtfPrice);
txtItemAmount = new JTextField();
txtItemAmount.setBackground(Color.WHITE);
txtItemAmount.setEditable(false);
txtItemAmount.setFont(new Font("Tahoma", Font.PLAIN, 16));
txtItemAmount.setText("Amount");
txtItemAmount.setBounds(395, 99, 75, 28);
getContentPane().add(txtItemAmount);
//ListBox
scrollPane1 = new JScrollPane();
scrollPane1.setBounds(185, 133, 210, 330);
getContentPane().add(scrollPane1);
scrollPane2 = new JScrollPane();
scrollPane2.setBounds(400, 133, 65, 330);
getContentPane().add(scrollPane2);
scrollPane3 = new JScrollPane();
scrollPane3.setBounds(490, 133, 70, 330);
getContentPane().add(scrollPane3);
textItemList = new JTextArea();
textItemList.setEditable(false);
scrollPane1.setViewportView(textItemList);
textItemList.setBackground(Color.GRAY);
textAmountList = new JTextArea();
textAmountList.setEditable(false);
scrollPane2.setViewportView(textAmountList);
textAmountList.setBackground(Color.GRAY);
textPriceList = new JTextArea();
textPriceList.setEditable(false);
scrollPane3.setViewportView(textPriceList);
textPriceList.setBackground(Color.GRAY);
//Summation
txtpnTotal = new JTextPane();
txtpnTotal.setEditable(false);
txtpnTotal.setFont(new Font("Tahoma", Font.PLAIN, 14));
txtpnTotal.setText("Total no. of Items:");
getContentPane().add(txtpnTotal);
txtpnTotal.setBounds(195, 473, 150, 38);
txtpnSubtotal = new JTextPane();
txtpnSubtotal.setEditable(false);
txtpnSubtotal.setFont(new Font("Tahoma", Font.PLAIN, 14));
txtpnSubtotal.setText("Subtotal:");
txtpnSubtotal.setBounds(360, 473, 85, 67);
getContentPane().add(txtpnSubtotal);
txtpnShoppingLists = new JTextPane();
txtpnShoppingLists.setEditable(false);
txtpnShoppingLists.setFont(new Font("Tahoma", Font.BOLD, 15));
txtpnShoppingLists.setText("Shopping Lists");
txtpnShoppingLists.setBounds(10, 10, 120, 31);
getContentPane().add(txtpnShoppingLists);
//For new List
btnMakeNewList = new JButton("Make New List");
btnMakeNewList.setBounds(10, 519, 120, 21);
getContentPane().add(btnMakeNewList);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent exit){
int reply = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit the app?", "Confirm Exit",0);
if(reply == JOptionPane.YES_OPTION){
JOptionPane.showMessageDialog(null, "Thank your for using List n' Go!", "Goodbye!",1);
System.exit(0);
}
else{
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
}
});
setSize(600,600);
setVisible(true);
setResizable(false);
}
//for testiong purposes
public static void main (String []args){
MainPage mainpage = new MainPage();
}
//Action Listeners
public void actionPerformed(ActionEvent e) {
//logout Button
if(e.getSource() == btnLogout){
int reply = JOptionPane.showConfirmDialog(null, "Are you sure you want to Logout?", "Confirm Logout?",2);
if( reply == JOptionPane.YES_OPTION){
JOptionPane.showMessageDialog(null, "You have logged out.", "Logout Success",1);
LoginScreen login = new LoginScreen();
dispose();
}
else{
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
// Make new List Button
}
else if(e.getSource() == btnMakeNewList){
}
// Add item to list Button
else if(e.getSource() == btnNewButton_1){
}
else if (e.getSource() == btnNewButton){
}
}
}
And here is the GUI where I want to ask the user for input:
package com.main;
import javax.swing.*;
import java.awt.event.*;
public class AddToList extends JFrame implements ActionListener{
JLabel itemName, itemAmount, itemPrice, itemTotalPrice;
JTextField jtfItemName, jtfItemAmount, jtfItemPrice, jtfTotalPrice;
JButton addItem, goBack;
public AddToList(){
super("What do you want to add?");
setLayout(null);
itemName = new JLabel("Item Name");
itemAmount = new JLabel("Item Amount");
itemPrice = new JLabel("Item Price");
itemTotalPrice = new JLabel();
jtfItemName = new JTextField();
jtfItemAmount = new JTextField();
jtfItemPrice = new JTextField();
jtfTotalPrice = new JTextField();
addItem = new JButton("Add Item");
goBack = new JButton("Back");
itemName.setBounds(10,10, 70,15);
jtfItemName.setBounds(75,10, 270,20);
itemAmount.setBounds(350,10, 70,15);
jtfItemAmount.setBounds(425,10, 120,20);
itemPrice.setBounds(550,10, 70,15);
jtfItemPrice.setBounds(610,10, 120,20);
addItem.setBounds(250,35, 100,25);
goBack.setBounds(400,35, 100,25);
addItem.addActionListener(this);
goBack.addActionListener(this);
add(itemName);add(jtfItemName);add(itemAmount);
add(jtfItemAmount);add(itemPrice);add(jtfItemPrice);
add(addItem);add(goBack);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent exit){
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
});
setSize(750, 100);
setResizable(false);
setVisible(true);
}
// test Program
public static void main(String []args){
AddToList test = new AddToList();
}
// Action Trigger
public void actionPerformed(ActionEvent e) {
//Add item Confirmation
if(e.getSource() == addItem){
}
// Cancel Add Item
else if(e.getSource() == goBack){
}
}
}
My goal here is after the user clicked the "Add Item" button from the Main page, it will prompt the user to input the product details such as the name, amount, and price on the add Item GUI. it will then take the user input and list it on the main page. After that it will calculate the total amount of items on the list, it's amount, and total price. The problem is that I am currently stuck on how can I pass the user input from the Add Item GUI to the main page. I've been researching but I still couldn't find my way around it. I hope you can help me and any help is much appreciated.
P.S: I'm sorry if you find my code a bit too long because this is what currently I could do with the best of my knowledge and abilities. But don't worry, I know that I shouldn't use setLayout(null) since swing has layout managers that I can use. I am still currently learning more about it so bear with me please.
Usually I have a JFrame holding most of the data. If additional information is required by the application, it will show an input dialog. Most of the time this input is not just a string but some more complex stuff. So here is the pattern I follow:
Create a form derived from JPanel. Add the UI elements you need, and use the bean pattern so the necessary data can be injected/retrieved. Very likely you want to show such input when a button in a pane is pressed, so the ActionListener code can look like this:
FormBean fb = new FormBean();
fb.setData(...); (use setters to display data if required/feasible)
if (JOptionPane.showOptionDialog(this, fb, ...)==JOptionPane.OK_OPTION) {
// user pressed ok, so process the data he entered
fb.getData();
}
The advantage of using JOptionPane.showOptionDialog is that you get a standard modal dialog window without threading issues or the question when to activate your code again.
Related
I know the code is bad and easy. I am a starter and need some help. I want to add a second button to my code. I feel like I changed the coordinates of the button so it doesn't "fall" on the first one. Any suggestions? (Also, .this is a bit unknown to me so I just copy - pasted it hoping it doesnt affect the second button. I feel like it has to do with .this and the coordinates of the button I entered).
import java.awt.*;
import java.awt.event.*;
public class CalculatorGUI extends Frame implements ActionListener
{
static Operand op;
TextField display;
Button button0;
Button button1;
public CalculatorGUI(String title, Operand op)
{
super(title);
CalculatorGUI.op = op;
this.setLayout(null);
this.setFont(new Font("TimesRoman", Font.PLAIN, 14));
this.setBackground(Color.blue);
button0 = new Button("0");
button0.setBounds(64, 265, 35, 28);
button0.setFont(new Font("TimesRoman", Font.PLAIN, 14));
button0.setForeground(Color.blue);
button0.setFocusable(false);
button0.addActionListener(this);
this.add(button0);
this.setSize(283,320);
this.setLocation(40,30);
this.setVisible(true);
this.setResizable(false);
button1 = new Button("1");
button1.setBounds(64, 230, 35, 28);
button1.setFont(new Font("TimesRoman", Font.PLAIN, 14));
button1.setForeground(Color.blue);
button1.setFocusable(false);
button1.addActionListener(this);
this.add(button1);
this.setSize(283,320);
this.setLocation(40,30);
this.setVisible(true);
this.setResizable(false);
this.addWindowListener(new CloseWindowAndExit());
display = new TextField("");
display.setEditable(false);
display.setBounds(13, 55, 257, 30);
this.add(display);
}
class CloseWindowAndExit extends WindowAdapter
{
public void windowClosing(WindowEvent closeWindowAndExit)
{
System.exit(0);
}
}
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==button0)
{
display.setText("Button0 is pressed");
CalculatorGUI.op.addDigit('0');
}
}
}
Do not add buttons directly to the main frame. Instead, create another panel and add the buttons to it:
Panel newPanel = new Panel(new GridBagLayout());
Button button0 = new Button("BUTTON_0");
button0.setBounds(10, 265, 30, 30);
button0.setFont(new Font("TimesRoman", Font.PLAIN, 14));
button0.setForeground(Color.blue);
button0.setFocusable(false);
Button button1 = new Button("BUTTON_1");
button1.setBounds(10, 265, 30, 30);
button1.setFont(new Font("TimesRoman", Font.PLAIN, 14));
button1.setForeground(Color.blue);
button1.setFocusable(false);
newPanel.add(button0);
newPanel.add(button1);
this.add(newPanel);
I have two menu items here ,one is for the student information and the another one is for the teacher information.i have added the menu for student and teacher both.
I am struck in the event listener how to add the action to the menu and menu1,suppose when the user click on menu 1 then student information should be displayed and for the menu2 the teacher information action should be performed.i am confused where to add the action listenr and perform the operation for the student and teacher.
I am new to the the event and action listner in java.kindly suggest the solution
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.sql.*;
public class Searchdb extends JFrame implements ActionListener {
//Initializing Components
JLabel lb,lbd,lb1, lb2, lb3, lb5;
JTextField tf1, tf2,tf3,tf5,tfd;
JButton btn;
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Student");
JMenu menu1 = new JMenu("Teacher");
//Creating Constructor for initializing JFrame components
Searchdb() {
//Providing Title
super("Fetching Roll Information");
setJMenuBar(menuBar);
menuBar.add(menu);
menuBar.add(menu1);
lb5 = new JLabel("Roll Number:");
lb5.setBounds(20, 20, 100, 20);
tf5 = new JTextField(20);
tf5.setBounds(130, 20, 200, 20);
lbd = new JLabel("Date:");
lbd.setBounds(20, 50, 100, 20);
tfd = new JTextField(20);
tfd.setBounds(130, 50, 200, 20);
btn = new JButton("Submit");
btn.setBounds(50, 50, 100, 20);
btn.addActionListener(this);
lb = new JLabel("Fetching Student Information From Database");
lb.setBounds(30, 80, 450, 30);
lb.setForeground(Color.black);
lb.setFont(new Font("Serif", Font.PLAIN, 12));
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 500);
lb1 = new JLabel("Name:");
lb1.setBounds(20, 120, 100, 20);
tf1 = new JTextField(50);
tf1.setBounds(130, 120, 200, 20);
lb2 = new JLabel("Fathername:");
lb2.setBounds(20, 150, 100, 20);
tf2 = new JTextField(100);
tf2.setBounds(130, 150, 200, 20);
lb3 = new JLabel("State:");
lb3.setBounds(20, 180, 100, 20);
tf3 = new JTextField(50);
tf3.setBounds(130, 180, 200, 20);
setLayout(null);
//Add components to the JFrame
add(lb5);
add(tf5);
add(lbd);
add(tfd);
add(btn);
add(lb);
add(lb1);
add(tf1);
add(lb2);
add(tf2);
add(lb3);
add(tf3);
//Set TextField Editable False
tf1.setEditable(false);
tf2.setEditable(false);
tf3.setEditable(false);
}
public void actionPerformed(ActionEvent e) {
//Create DataBase Coonection and Fetching Records
try {
String str = tf5.getText();
Datestri = tfd.getText();//Getting the unable to convert String to Date error
System.out.println(str);
System.out.println(stri);
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#//host:port/servicename","username","password");
PreparedStatement st = con.prepareStatement("select Name,Fathername,State from student_db where roll_number=? and medium=?");
System.out.println(st);
st.setString(1, str);
st.setDate(2, stri);
//Excuting Query
ResultSet rs = st.executeQuery();
System.out.println(rs);
if (rs.next()) {
String s = rs.getString(1);
String s1 = rs.getString(2);
String s2 = rs.getString(3);
//Sets Records in TextFields.
tf1.setText(s);
tf2.setText(s1);
tf3.setText(s2);
} else {
JOptionPane.showMessageDialog(null, "Student not Found");
}
//Create Exception Handler
} catch (Exception ex) {
System.out.println(ex);
}
}
public void actionPerformed(ActionEvent e) {
//Create DataBase Coonection and Fetching Records
//Teacher information should be retrieved from the db
}
//Running Constructor
public static void main(String args[]) {
new Searchdb();
}
}
Thanks for any help in advance.
Hope, This will help
For JMenu you can use MenuListener
class MenuListenerAdapter implements MenuListener {
#Override
public void menuSelected(MenuEvent e) {
System.out.println("Menu Selected");
}
#Override
public void menuDeselected(MenuEvent e) {
System.out.println("Menu Deselected");
}
#Override
public void menuCanceled(MenuEvent e) {
System.out.println("Menu Canceled");
}
}
Then add MenuListener on menu
menu.addMenuListener(new MenuListenerAdapter());
You can use MouseListener,
Find your solution below, check out console when you click on Student and Teacher Menu
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JTextField;
public class Searchdb extends JFrame implements ActionListener {
//Initializing Components
JLabel lb, lbd, lb1, lb2, lb3, lb5;
JTextField tf1, tf2, tf3, tf5, tfd;
JButton btn;
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Student");
JMenu menu1 = new JMenu("Teacher");
//Creating Constructor for initializing JFrame components
Searchdb() {
//Providing Title
super("Fetching Roll Information");
setJMenuBar(menuBar);
menuBar.add(menu);
menuBar.add(menu1);
menu.addMouseListener(new MouseListenerForStudentAndTeacher());
menu1.addMouseListener(new MouseListenerForStudentAndTeacher());
lb5 = new JLabel("Roll Number:");
lb5.setBounds(20, 20, 100, 20);
tf5 = new JTextField(20);
tf5.setBounds(130, 20, 200, 20);
lbd = new JLabel("Date:");
lbd.setBounds(20, 50, 100, 20);
tfd = new JTextField(20);
tfd.setBounds(130, 50, 200, 20);
btn = new JButton("Submit");
btn.setBounds(50, 50, 100, 20);
btn.addActionListener(this);
lb = new JLabel("Fetching Student Information From Database");
lb.setBounds(30, 80, 450, 30);
lb.setForeground(Color.black);
lb.setFont(new Font("Serif", Font.PLAIN, 12));
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 500);
lb1 = new JLabel("Name:");
lb1.setBounds(20, 120, 100, 20);
tf1 = new JTextField(50);
tf1.setBounds(130, 120, 200, 20);
lb2 = new JLabel("Fathername:");
lb2.setBounds(20, 150, 100, 20);
tf2 = new JTextField(100);
tf2.setBounds(130, 150, 200, 20);
lb3 = new JLabel("State:");
lb3.setBounds(20, 180, 100, 20);
tf3 = new JTextField(50);
tf3.setBounds(130, 180, 200, 20);
setLayout(null);
//Add components to the JFrame
add(lb5);
add(tf5);
add(lbd);
add(tfd);
add(btn);
add(lb);
add(lb1);
add(tf1);
add(lb2);
add(tf2);
add(lb3);
add(tf3);
//Set TextField Editable False
tf1.setEditable(false);
tf2.setEditable(false);
tf3.setEditable(false);
}
public void actionPerformed(ActionEvent e) {
// removed code, you can add your code later on
}
public static void main(String args[]) {
new Searchdb();
}
private class MouseListenerForStudentAndTeacher extends MouseAdapter {
#Override
public void mouseClicked(MouseEvent e) {
if (e.getSource() == menu) {
System.out.println("Student Menu Clicked");
}
if (e.getSource() == menu1) {
System.out.println("Teacher Menu Clicked");
}
}
}
}
I want to be able to validate a number of different JTextFields in my java project. One being to ensure the user enters a number into a particular field.
Another problem I'm having is being able to validate a particular number, such as 1234 in a field when a submit button is pressed.
If I have to create a method in a separate class then that fine but how would I call the method into my GUI class to use for my JTextField.
I'm quite new to Java and find some of this hard so any help is greatly appreciated.
At the minute I have:
import java.awt.BorderLayout;
public class CashDialog extends JDialog {
private final JPanel contentPanel = new JPanel();
private JTextField txtEmilysBistro;
private JTextField textconfirmNumber;
private String confirmNumber;
private JButton btnSubmit;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
CashDialog dialog = new CashDialog();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the dialog.
*/
public CashDialog() {
this.confirmNumber = confirmNumber;
setBounds(100, 100, 526, 372);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBackground(new Color(255, 0, 153));
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
{
txtEmilysBistro = new JTextField();
txtEmilysBistro.setBackground(new Color(255, 0, 153));
txtEmilysBistro.setHorizontalAlignment(SwingConstants.CENTER);
txtEmilysBistro.setForeground(new Color(255, 255, 255));
txtEmilysBistro.setFont(new Font("AR ESSENCE", Font.PLAIN, 50));
txtEmilysBistro.setEditable(false);
txtEmilysBistro.setText("Emily's Bistro");
txtEmilysBistro.setBounds(0, 0, 504, 57);
contentPanel.add(txtEmilysBistro);
txtEmilysBistro.setColumns(10);
}
JTextArea txtrConfirm = new JTextArea();
txtrConfirm.setForeground(new Color(255, 255, 255));
txtrConfirm.setBackground(new Color(255, 0, 153));
txtrConfirm.setEditable(false);
txtrConfirm.setFont(new Font("AR ESSENCE", Font.PLAIN, 25));
txtrConfirm.setText("Please allow your waiter/waitress to enter the confirmation number.");
txtrConfirm.setBounds(54, 73, 407, 77);
contentPanel.add(txtrConfirm);
txtrConfirm.setLineWrap(true);
textconfirmNumber = new JTextField();
textconfirmNumber.setFont(new Font("AR ESSENCE", Font.PLAIN, 30));
textconfirmNumber.setBounds(147, 148, 227, 47);
contentPanel.add(textconfirmNumber);
textconfirmNumber.setColumns(10);
btnSubmit = new JButton("Submit");
btnSubmit.setBackground(new Color(102, 51, 255));
btnSubmit.setForeground(new Color(255, 255, 255));
btnSubmit.setFont(new Font("AR ESSENCE", Font.PLAIN, 25));
btnSubmit.setBounds(184, 211, 162, 29);
contentPanel.add(btnSubmit);
}
}
In this particular text field I only want it to accept the number 1234 in the text field.
There are a few issues with your code, but that is beside the point. To address your question specifically here is one approach. Grant it, you'd probably want to handle it differently, verify you are getting an integer instead of comparing strings, but still this is how you'd add a listener to your submit button.
btnSubmit.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent arg0)
{
final String data = txtrConfirm.getText();
if( data.compareTo("1234") != 0 )
{
// alert the user
}
else
{
// data is good, do something with it
}
}
});
so im making a program for my project.
and when i clicked a button it must open anohter frame and make the button unclickable. and when you closed the popup frame the button must re enable. so this is
my main frame
package Option2;
import javax.swing.event.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MainMenu {
int intCtr1 = 0;
JFrame frame1 = new JFrame("EXD LAN PARTY");
JButton Button1 = new JButton();
JButton Button2 = new JButton();
JButton Button3 = new JButton();
JButton Button4 = new JButton();
JLabel Label1 = new JLabel();
public void MainMenu(){
//BUTTON1
Button1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Option2/PI2.jpg")));
Button1.setBackground(Color.white);
Button1.setBounds(50, 350, 150, 150);
Button1.setToolTipText("Personal Info");
//BUTTON1 END
//BUTTON2
Button2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Option2/PC.jpg")));
Button2.setBackground(Color.white);
Button2.setBounds(250, 350, 150, 150);
Button2.setToolTipText("PC INFO");
//BUTTON2 END
//BUTTON3
Button3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Option2/Games.jpg")));
Button3.setBackground(Color.white);
Button3.setBounds(450, 350, 150, 150);
Button3.setToolTipText("Games");
//BUTTON3 END
//BUTTON4 END
Button4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Option2/Players.jpg")));
Button4.setBackground(Color.white);
Button4.setBounds(650, 350, 150, 150);
Button3.setToolTipText("Players");
//BUTTON4 END
//LABEL1
Label1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Option2/EXD.jpg")));
Label1.setBounds(50, 50, 800, 250);
//LABEL1 END
//Frame1
frame1.getContentPane().setBackground(Color.black);
frame1.setResizable(false);
frame1.setLayout(null);
frame1.setSize(870,650);
frame1.setVisible(true);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.add(Label1);
frame1.add(Button1);
frame1.add(Button2);
frame1.add(Button3);
frame1.add(Button4);
//Frame1 END
Button1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent a){
PersonalInfo objPI = new PersonalInfo();
objPI.Menu1();
Button1.setEnabled(false);
}
});
Button2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent a){
PCInfo objPCI = new PCInfo();
objPCI.Menu2();
}
});
Button3.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent a){
Games objGames = new Games();
objGames.Menu3();
}
});
Button4.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent a){
Players objPlayers = new Players();
objPlayers.Menu4();
}
});
}
public void dim1(){
if(intCtr1 == 1){
MainMenu objMM = new MainMenu();
objMM.Button1.setEnabled(true);
System.out.println("SD");
}
}
}
**and this is my sub frame**
package Option2;
import javax.swing.event.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class PersonalInfo {
String[] arrSex = {"Male","Female"};
JFrame frame1 = new JFrame("Personal Info");
JLabel label1 = new JLabel("ID");
JLabel label2 = new JLabel("Last Name");
JLabel label3 = new JLabel("First Name");
JLabel label4 = new JLabel("Middle Name");
JLabel label5 = new JLabel("SEX");
JLabel label6 = new JLabel();
JTextField tf1 = new JTextField();
JTextField tf2 = new JTextField();
JTextField tf3 = new JTextField();
JTextField tf4 = new JTextField();
JComboBox CB1 = new JComboBox(arrSex);
JButton Button1 = new JButton("NEW");
JButton Button2 = new JButton("SAVE");
JButton Button3 = new JButton("EDIT");
JButton Button4 = new JButton("CANCEL");
JButton Button5 = new JButton();
JButton Button6 = new JButton();
JButton Button7 = new JButton();
JButton Button8 = new JButton();
public void Menu1(){
//Frame1
frame1.add(label6);
frame1.add(label1);
frame1.add(tf1);
frame1.add(label2);
frame1.add(tf2);
frame1.add(label3);
frame1.add(tf3);
frame1.add(label4);
frame1.add(tf4);
frame1.add(label5);
frame1.add(CB1);
frame1.add(Button1);
frame1.add(Button2);
frame1.add(Button3);
frame1.add(Button4);
frame1.add(Button5);
frame1.add(Button6);
frame1.add(Button7);
frame1.add(Button8);
frame1.setVisible(true);
frame1.getContentPane().setBackground(Color.black);
frame1.setSize(600,600);
frame1.setResizable(false);
frame1.setLayout(null);
frame1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame1.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
MainMenu objMM = new MainMenu();
objMM.intCtr1=1;
objMM.dim1();
}
});
//Frame1 End
//LABEL6
label6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Option2/PI.jpg")));
label6.setBounds(30, 5, 800, 250);
//LABEL6 END
//LABEl1
label1.setBounds(100, 220, 50,50);
label1.setForeground(Color.white);
label1.setFont(new Font("Serif", Font.BOLD, 18));
//Label1 end
//Tf
tf1.setBounds(130, 230, 400,30);
tf1.setEnabled(false);
SmartC objSMC = new SmartC();
tf1.setText(objSMC.SmartCounter("ABC123415XYZS"));
//tf end
//label2
label2.setBounds(35, 255, 120,50);
label2.setForeground(Color.white);
label2.setFont(new Font("Serif", Font.BOLD, 18));
//label2 end
//Tf2
tf2.setBounds(130, 270, 400,30);
//tf2 end
//label3
label3.setBounds(35, 295, 120,50);
label3.setForeground(Color.white);
label3.setFont(new Font("Serif", Font.BOLD, 18));
//label3 end
//Tf3
tf3.setBounds(130, 310 , 400, 30);
//tf3 end
//label4
label4.setBounds(15, 335, 120,50);
label4.setForeground(Color.white);
label4.setFont(new Font("Serif", Font.BOLD, 18));
//label4 end
//Tf4
tf4.setBounds(130, 350 , 400, 30);
//tf4 end
//label4
label5.setBounds(85, 375, 120,50);
label5.setForeground(Color.white);
label5.setFont(new Font("Serif", Font.BOLD, 18));
//label4 end
//cb1
CB1.setBounds(130, 390, 100, 30);
CB1.setBackground(Color.white);
//cb1 end
//button1
Button1.setBounds(35, 450, 100, 30);
Button1.setBackground(Color.white);
//
//
Button2.setBounds(150, 450, 100, 30);
Button2.setBackground(Color.white);
//
//
Button3.setBounds(335, 450, 100, 30);
Button3.setBackground(Color.white);
//
//
Button4.setBounds(450, 450, 100, 30);
Button4.setBackground(Color.white);
//
//
Button5.setBounds(35, 500, 100, 50);
Button5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Option2/First.jpg")));
Button5.setBackground(Color.white);
//
//
Button6.setBounds(150, 500, 100, 50);
Button6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Option2/Previous.jpg")));
Button6.setBackground(Color.white);
//
//
Button7.setBounds(335, 500, 100, 50);
Button7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Option2/Next.jpg")));
Button7.setBackground(Color.white);
//
//
Button8.setBounds(450, 500, 100, 50);
Button8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Option2/Last.jpg")));
Button8.setBackground(Color.white);
//
//
}
}
Any Suggestions about my coding is accepted. Sorry Still learning about Java :)
and when i clicked a button it must open anohter frame
You should NOT be creating another JFrame.
Instead you should be creating a modal JDialog. The dialog will not allow you to click on the frame until the dialog is closed.
Any Suggestions about my coding is accepted
Follow Java naming conventions. Variable names should NOT start with an upper case character. Sometimes you follow this guideline and sometimes you don't. Be consistent!
Don't use setBounds(...). Swing was designed to be used with layout managers!
First, please read Java naming conventions.
You need to pass the reference of MainMenu to PersonalInfo in order to achieve what you need, here:
button1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent a){
PersonalInfo objPI = new PersonalInfo(this);
objPI.menu1();
button1.setEnabled(false);
}
});
And you need to add a constructor to PersonalInfo:
private MainMenu m;
public PersonalInfo(MainMenu m) {
this.m = m;
}
Add a public method to MainMenu:
public void enableMyButton() {
button1.setEnabled(true);
}
Now you can add an event listener to PersonalInfo to enable the button of the MainMenu frame:
frame1.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
this.m.enableMyButton();
}
});
This question already has answers here:
Allowing the "Enter" key to press the submit button, as opposed to only using MouseClick
(7 answers)
Closed 8 years ago.
Im doing this program and this frame signs up the new users.
What I want is to be able to fill in each text field with the information and then to press the "Cadastrar" key ("Cadastrar" = "Sign up"), not only with the mouse but also with the "Enter" key.
I tried using a keyListener but it turned out to be a little to confusing to me.
Here's the code:
package grafico;
public class TelaDeCadastro extends JFrame {
private TextField campoConfirmaSenha;
private TextField campoNome;
private TextField campoEmail;
private TextField campoSenha;
private TextField dicaDeSenha;
public static void main(String[] args) {
public TelaDeCadastro() {
setResizable(false);
setIconImage(Toolkit.getDefaultToolkit().getImage(
TelaDeCadastro.class.getResource("/Files/CashLog.png")));
setTitle("Cadastro");
setPreferredSize(new Dimension(400, 300));
setLocationRelativeTo(null);
JButton botaoCadastrar = new JButton("Cadastrar");
botaoCadastrar.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
}
}
});
botaoCadastrar.setBounds(139, 196, 115, 35);
JButton botaoVoltar = new JButton("Voltar");
botaoVoltar.setBounds(10, 231, 90, 30);
JButton botaoSair = new JButton("Sair");
botaoSair.setBounds(294, 231, 90, 30);
ButtonGroup botoesRetorno = new ButtonGroup();
botoesRetorno.add(botaoSair);
botoesRetorno.add(botaoVoltar);
// botão para submeter as informações passadas
botaoCadastrar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
});
// botão sair fecha o programa
botaoSair.addActionListener(new ActionListener() {
// botão voltar retorna para a tela de login
botaoVoltar.addActionListener(new ActionListener() {
JPanel container = new JPanel();
container.setLayout(null);
dicaDeSenha = new TextField();
dicaDeSenha.setBounds(109, 159, 265, 22);
container.add(dicaDeSenha);
campoConfirmaSenha = new TextField();
campoConfirmaSenha.setEchoChar('*');
campoConfirmaSenha.setBounds(138, 126, 236, 23);
container.add(campoConfirmaSenha);
campoSenha = new TextField();
campoSenha.setEchoChar('*');
campoSenha.setBounds(109, 93, 265, 23);
container.add(campoSenha);
campoEmail = new TextField();
campoEmail.setBounds(109, 62, 265, 23);
container.add(campoEmail);
campoNome = new TextField();
campoNome.setBounds(109, 31, 265, 23);
container.add(campoNome);
JLabel labelNome = new javax.swing.JLabel("Seu nome:");
labelNome.setBounds(10, 35, 364, 14);
container.add(labelNome);
JLabel labelEmail = new javax.swing.JLabel("Seu Email:");
labelEmail.setBounds(10, 66, 364, 14);
container.add(labelEmail);
JLabel labelSenha = new javax.swing.JLabel("Sua senha:");
labelSenha.setBounds(10, 95, 364, 14);
container.add(labelSenha);
JLabel lblConfirmarSenha = new JLabel("Confirmar senha:");
lblConfirmarSenha.setBounds(10, 126, 122, 15);
container.add(lblConfirmarSenha);
JLabel lblDicaDaSenha = new JLabel("Dica da senha:");
lblDicaDaSenha.setBounds(10, 162, 90, 14);
container.add(lblDicaDaSenha);
container.add(botaoCadastrar);
container.add(botaoVoltar);
container.add(botaoSair);
getContentPane().add(container);
JLabel lblCadastrese = new JLabel("Cadastre-se:");
lblCadastrese.setHorizontalAlignment(SwingConstants.CENTER);
lblCadastrese.setHorizontalTextPosition(SwingConstants.CENTER);
lblCadastrese.setBounds(10, 9, 364, 14);
container.add(lblCadastrese);
JLabel label = new JLabel("");
label.setIcon(new ImageIcon(TelaDeCadastro.class
.getResource("/Files/conta-sem-tarifa.jpg")));
label.setBounds(0, 0, 400, 300);
container.add(label);
pack();
}
public TextField getCampoConfirmaSenha() {
public TextField getCampoNome() {
public TextField getCampoEmail() {
public TextField getCampoSenha() {
public TextField getDicaDeSenha() {
}
Don't use KeyListener (or for that matter MouseListener) with buttons.
Buttons are backed by the ActionListener API which deals with Enter, Space, other platform specific activation key strokes, left mouse clicks and mnemonics automatically...
Take a look at How to Use Buttons, Check Boxes, and Radio Buttons and How to Write an Action Listener for more details.
You should also have a look at How to Use Root Panes, as JRootPane allows you to define a "default" button which will be actived when the user presses the "activation" key stroke. Just beware, that if the component with focus consumes that event, it won't active the button though
Generally speaking, you should avoid KeyListener where ever possible and favor the key bindings API instead anyway