I am trying to pass the table number from the restaurant class into tableLabel which is in the Menu page class. When the code is running the tableLabel returns null. Any help would be appreciated to enable the code when running to return a number in the tableLabel.
Extract from Restaurant Class
public class Restaurant extends JFrame {
private JPanel contentPane;
private JTextField restaurant_Txt;
private JTextField num_Diners;
private JTextField num_Diners_Txt;
private JTextField table_Num_Txt;
private JTextField num_Table;
private JButton num_TableSub_Btn;
private JButton proceed_Menu_Btn;
private JButton MyDocumentListener;
MenuPage parent;
public static String tableNumber;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Restaurant frame = new Restaurant();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Restaurant() {
super("Restaurant");
parent = new MenuPage();
initGUI();
num_Table = new JTextField("NewUser", 10);
}
public void initGUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 640, 310);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
table_Num_Txt = new JTextField();
table_Num_Txt.setEditable(false);
table_Num_Txt.setText("Table number ?");
table_Num_Txt.setBounds(145, 164, 112, 26);
contentPane.add(table_Num_Txt);
table_Num_Txt.setColumns(10);
num_Table = new JTextField("");
num_Table.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
if (e.getKeyCode() == 10) {
tableNumber = num_Table.getText();
}
}
});
num_Table.setBounds(334, 161, 83, 26);
contentPane.add(num_Table);
num_Table.setColumns(10);
}
}
Extract from Menu Page class
tableLabel = new JLabel(" : " + Restaurant.tableNumber);
tableLabel.setBounds(16, 6, 61, 16);
contentPane.add(tableLabel);
This may be a stupid question, but are you sure you are pressing enter when being inside the num_Table field inside your GUI since the variable is set when this happens. Also you should probably pass it via the constructor to MainPage, not as a static variable.
Related
My problem is that I have a class that when the user types out the text displayed dispose() is called, which works the first time but if you don't close the program and open it again, dispose() is called, but doesn't do anything which breaks the program.
public class TypeMenu extends JDialog {
protected final JPanel contentPanel = new JPanel();
protected static JTextField inputTxtField;
protected static JTextField textField;
protected static JTextField introTxtField;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
Easy dialog = new Easy();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the dialog.
* #param introTxtField2
* #param textField2
* #param inputTxtField2
*/
public TypeMenu(JTextField inputTxtField2, JTextField introTxtField2, JTextField textField2) {
setBounds(100, 100, 450, 300);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
contentPanel.add(getInputTxtField());
contentPanel.add(getTextField());
contentPanel.add(getIntroTxtField());
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
}
}
protected JTextField getInputTxtField() {
if (inputTxtField == null) {
inputTxtField = new JTextField();
inputTxtField.setHorizontalAlignment(SwingConstants.CENTER);
inputTxtField.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent arg0) {
String strField = textField.getText();
char key = arg0.getKeyChar();
int length = strField.length();
if (Character.toLowerCase(strField.charAt(0)) == Character.toLowerCase(key)) {
inputTxtField.setText(" ");
textField.setText(strField.substring(1));
System.out.println(length);
System.out.println(strField);
if (length - 1 <= 0) {
dispose();
}
} else {
inputTxtField.setText(" ");
}
}
});
inputTxtField.setBounds(56, 177, 314, 40);
inputTxtField.setColumns(10);
}
return inputTxtField;
}
protected JTextField getIntroTxtField() {
if (introTxtField == null) {
introTxtField = new JTextField();
introTxtField.setHorizontalAlignment(SwingConstants.CENTER);
introTxtField.setFont(new Font("Tahoma", Font.BOLD, 15));
introTxtField.setText("Easy Mode");
introTxtField.setEditable(false);
introTxtField.setBounds(56, 11, 314, 29);
introTxtField.setColumns(10);
}
return introTxtField;
}
private JTextField getTextField() {
if (textField == null) {
textField = new JTextField();
textField.setHorizontalAlignment(SwingConstants.CENTER);
textField.setFont(new Font("Monospaced", Font.BOLD, 20));
textField.setBounds(10, 51, 414, 40);
}
return textField;
}
}
This is one of the child classes
public class Easy extends TypeMenu {
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
Easy dialog = new Easy();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the dialog.
*/
public Easy() {
super(inputTxtField, introTxtField, textField);
setBounds(100, 100, 450, 300);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
contentPanel.add(getInputTxtField());
contentPanel.add(getIntroTxtField());
getString();
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
textField.selectAll();
}
}
private void getString() {
String str = textField.getText();
if (str.equals("")) {
String generator = StringGenerator.medium();
String nStr = "" + generator;
textField.setText(nStr);
}
}
}
The code that calls this class
public class StartMenu extends JDialog {
private final JPanel contentPanel = new JPanel();
private JTextField introTxt;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
StartMenu dialog = new StartMenu();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Creates the dialog and creates the buttons that take the user to each variation of the game when pressed.
*/
public StartMenu() {
setBounds(100, 100, 450, 300);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
{
introTxt = new JTextField();
introTxt.setFont(new Font("Tahoma", Font.BOLD, 12));
introTxt.setHorizontalAlignment(SwingConstants.CENTER);
introTxt.setText("Start Menu\r\n");
introTxt.setEditable(false);
introTxt.setBounds(75, 11, 276, 20);
contentPanel.add(introTxt);
introTxt.setColumns(10);
}
{
JButton btnEasyButton = new JButton("Easy Mode");
btnEasyButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
new Easy().setVisible(true);
}
});
btnEasyButton.setBounds(141, 42, 140, 23);
contentPanel.add(btnEasyButton);
}
{
JButton btnMediumButton = new JButton("Medium Mode");
btnMediumButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
new Medium().setVisible(true);
}
});
btnMediumButton.setBounds(141, 81, 140, 23);
contentPanel.add(btnMediumButton);
}
{
JButton btnHardButton = new JButton("Hard Mode");
btnHardButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
new Hard().setVisible(true);
}
});
btnHardButton.setBounds(141, 120, 140, 23);
contentPanel.add(btnHardButton);
}
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
}
}
}
}
your text field is static so he will have only one instance across the application.
so in the method getIntroTxtField() you have if statement that says :
if (introTxtField == null)
in the first time this condition is true but when you create the new instance this condition is false because the instance of the static field is all ready created in the first and you are adding the key listener inside the condition
so the action listener will be added only in the first creation.
if you need to keep the static because you need in other class you need to remove the == null
protected JTextField getInputTxtField() {
inputTxtField = null;
{
inputTxtField = new JTextField();
inputTxtField.setHorizontalAlignment(SwingConstants.CENTER);
inputTxtField.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent arg0) {
String strField = textField.getText();
char key = arg0.getKeyChar();
int length = strField.length();
if (Character.toLowerCase(strField.charAt(0)) == Character.toLowerCase(key)) {
inputTxtField.setText(" ");
textField.setText(strField.substring(1));
System.out.println(length);
System.out.println(strField);
if (length - 1 <= 0) {
dispose();
}
} else {
inputTxtField.setText(" ");
}
}
});
inputTxtField.setBounds(56, 177, 314, 40);
inputTxtField.setColumns(10);
}
return inputTxtField;
}
or remove the static from you field declaration static is used in
shared instace only when you are using only one instace across the
application like sessionFactory or any thing that need to be created
only one time.
you code is a lot to read but i think your problem is that you are calling the dispose() of the wrong object. may you are calling it always for the first object and you are creating a new one, and the dispose of this new dialog will never be call,Check you code may be you are creating many object and the dispose() is not called at all. make sure that you have full control of your objects instance to know if you are diposing the wanted dialog.
Hi guys im trying to set a string value on my main frame with a value generated in an other frame, but i dont quite know how to do it this is my code so far.
This is my mainframe opens the query frame where i input the data
public class InfoCd extends JFrame {
private JPanel contentPane;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
InfoCd frame = new InfoCd();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection conn=null;
private JTextField verConsulta;
/**
* Create the frame.
*/
public InfoCd() {
conn=sqliteConnection.dbConnector();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 753, 477);
contentPane = new JPanel();
contentPane.setBackground(SystemColor.activeCaption);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnHacerConsulta = new JButton("Hacer Consulta");
btnHacerConsulta.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Query q = new Query();
q.setVisible(true);
String userQuery = Query.getqueryField();//here is the problem im sending the value before filling it in the second frame
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery(userQuery);
table.setModel(DbUtils.resultSetToTableModel(rs));
//insert delete update
} catch (Exception e2) {
e2.printStackTrace();
}
}
});
btnHacerConsulta.setBounds(20, 388, 169, 39);
contentPane.add(btnHacerConsulta);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 0, 737, 367);
contentPane.add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
verConsulta = new JTextField();
verConsulta.setBounds(260, 388, 359, 29);
contentPane.add(verConsulta);
verConsulta.setColumns(10);
}
}
here is the query field
public class Query extends JFrame {
private JPanel contentPane;
private static JTextField queryField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Query frame = new Query();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Query() {
setBackground(SystemColor.activeCaption);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 641, 146);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnAceptar = new JButton("Aceptar");
btnAceptar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
getqueryField();
dispose();
}
});
btnAceptar.setBounds(226, 52, 155, 34);
contentPane.add(btnAceptar);
JLabel lblConsulta = new JLabel("Consulta:");
lblConsulta.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 13));
lblConsulta.setBounds(69, 11, 101, 39);
contentPane.add(lblConsulta);
queryField = new JTextField();
queryField.setBounds(135, 21, 480, 20);
contentPane.add(queryField);
queryField.setColumns(10);
}
public static String getqueryField() {
return queryField.getText();
}
}
So i have a bit of a weird issue, i just posted and fixed my other error, but that seems to have created this one, and it makes no sense.
Basically, the user presses a button, this window opens, then whether he presses cancel, or register, this window should setVisible to false. but when this code gets executed, it says my window is null.
package frontend;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class Registration extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private static boolean ranOnce = false;
private JPanel contentPane;
private Registration reg;
private JTextField userTF;
private JTextField passTF;
private JTextField emailTF;
private LoginProcess lp = new LoginProcess();
private JLabel error;
private JButton cancelBtn;
/**
* Create the frame.
*/
public Registration() {
if (!ranOnce) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
reg = new Registration();
reg.setVisible(true);
ranOnce = true;
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 245, 212);
setLocationRelativeTo(null);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblUsername = new JLabel("Username:");
lblUsername.setBounds(10, 11, 75, 14);
contentPane.add(lblUsername);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setBounds(10, 36, 75, 14);
contentPane.add(lblPassword);
JLabel lblEmail = new JLabel("Email:");
lblEmail.setBounds(10, 61, 75, 14);
contentPane.add(lblEmail);
userTF = new JTextField();
userTF.setBounds(95, 8, 130, 20);
contentPane.add(userTF);
userTF.setColumns(10);
passTF = new JTextField();
passTF.setColumns(10);
passTF.setBounds(95, 33, 130, 20);
contentPane.add(passTF);
emailTF = new JTextField();
emailTF.setColumns(10);
emailTF.setBounds(95, 58, 130, 20);
contentPane.add(emailTF);
error = new JLabel("");
error.setBounds(10, 154, 215, 14);
contentPane.add(error);
JButton regBtn = new JButton("Register");
regBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (!userTF.getText().equals("") || !passTF.getText().equals("") || !emailTF.getText().equals("")) {
try {
if (lp.newUser(userTF.getText(), passTF.getText(), emailTF.getText())) {
// THIS IS LINE 117 reg.setVisible(false);
Main.mainFrame.setVisible(true);
} else {
if (lp.duplicateAccount) {
error.setText("Error: Username already in use.");
}
}
} catch (SQLException e) {
}
}
}
});
regBtn.setBounds(10, 120, 215, 23);
contentPane.add(regBtn);
cancelBtn = new JButton("Cancel");
cancelBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
reg.setVisible(false);
Main.mainFrame.setVisible(true);
}
});
cancelBtn.setBounds(10, 86, 215, 23);
contentPane.add(cancelBtn);
}
}
this is the abnormal error:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at frontend.Registration$3.actionPerformed(Registration.java:117)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
i really have no clue as to why it's saying my window is null, when it's not. it has to be something i've done when initialising the window.
Why is it not working ?
You are not using Singleton design pattern correctly. Did you notice that you have two JFrame popping up ?
if (!ranOnce)
{
EventQueue.invokeLater(new Runnable()//this call the run method in a separate thread
{
public void run()
{
try
{
// for the current instance of Registration, you are setting
// the reg variable by calling another instance of Registration => thats not the correct way to do a Singleton
reg = new Registration();
reg.setVisible(true);
ranOnce = true;
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
So, let's assume you are calling new Registration() in your main method, you will enter the public Registration() constructor (let's call it instance1) and set the variable reg by calling one more time the constructor new Registration() (instance2) but by this time, ranOnce will be true and so EventQueue.invokeLater will not be called => reg will not be set in instance2 => NullPointerException when clicking on Jbutton in the second frame (the one on the top) (instance2). Clicking on first frame (instance1) button's will hide the second frame (instance2).
How to fix it ?
Use a proper Singleton :
private static final long serialVersionUID = 1L;
private static boolean ranOnce = false;
private JPanel contentPane;
private static Registration reg;
private JTextField userTF;
private JTextField passTF;
private JTextField emailTF;
private LoginProcess lp = new LoginProcess();
private JLabel error;
private JButton cancelBtn;
public static synchronized Registration getRegistration()
{
if(reg == null)
reg = new Registration();
return reg;
}
/**
* Create the frame.
*/
private Registration()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 245, 212);
setLocationRelativeTo(null);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblUsername = new JLabel("Username:");
lblUsername.setBounds(10, 11, 75, 14);
contentPane.add(lblUsername);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setBounds(10, 36, 75, 14);
contentPane.add(lblPassword);
JLabel lblEmail = new JLabel("Email:");
lblEmail.setBounds(10, 61, 75, 14);
contentPane.add(lblEmail);
userTF = new JTextField();
userTF.setBounds(95, 8, 130, 20);
contentPane.add(userTF);
userTF.setColumns(10);
passTF = new JTextField();
passTF.setColumns(10);
passTF.setBounds(95, 33, 130, 20);
contentPane.add(passTF);
emailTF = new JTextField();
emailTF.setColumns(10);
emailTF.setBounds(95, 58, 130, 20);
contentPane.add(emailTF);
error = new JLabel("");
error.setBounds(10, 154, 215, 14);
contentPane.add(error);
JButton regBtn = new JButton("Register");
regBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (!userTF.getText().equals("") || !passTF.getText().equals("") || !emailTF.getText().equals("")) {
try {
if (lp.newUser(userTF.getText(), passTF.getText(), emailTF.getText())) {
setVisible(false);
Main.mainFrame.setVisible(true);
} else {
if (lp.duplicateAccount) {
error.setText("Error: Username already in use.");
}
}
} catch (SQLException e) {
}
}
}
});
regBtn.setBounds(10, 120, 215, 23);
contentPane.add(regBtn);
cancelBtn = new JButton("Cancel");
cancelBtn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
setVisible(false);
}
});
cancelBtn.setBounds(10, 86, 215, 23);
contentPane.add(cancelBtn);
}
public static void main(String[] args)
{
Registration registration = Registration.getRegistration();
registration.setVisible(true);
}
Try setVisible(fasle) instead of reg.setVisible(false)
So I'm starting a new project and I was wondering how can I setup multiple classes for my different JPanels. It looks very messy in one class. Let me show you the example. I would like the JPanel for a menu screen in it's own class.
import java.awt.EventQueue;
public class TakeAwayLogin {
private JFrame frmTakeAwaySystem;
private JTextField textFieldId;
private JPasswordField passwordField;
/**
* Launch the application.
* #return
*/
public void login() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TakeAwayLogin window = new TakeAwayLogin();
window.frmTakeAwaySystem.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public TakeAwayLogin() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmTakeAwaySystem = new JFrame();
frmTakeAwaySystem.setTitle("Take Away System Alpha");
frmTakeAwaySystem.setBounds(100, 100, 450, 300);
frmTakeAwaySystem.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmTakeAwaySystem.getContentPane().setLayout(new CardLayout(0, 0));
final JPanel panelLogin = new JPanel();
frmTakeAwaySystem.getContentPane().add(panelLogin, "name_254735117500687");
panelLogin.setLayout(null);
panelLogin.setVisible(true);
final JLabel lblIncorrect = new JLabel("Incorrect login, try again");
lblIncorrect.setHorizontalAlignment(SwingConstants.CENTER);
lblIncorrect.setFont(new Font("Tahoma", Font.PLAIN, 9));
lblIncorrect.setForeground(Color.RED);
lblIncorrect.setBounds(148, 74, 139, 14);
panelLogin.add(lblIncorrect);
lblIncorrect.setVisible(false);
final JPanel panelPassword = new JPanel();
frmTakeAwaySystem.getContentPane().add(panelPassword, "name_254738265432897");
panelPassword.setLayout(null);
passwordField = new JPasswordField();
passwordField.setBounds(112, 157, 205, 41);
panelLogin.add(passwordField);
passwordField.setHorizontalAlignment(JPasswordField.CENTER);
JButton btnNewButton = new JButton("Lock Application");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
panelPassword.setVisible(false);
panelLogin.setVisible(true);
passwordField.setText("");
textFieldId.disable();
}
});
btnNewButton.setBounds(135, 155, 172, 50);
panelPassword.add(btnNewButton);
panelPassword.setVisible(false);
JButton btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String login = textFieldId.getText();
char[] pass = passwordField.getPassword();
String p = new String(pass);
String password = "pass";
if (login.equalsIgnoreCase("milan") && p.equals(password)) {
panelPassword.setVisible(true);
panelLogin.setVisible(false);
}else {
lblIncorrect.setVisible(true);
}
}
});
btnLogin.setBounds(160, 209, 97, 41);
panelLogin.add(btnLogin);
textFieldId = new JTextField();
textFieldId.setBounds(112, 88, 205, 43);
panelLogin.add(textFieldId);
textFieldId.setColumns(10);
textFieldId.setHorizontalAlignment(JTextField.CENTER);
JLabel lblId = new JLabel("Enter the business login:");
lblId.setHorizontalAlignment(SwingConstants.CENTER);
lblId.setBounds(112, 63, 205, 14);
panelLogin.add(lblId);
JLabel lblEnterYourPassword = new JLabel("Enter your password");
lblEnterYourPassword.setHorizontalAlignment(SwingConstants.CENTER);
lblEnterYourPassword.setBounds(148, 142, 139, 14);
panelLogin.add(lblEnterYourPassword);
JPanel panelPizza = new JPanel();
frmTakeAwaySystem.getContentPane().add(panelPizza, "name_254741096954780");
}
}
So help would be great.
Thanks very much.
I don't know why creating a second class would be necessary. If you just want the code to look less messy, then add comment separators between Panels or something to that effect. I think that splitting up the Panels into their own classes would be just cause you to have to write more calls to be able to create the same functionality. But if you must, then make a class within your initiate class and work from there.
Simplifying, you want something like:
public class MyMainJFrame extends JFrame{
private JPanel panel1 = new MyFooPanel();
private JPanel panel2 = new MyBarPanel();
public MyMainPanel(){
initialize();
}
void initialize(){
//init the JFrame
this.setTitle("Take Away System Alpha");
this.setBounds(100, 100, 450, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new CardLayout(0, 0));
//and add the panels
this.add(panel1);
this.add(panel2);
}
}
// a file for each one
public class MyFooPanel extends JPanel{
private JButton button;
//... add components and logic
}
public class MyBarPanel extends JPanel{
private JTextField field;
//... add components and logic
}
If you want to use specific methods for each custom panel, then change the type of variable for the same name of the custom class.
Why would the order of Tabs in a JTabbedPane affect if the content of the tab works as expected?
I am writing my first advanced application and am having some trouble with my JTabbedPane.
Here's what I have:
public ProjectTracker() {
initialize();
newJobTab();
newUpdateTab();
newReportsTab();
}
newJobTab(), newUpdateTab() and newReportsTab() are placed into a JTabbed pane within the initialize() method. Each create an instance of a GUI class that I made. It basically has a bunch of Text fields, and comboboxes, etc. and they interact with a database to either populate the fields or collect info from the fields.
The functionality of the buttons on the tab are the main difference between the three. Individually, each tab works as I would expect it to. When I place them in the Tabbed pane, only the third tab works properly. If I switch around the order, it is the same deal. Whichever one is the third tab is the only one that functions the way I want.
Here is my revision to my original post...now with code.
public class SampleTracker {
private JFrame frmProjectTracker;
private JTabbedPane tabbedPane;
public String Title;
SampleTJV newJobPanel;
SampleTJV updatePanel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SampleTracker window = new SampleTracker();
window.frmProjectTracker.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public SampleTracker() {
initialize();
newJobTab();
newUpdateTab();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmProjectTracker = new JFrame();
frmProjectTracker.setBounds(100, 100, 662, 461);
frmProjectTracker.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmProjectTracker.getContentPane().setLayout(new FormLayout(new ColumnSpec[] {
ColumnSpec.decode("662px"),},
new RowSpec[] {
RowSpec.decode("50px"),
RowSpec.decode("389px"),}));
tabbedPane = new JTabbedPane(JTabbedPane.TOP);
frmProjectTracker.getContentPane().add(tabbedPane, "1, 2, fill, fill");
}
private void newJobTab(){
newJobPanel = new SampleTJV();
newJobPanel.UpdateButton.setText("Enter Job");
tabbedPane.addTab("Enter New Job", null, newJobPanel, null);
newJobPanel.UpdateButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
newJobPanel.collectInfo();
Title = newJobPanel.Title;
//Here the connection to DB is made and the Title is written to DB
newJobPanel.newJobField.setText(Title);
}
});
}
private void newUpdateTab(){
updatePanel = new SampleTJV();
newJobPanel.UpdateButton.setText("Update Job");
tabbedPane.addTab("Update Job", null, updatePanel, null);
updatePanel.UpdateButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
updatePanel.collectInfo();
Title = updatePanel.Title;
updatePanel.updateJobField.setText(Title);
}
});
}
}
public class SampleTJV extends JPanel {
private static final long serialVersionUID = 1L;
public static JTextField TitleField;
public String Title;
public JButton UpdateButton;
public JTextField newJobField;
public JTextField updateJobField;
/**
* Create the panel.
*/
public SampleTJV() {
setLayout(null);
TitleField = new JTextField();
TitleField.setColumns(10);
TitleField.setBounds(109, 6, 134, 28);
add(TitleField);
newJobField = new JTextField();
newJobField.setBounds(171, 79, 134, 28);
add(newJobField);
newJobField.setColumns(10);
UpdateButton = new JButton("Update Job");
UpdateButton.setBounds(267, 7, 112, 29);
add(UpdateButton);
JLabel lblNewJobResult = new JLabel("New Job Result");
lblNewJobResult.setBounds(47, 85, 112, 16);
add(lblNewJobResult);
JLabel lblUpdateJobResult = new JLabel("Update Job Result");
lblUpdateJobResult.setBounds(47, 125, 112, 16);
add(lblUpdateJobResult);
updateJobField = new JTextField();
updateJobField.setColumns(10);
updateJobField.setBounds(171, 119, 134, 28);
add(updateJobField);
}
public void collectInfo(){
Title = TitleField.getText();
}
}
The following is a copy error:
private void newUpdateTab(){
updatePanel = new SampleTJV();
newJobPanel.UpdateButton.setText("Update Job");
newJobPanel there is probably not intended.
Also wrong is a static GUI field:
static JTextField TitleField;
The problem was exactly what JB Nizet guessed earlier. It was static methods and variables which should have been instance variables.
In my sample code, SampleTJV, if you remove the word static from
public static JTextField TitleField;
the program works exactly as intended.