I have a login and a register panel and a window to hold all the panels. What I am trying to do is to go to the login panel when the register button is pressed. But it does not work. The method that I use would work if the login panel is inside the window but when it is in its own class it doesn't. Can someone please let me know how to do this?
Here is my code for the Window
package userInterface;
import java.awt.*;
import java.awt.EventQueue;
import java.sql.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import company.CompanySys;
import javax.swing.*;
import java.awt.CardLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
public class FrontEnd {
/**
* Variables
*/
// System
CompanySys sys = CompanySys.getSystem();
private static FrontEnd front = new FrontEnd();
private JFrame frame;
private final JLayeredPane layeredPane = new JLayeredPane();
public final RegisterPanel registerPan = new RegisterPanel();
public final LoginPanel loginPan = new LoginPanel();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FrontEnd window = new FrontEnd();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
private FrontEnd() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
this.setFrame();
this.setLayout();
this.addPanels();
}
/**
* Setting up the main frame
*/
private void setFrame() {
frame = new JFrame();
frame.setBounds(100, 100, 900, 700);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
layeredPane.setBounds(0, 0, 900, 700);
frame.getContentPane().add(layeredPane);
layeredPane.setLayout(new CardLayout(0, 0));
}
/**
* Setting Layout
*/
public void setLayout() {
// frame.getContentPane().add(layeredPane, "name_2578740971832500");
// layeredPane.setLayout(new CardLayout(0, 0));
}
public void SetSizeandLocation() {
this.registerPan.setBounds(10, 10, 900, 700);
layeredPane.setLayer(loginPan, 0);
this.loginPan.setBounds(10, 10, 900, 700);
}
/**
* Set visibility of the components
*/
private void setVisibility() {
// this.registerPan.setVisible(true);
// this.loginPan.setVisible(true);
}
/**
* Adding panels to the window
*/
private void addPanels() {
layeredPane.add(registerPan);
layeredPane.add(loginPan);
}
public static FrontEnd getFront() {
return front;
}
/**
* Switching Panels
* #param panel
*/
public void switchPanels(JPanel panel) {
layeredPane.removeAll();
layeredPane.add(panel);
layeredPane.repaint();
layeredPane.revalidate();
}
public LoginPanel getLoginPan() {
return this.loginPan;
}
}
Here is the code for Register Panel
package userInterface;
import company.*;
import javax.swing.*;
import java.awt.event.*;
public class RegisterPanel extends JPanel implements ActionListener{
/**
* Variables
*/
// System
CompanySys sys = CompanySys.getSystem();
FrontEnd front = FrontEnd.getFront();
// Input fields
private JTextField usernameTextField = new JTextField();
private JPasswordField passwordField1 = new JPasswordField();
private JPasswordField passwordField2 = new JPasswordField();
// Labels
private JLabel usernameLabel = new JLabel("Username");
private JLabel password1Label = new JLabel("Password");
private JLabel password2Label = new JLabel("Password");
// Buttons
private JButton registerButton = new JButton("REGISTER");
private JButton cancelButton = new JButton("CANCEL");
private JButton haveAccount = new JButton("Already have an account? Login");
private JButton clearButton = new JButton("CLEAR");
// Others
private JCheckBox showPasswordCheckBox = new JCheckBox("Show Password");
/**
* Create the panel.
*/
public RegisterPanel() {
setLayout(null);
this.addComponents();
this.setSizeandLocations();
this.addActionEvent();
}
/**
* Methods
*/
// Set size and location of the components
public void setSizeandLocations() {
// Labels
usernameLabel.setBounds(312, 106, 64, 14);
password1Label.setBounds(324, 175, 64, 14);
password2Label.setBounds(312, 237, 64, 14);
// Input Fields
usernameTextField.setBounds(493, 103, 96, 20);
passwordField1.setBounds(493, 173, 97, 17);
passwordField2.setBounds(494, 234, 96, 20);
passwordField1.setEchoChar('*');
passwordField2.setEchoChar('*');
//Buttons
registerButton.setBounds(337, 301, 89, 23);
cancelButton.setBounds(479, 301, 89, 23);
haveAccount.setBounds(366, 363, 196, 23);
clearButton.setBounds(606, 301, 89, 23);
// Others
showPasswordCheckBox.setBounds(493, 261, 141, 23);
}
// Add all components to the panel
public void addComponents() {
// Add Labels
add(usernameLabel);
add(password1Label);
add(password2Label);
// Add input fields
add(usernameTextField);
add(passwordField1);
add(passwordField2);
// Add Buttons
add(registerButton);
add(cancelButton);
add(haveAccount);
add(clearButton);
// Others
add(showPasswordCheckBox);
}
/**
* Adding Action listener
*/
public void addActionEvent() {
this.registerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
front.switchPanels(front.getLoginPan());
}
});
this.cancelButton.addActionListener(this);
this.haveAccount.addActionListener(this);
this.clearButton.addActionListener(this);
this.showPasswordCheckBox.addActionListener(this);
}
/**
* Main method of the panel
* #param args
*/
public static void main(String args[]) {
RegisterPanel frame = new RegisterPanel();
frame.setVisible(true);
frame.setBounds(10, 10, 900, 500);
}
/**
* Adding the functionality to the components
*/
#Override
public void actionPerformed(ActionEvent e) {
String usr = this.usernameTextField.getText();
String pass1 = String.valueOf(this.passwordField1.getPassword());
String pass2 = String.valueOf(this.passwordField2.getPassword());
// if (e.getSource() == this.registerButton) {
// if (sys.register(usr, pass1, pass2)) {
// // JOptionPane.showConfirmDialog(null, "Success", getName(), JOptionPane.DEFAULT_OPTION);
//
// front.switchPanels(front.getLoginPan());
// }
// else {
// JOptionPane.showConfirmDialog(null, "fail", getName(), JOptionPane.DEFAULT_OPTION);
// }
// }
if (e.getSource() == this.cancelButton) {
}
else if (e.getSource() == this.haveAccount) {
}
else if (e.getSource() == this.showPasswordCheckBox) {
if(this.showPasswordCheckBox.isSelected()) {
this.passwordField1.setEchoChar((char) 0);
this.passwordField2.setEchoChar((char) 0);
}
else {
this.passwordField1.setEchoChar('*');
this.passwordField2.setEchoChar('*');
}
}
else if (e.getSource() == this.clearButton) {
this.passwordField1.setText("");
this.passwordField2.setText("");
this.usernameTextField.setText("");
}
}
}
Here is code for login panel
package userInterface;
import company.CompanySys;
import javax.swing.*;
import java.awt.event.*;
public class LoginPanel extends JPanel implements ActionListener{
/**
* Variables
*/
// System
CompanySys sys = CompanySys.getSystem();
// Fields
private JTextField userNameTextField = new JTextField();;
private JPasswordField passwordField = new JPasswordField();;
// Labels
JLabel userNameLabel = new JLabel("Username");
JLabel passwordLabel = new JLabel("Password");
// Buttons
JButton cancelButton = new JButton("CANCEL");
JButton loginButton = new JButton("LOGIN");
JButton noAccountButton = new JButton("Don't have an acount? register");
JButton clearButton = new JButton("CLEAR");
// Others
JCheckBox showPassCheckBox = new JCheckBox("Show Password");
/**
* Constructor
*/
public LoginPanel() {
setLayout(null);
this.setSizeAndLocation();
this.addComponent();
this.addAction();
}
/**
* Setting size and location of the components
*/
public void setSizeAndLocation() {
// Labels
userNameLabel.setBounds(97, 52, 69, 14);
passwordLabel.setBounds(97, 88, 48, 14);
// TextFields
passwordField.setBounds(197, 85, 103, 20);
userNameTextField.setBounds(197, 49, 96, 20);
// Buttons
clearButton.setBounds(325, 146, 89, 23);
noAccountButton.setBounds(85, 196, 208, 23);
cancelButton.setBounds(209, 146, 89, 23);
loginButton.setBounds(85, 146, 89, 23);
// Others
showPassCheckBox.setBounds(197, 116, 130, 23);
}
/**
* Adding components to the Panel
*/
public void addComponent() {
// Labels
this.add(userNameLabel);
this.add(passwordLabel);
// TextFields
this.add(userNameTextField);
this.add(passwordField);
// Buttons
this.add(loginButton);
this.add(cancelButton);
this.add(noAccountButton);
this.add(clearButton);
// Others
this.add(showPassCheckBox);
}
/**
* Adding ActionListener to the interactive components
*/
public void addAction() {
// Buttons
this.clearButton.addActionListener(this);
this.cancelButton.addActionListener(this);
this.loginButton.addActionListener(this);
this.noAccountButton.addActionListener(this);
// Others
this.showPassCheckBox.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
}
public static void main(String args[]) {
LoginPanel frame = new LoginPanel();
frame.setVisible(true);
frame.setBounds(10, 10, 900, 700);
}
}
I have tried other ways too but it doesnt work!
Related
I am making a program which will open a class GUI called "Menu" when correct login info is put into a text field password field and a button called "login" is pressed. The problem is that the Menu window will open blank, not displaying what I have programmed into the Menu.
This is my code for Login class,
package ems;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import javax.swing.JPanel;
import java.awt.SystemColor;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Login extends JFrame implements ActionListener{
private JFrame loginFrame;
private JTextField usernameField;
private JPasswordField passwordField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login window = new Login();
window.loginFrame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Login() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
loginFrame = new JFrame();
loginFrame.setTitle("Login");
loginFrame.setBounds(100, 100, 450, 300);
loginFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
loginFrame.getContentPane().setLayout(null);
JLabel lblUsername = new JLabel("Username");
lblUsername.setBounds(112, 116, 74, 16);
loginFrame.getContentPane().add(lblUsername);
JLabel lblPassword = new JLabel("Password");
lblPassword.setBounds(112, 165, 74, 16);
loginFrame.getContentPane().add(lblPassword);
usernameField = new JTextField();
usernameField.setBounds(198, 110, 134, 28);
loginFrame.getContentPane().add(usernameField);
usernameField.setColumns(10);
passwordField = new JPasswordField();
passwordField.setBounds(198, 159, 134, 28);
loginFrame.getContentPane().add(passwordField);
JButton btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String uname = usernameField.getText();
String pword = passwordField.getText();
if (uname.equals("test") && pword.equals("test")){
JOptionPane.showMessageDialog(loginFrame, "Login successful.");
loginFrame.setVisible(false);
Menu menu = new Menu ();
menu.setVisible (true);
}else{
JOptionPane.showMessageDialog(loginFrame, "Login unsuccessful.");
}
}
});
btnLogin.setBounds(238, 210, 90, 30);
loginFrame.getContentPane().add(btnLogin);
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
btnExit.setBounds(108, 210, 90, 30);
loginFrame.getContentPane().add(btnExit);
JPanel panel = new JPanel();
panel.setBackground(new Color(192, 192, 192));
panel.setBounds(91, 86, 258, 163);
loginFrame.getContentPane().add(panel);
JLabel lblLoginToThe = new JLabel("LOGIN TO THE ELECTRICITY MONITORING SYSTEM");
lblLoginToThe.setForeground(new Color(255, 255, 255));
lblLoginToThe.setFont(new Font("Arial", Font.BOLD, 16));
lblLoginToThe.setBounds(26, 23, 418, 16);
loginFrame.getContentPane().add(lblLoginToThe);
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(46, 139, 87));
panel_1.setBounds(0, 0, 450, 63);
loginFrame.getContentPane().add(panel_1);
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
This is the code for the Menu class,
package ems;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import ems.Login;
public class Menu extends Login implements ActionListener{
private JFrame menuFrame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Menu window = new Menu();
window.menuFrame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Menu() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
menuFrame = new JFrame();
menuFrame.setTitle("Menu");
menuFrame.setBounds(100, 100, 450, 300);
menuFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
menuFrame.getContentPane().setLayout(null);
JLabel lblLoginToThe = new JLabel("THE ELECTRICITY MONITORING SYSTEM");
lblLoginToThe.setForeground(new Color(255, 255, 255));
lblLoginToThe.setFont(new Font("Arial", Font.BOLD, 16));
lblLoginToThe.setBounds(64, 22, 331, 16);
menuFrame.getContentPane().add(lblLoginToThe);
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(46, 139, 87));
panel_1.setBounds(0, 0, 450, 63);
menuFrame.getContentPane().add(panel_1);
JButton btnLogout = new JButton("Logout");
btnLogout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
menuFrame.setVisible(false);
Login login = new Login ();
login.setVisible(true);
}
});
btnLogout.setBounds(307, 222, 117, 29);
menuFrame.getContentPane().add(btnLogout);
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
btnExit.setBounds(10, 222, 117, 29);
menuFrame.getContentPane().add(btnExit);
}
}
Both of these classes are under a package called ems.
I am very new to programming and help would be greatly appreciated.
Thank you
You are creating another JFrame inside of Login and Menu, which is wrong, theres also no need that Menu extends Login
Here is the fixed version for Login:
package ems;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Login extends JFrame {
private static final long serialVersionUID = 1L;
private JTextField usernameField;
private JPasswordField passwordField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login window = new Login();
window.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Login() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
this.setTitle("Login");
this.setBounds(100, 100, 450, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().setLayout(null);
JLabel lblUsername = new JLabel("Username");
lblUsername.setBounds(112, 116, 74, 16);
this.getContentPane().add(lblUsername);
JLabel lblPassword = new JLabel("Password");
lblPassword.setBounds(112, 165, 74, 16);
this.getContentPane().add(lblPassword);
usernameField = new JTextField();
usernameField.setBounds(198, 110, 134, 28);
this.getContentPane().add(usernameField);
usernameField.setColumns(10);
passwordField = new JPasswordField();
passwordField.setBounds(198, 159, 134, 28);
this.getContentPane().add(passwordField);
JButton btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String uname = usernameField.getText();
String pword = passwordField.getText();
if (uname.equals("test") && pword.equals("test")){
JOptionPane.showMessageDialog(Login.this, "Login successful.");
Login.this.setVisible(false);
Menu menu = new Menu ();
menu.setVisible (true);
}else{
JOptionPane.showMessageDialog(Login.this, "Login unsuccessful.");
}
}
});
btnLogin.setBounds(238, 210, 90, 30);
this.getContentPane().add(btnLogin);
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
btnExit.setBounds(108, 210, 90, 30);
this.getContentPane().add(btnExit);
JPanel panel = new JPanel();
panel.setBackground(new Color(192, 192, 192));
panel.setBounds(91, 86, 258, 163);
this.getContentPane().add(panel);
JLabel lblLoginToThe = new JLabel("LOGIN TO THE ELECTRICITY MONITORING SYSTEM");
lblLoginToThe.setForeground(new Color(255, 255, 255));
lblLoginToThe.setFont(new Font("Arial", Font.BOLD, 16));
lblLoginToThe.setBounds(26, 23, 418, 16);
this.getContentPane().add(lblLoginToThe);
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(46, 139, 87));
panel_1.setBounds(0, 0, 450, 63);
this.getContentPane().add(panel_1);
}
}
And for Menu
package ems;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Menu extends JFrame{
private static final long serialVersionUID = 1L;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Menu window = new Menu();
window.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Menu() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
this.setTitle("Menu");
this.setBounds(100, 100, 450, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().setLayout(null);
JLabel lblLoginToThe = new JLabel("THE ELECTRICITY MONITORING SYSTEM");
lblLoginToThe.setForeground(new Color(255, 255, 255));
lblLoginToThe.setFont(new Font("Arial", Font.BOLD, 16));
lblLoginToThe.setBounds(64, 22, 331, 16);
this.getContentPane().add(lblLoginToThe);
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(46, 139, 87));
panel_1.setBounds(0, 0, 450, 63);
this.getContentPane().add(panel_1);
JButton btnLogout = new JButton("Logout");
btnLogout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Menu.this.setVisible(false);
Login login = new Login ();
login.setVisible(true);
}
});
btnLogout.setBounds(307, 222, 117, 29);
this.getContentPane().add(btnLogout);
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
btnExit.setBounds(10, 222, 117, 29);
this.getContentPane().add(btnExit);
}
}
Still looking, but:
menuFrame.getContentPane().add(lblLoginToThe);
The content pane isn't a container, you can't add multiple things to it. You need to put everything in a panel (note panel != pane) and then add one panel to the content pane.
Also don't call setBounds() directly, use a layout manager. That's another reason you could be seeing nothing: all your components are drawn outside of the window or some other similar error. Layout managers will fix that.
EDIT: And as Edwardth said you have a habit of declaring your classes to be a thing (like JFrame) and then creating a second JFrame inside the initialize method. Don't do that.
public class Login extends JFrame implements ActionListener{
...
private void initialize() {
loginFrame = new JFrame(); // BAD!
The JFrame was already made when you declared that Login extends JFrame you don't need a second frame.
Edwardth got the answer before me so go ahead and study his example and then mark his answer correct. Ask in the comments below if you have further questions.
Here's my example of the Login class, without the setBounds().
class Login extends JFrame implements ActionListener{
private JTextField usernameField;
private JPasswordField passwordField;
/**
* Create the application.
*/
public Login() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
setTitle("Login");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel lblUsername = new JLabel("Username");
JLabel lblPassword = new JLabel("Password");
usernameField = new JTextField();
usernameField.setColumns(10);
passwordField = new JPasswordField();
JPanel loginPanel = new JPanel( new GridLayout( 0,2 ) );
loginPanel.add( lblUsername );
loginPanel.add( usernameField );
loginPanel.add( lblPassword );
loginPanel.add( passwordField );
JButton btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String uname = usernameField.getText();
String pword = passwordField.getText();
if (uname.equals("test") && pword.equals("test")){
JOptionPane.showMessageDialog( Login.this, "Login successful.");
setVisible(false);
Menu menu = new Menu ();
menu.setVisible (true);
}else{
JOptionPane.showMessageDialog( Login.this, "Login unsuccessful.");
}
}
});
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
JPanel panel = new JPanel();
panel.setBackground(new Color(192, 192, 192));
panel.add( btnLogin );
panel.add( btnExit );
JLabel lblLoginToThe = new JLabel("LOGIN TO THE ELECTRICITY MONITORING SYSTEM");
lblLoginToThe.setForeground(new Color(255, 255, 255));
lblLoginToThe.setFont(new Font("Arial", Font.BOLD, 16));
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(46, 139, 87));
panel_1.add( lblLoginToThe );
Box topBox = Box.createVerticalBox();
topBox.add( panel_1 );
topBox.add( loginPanel );
topBox.add( panel );
add( topBox );
pack();
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
And the Main class:
class Menu extends JFrame {
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Menu window = new Menu();
window.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Menu() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
setTitle("Menu");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Box topBox = Box.createVerticalBox();
JLabel lblLoginToThe = new JLabel("THE ELECTRICITY MONITORING SYSTEM");
lblLoginToThe.setForeground(new Color(255, 255, 255));
lblLoginToThe.setFont(new Font("Arial", Font.BOLD, 16));
topBox.add( lblLoginToThe ); // **********
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(46, 139, 87));
topBox.add( panel_1 ); // *************
JButton btnLogout = new JButton("Logout");
btnLogout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Menu.this.setVisible(false);
Login login = new Login ();
login.setVisible(true);
}
});
topBox.add( btnLogout ); //****************
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
topBox.add( btnExit );
add( topBox );
pack();
}
}
I'm trying to access the int myInt in this GUI form class from another class. The method does pass the input variable to myInt properly but I have not been able to make it visible to the other java file. I have been reading about scope and class declarations and have been able to muddle along up until now, but I am doing something wrong here. Nothing I have tried has worked.
package com.jdividend.platform.allocation;
import com.ib.client.*;
import com.jdividend.platform.model.*;
import com.jdividend.platform.trader.*;
import com.jdividend.platform.util.*;
import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
/**
* Dialog to show the account size allowed info.
*/
public class AllocationDialog extends JDialog {
/* inner class to define the "about" model */
public static class AllocationTableModel extends TableDataModel {
private AllocationTableModel() {
String[] aboutSchema = {"Property", "Value"};
setSchema(aboutSchema);
}
}
public AllocationDialog(JFrame parent) {
super(parent);
init();
pack();
setLocationRelativeTo(parent);
setVisible(true);
}
public void init() {
setModal(true);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setTitle("Allocation - JDividend");
JPanel contentPanel = new JPanel();
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(new BorderLayout(0, 0));
{
JPanel panel = new JPanel();
contentPanel.add(panel, BorderLayout.CENTER);
panel.setLayout(null);
JPanel panel_1 = new JPanel();
panel_1.setBounds(84, 146, 274, 19);
panel.add(panel_1);
JLabel lblNewLabel = new JLabel("Total account cash and margin that");
panel_1.add(lblNewLabel);
JPanel panel_2 = new JPanel();
panel_2.setBounds(84, 163, 274, 19);
panel.add(panel_2);
JLabel lblJdividendIsAllowed = new JLabel("JDividend is allowed to trade with.");
panel_2.add(lblJdividendIsAllowed);
JFormattedTextField formattedTextField = new JFormattedTextField();
formattedTextField.setBounds(172, 189, 100, 20);
panel.add(formattedTextField);
JButton btnOk = new JButton("OK");
btnOk.setBounds(121, 221, 89, 23);
panel.add(btnOk);
btnOk.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
try {
int myInt = Integer.parseInt(formattedTextField.getText());
System.out.println(myInt);
//do some stuff
}
catch (NumberFormatException ex) {
System.out.println("Not a number");
//do you want
}
JButton btnCancel = new JButton("Cancel");
btnCancel.setBounds(238, 220, 89, 23);
panel.add(btnCancel);
formattedTextField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JButton button = new JButton("OK");
}
});
}
});
}
String serverVersion = "Disconnected from server";
Trader trader = Dispatcher.getInstance().getTrader();
if (trader != null) {
int version = trader.getAssistant().getServerVersion();
if (version != 0) {
serverVersion = String.valueOf(version);
}
}
TableDataModel aboutModel = new AllocationTableModel();
getContentPane().setPreferredSize(new Dimension(450, 400));
Properties properties = System.getProperties();
Enumeration<?> propNames = properties.propertyNames();
while (propNames.hasMoreElements()) {
String key = (String) propNames.nextElement();
String value = properties.getProperty(key);
String[] row = {key, value};
aboutModel.addRow(row);
}
}
}
myInt should be declared inside the class, but outside of any method implementations:
public class AllocationDialog extends JDialog {
public int myInt;
// ...
}
I m creating a GUI in java and would like to use a JTextArea, however I am having a lot of trouble adding it to the frame. How would I go about creating a text Area and then using it to read text or display text?
Here is my GUI code so far:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class addMemoUI extends JFrame {
JFrame frame = new JFrame();
/**
* Create the application.
*/
public addMemoUI() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame.getContentPane().setBackground(new Color(255, 255, 255));
frame.getContentPane().setLayout(null);
JButton button = new JButton("Create");
button.setBackground(new Color(100, 149, 237));
button.setBounds(135, 350, 130, 50);
frame.getContentPane().add(button);
JLabel lblMemos = new JLabel("MEMOS");
lblMemos.setForeground(new Color(100, 149, 237));
lblMemos.setFont(new Font("Moire", Font.BOLD, 30));
lblMemos.setBounds(22, 21, 234, 37);
frame.getContentPane().add(lblMemos);
JButton button_1 = new JButton("Cancel");
button_1.setBackground(new Color(100, 149, 237));
button_1.setBounds(5, 350, 130, 50);
frame.getContentPane().add(button_1);
frame.setBounds(100, 100, 270, 400);
frame.setUndecorated(true); //REMOVES MENU BAR
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton btnExit = new JButton("");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MemoUI window = new MemoUI();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
Thanks very much :)
Here is example for how to use JTextArea. You can set, get or append text. You can find the others by google.
public class Example {
private JTextArea jtextbox;
private void initialize() {
JFrame frm = new JFrame();
:
JScrollPane scroll = new JScrollPane();
jtextbox= new JTextArea();
scroll.setViewportView(jtextbox); // add scroll panel
jtextbox.setTabSize(4);
jtextbox.setLineWrap(true);
jtextbox.setBackground(SystemColor.window);
}
private void setText(String text) {
jtextbox.append(text); // or setText(text)
}
private String getText() {
return jtextbox.getText();
}
}
A software component is required which allows to find a given word in a given passage, whenever the component find the desired word in the passage the components will invoke all the listener that are attached to it that it has find the desired word.
This component must be used from a Swing UI based application showing user a text field to take a word and a text area for passage. There must be a label which will update its value showing count that how many times the given word has been found within the given passage.
this is my code it's displya gui but count field is not changed or set.
import java.awt.EventQueue;
public class compomentex implements ActionListener{
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
private JTextArea textArea;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
compomentex window = new compomentex();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public interface wordsearcherinterface
{
public void wordsearch();
}
public class wordsearcher implements wordsearcherinterface
{
public String word;
public String paragraph;
public void addwordsearch(wordsearcherinterface obj)
{
obj.wordsearch();
}
public void wordsearch()
{
//if(event.getSource()==Check)
String word;
String Words;
String [] Words2;
int disp=0;
word=textField.getText();
Words=textArea.getText();
Words2=Words.split(" ");
for(int i=0;i<Words2.length;i++)
{
if(Words2[i].equals(word))
{
disp++;
}
}
String show;
show=disp+"";
textField_1.setText(show);
if(disp==0)
{
JOptionPane.showMessageDialog(null, "The Word is not present int Passage");
}
}
}
* Create the application.
public compomentex() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblWord = new JLabel("WORD");
lblWord.setBounds(29, 81, 46, 14);
frame.getContentPane().add(lblWord);
textField = new JTextField();
textField.setBounds(121, 78, 86, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
JLabel lblPassage = new JLabel("PASSAGE");
lblPassage.setBounds(29, 143, 46, 14);
frame.getContentPane().add(lblPassage);
JTextArea textArea = new JTextArea();
textArea.setBounds(97, 161, 196, 90);
frame.getContentPane().add(textArea);
JButton btnCheck = new JButton("CHECK");
btnCheck.setBounds(326, 213, 98, 23);
frame.getContentPane().add(btnCheck);
JLabel lblSeeker = new JLabel("SEEKER");
lblSeeker.setBounds(161, 11, 46, 14);
frame.getContentPane().add(lblSeeker);
JLabel lblCount = new JLabel("COUNT");
lblCount.setBounds(349, 81, 46, 14);
frame.getContentPane().add(lblCount);
textField_1 = new JTextField();
textField_1.setBounds(325, 106, 86, 20);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
Thanks in advance
There are lots of issues in your code. I have mentioned corrected code below. Please correct.
First - actionPerformed method is empty.
#Override
public void actionPerformed(ActionEvent arg0) {
new wordsearcher().wordsearch();
}
Second - instance variable textArea is not initialized.
textArea = new JTextArea();
Third - ActionListener is not added on button btnCheck
btnCheck.addActionListener(this);
This is the source code for my calculator that i am building in eclipse windowbuilder, i am trying to make two textFields read input and output the area for a simple rectangle, i can type the numbers into the boxes however the numbers do not compute and i am at a loss as to what i could be doing wrong, please critique my code and let me know why it isn't working. Thank you
*Edit, i have removed and changed a few things and now the Answer box displays 0.0 and nothing else
import java.awt.EventQueue;
public class GUI {
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUI window = new GUI();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public GUI() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 694, 499);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
frame.getContentPane().add(tabbedPane, BorderLayout.CENTER);
JPanel panel = new JPanel();
tabbedPane.addTab("New tab", null, panel, null);
panel.setLayout(null);
JLabel lblInputBase = new JLabel("Input Base");
lblInputBase.setBounds(0, 0, 57, 39);
panel.add(lblInputBase);
textField = new JTextField();
textField.setBounds(0, 28, 86, 20);
panel.add(textField);
textField.setColumns(10);
double value = Double.parseDouble(textField.getText());
JLabel lblInputHeight = new JLabel("Input Height");
lblInputHeight.setBounds(0, 212, 68, 20);
panel.add(lblInputHeight);
textField_1 = new JTextField();
textField_1.setBounds(0, 230, 86, 20);
panel.add(textField_1);
textField_1.setColumns(10);
double value_1 = Double.parseDouble(textField_1.getText());
double Area = value*value_1;
String finalArea = Double.toString(Area);
JLabel lblArea = new JLabel("Area:");
lblArea.setBounds(244, 119, 75, 68);
panel.add(lblArea);
textField_2 = new JTextField();
textField_2.setBounds(273, 143, 86, 20);
panel.add(textField_2);
textField_2.setColumns(10);
textField_2.setEditable(false);
textField_2.setText(finalArea);
}
}
Your code is really confusing, but here are some problems that I found:
double value = Double.parseDouble(textField.getText());
This is being run before the user has any chance to even look at the gui. textField.getText() will return an empty string here, and the parseDouble method will always throw a NumberFormatException when the program is run, as it does not consider an empty string to be a valid number format.
double Area = Double.parseDouble(value)*Double.parseDouble(value_1);
Here, the variable value is already a double and does not need to be parsed, and the variable value_1 doesn't exist.
Where you meant to assign an actionListener to textField_1, you assigned a second one to textField.
Overall, it seems that all your calculation logic is being run in your initialize() method, and this means that it is only being run once. You'll want your math to be run whenever one of the text fields is updated.
Your field names are horribly confusing. Your textField variable names should give some indication of their function, like areaTextField, baseTextField, heightTextField.
Here is a modification of your code that seems to function as you intended yours to function. Note the addition of a calculate() method that is called by the action listeners that will find the area and display it, or display NaN (Not a Number) if either of the input fields are not valid numbers. All of your GUI code is retained as is, excepting the renaming of the text field variables.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
public class GUI {
private JFrame frame;
private JTextField baseTextField;
private JTextField heightTextField;
private JTextField areaTextField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUI window = new GUI();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public GUI() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 694, 499);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
frame.getContentPane().add(tabbedPane, BorderLayout.CENTER);
JPanel panel = new JPanel();
tabbedPane.addTab("New tab", null, panel, null);
panel.setLayout(null);
JLabel lblInputBase = new JLabel("Input Base");
lblInputBase.setBounds(0, 0, 57, 39);
panel.add(lblInputBase);
baseTextField = new JTextField();
baseTextField.setBounds(0, 28, 86, 20);
panel.add(baseTextField);
baseTextField.setColumns(20);
baseTextField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
calculate();
}
});
JLabel lblInputHeight = new JLabel("Input Height");
lblInputHeight.setBounds(0, 212, 68, 20);
panel.add(lblInputHeight);
heightTextField = new JTextField();
heightTextField.setBounds(0, 230, 86, 20);
panel.add(heightTextField);
heightTextField.setColumns(20);
heightTextField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
calculate();
}
});
JLabel lblArea = new JLabel("Area:");
lblArea.setBounds(244, 119, 75, 68);
panel.add(lblArea);
areaTextField = new JTextField();
areaTextField.setBounds(273, 143, 86, 20);
panel.add(areaTextField);
areaTextField.setColumns(20);
areaTextField.setEditable(false);
}
private void calculate() {
try {
double base = Double.parseDouble(baseTextField.getText());
double height = Double.parseDouble(heightTextField.getText());
double area = base * height;
areaTextField.setText(String.format("%.4f", area));
} catch (NumberFormatException e) {
areaTextField.setText("NaN");
}
}
}
Note that you need to hit the enter key in one of the two fields to update the area field. That is what it takes to trigger the ActionListener for a JTextField.