calling an instance variable obtained from an actionperformed in another JPanel - java

I have created a JFrame with cardLayout and the first visible JPanel has a Jbutton that I have added an action Listener to perform an action. The action creates a String variable 'hhhhh' that I want to use in another JPanel. This is what I have problem doing.
Class 1
import java.awt.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class NHome extends JFrame{
JPanel Bucket= new JPanel(), Start= new JPanel(), Cashier = new csView(), Manager = new JPanel();
JButton stbtn= new JButton("Start"), mnbtn= new JButton("Manager"), csbtn= new JButton("Cashier");
CardLayout cl= new CardLayout();
private final JTextField textField = new JTextField();
private JPasswordField passwordField;
public NHome() {
textField.setBounds(322, 141, 158, 31);
textField.setColumns(10);
Bucket.setLayout(cl);
Bucket.add(Start, "1");
Bucket.add(Cashier, "2");
Bucket.add(Manager, "3");
Start.setLayout(null);
stbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
cl.show(Bucket, "2");
/*
* I want to use this value of this String in the another class (csView)
*/
String hhhhh=new String("Peter");
System.out.println(hhhhh);
}
});
stbtn.setBounds(353, 245, 76, 23);
Start.add(stbtn);
Start.add(textField);
passwordField = new JPasswordField();
passwordField.setBounds(322, 183, 158, 31);
Start.add(passwordField);
Cashier.setLayout(null);
csbtn.setBounds(197, 139, 116, 23);
Cashier.add(csbtn);
Manager.setBackground(Color.BLUE);
Manager.add(mnbtn);
cl.show(Bucket, "1");
setTitle("NOVA PHARM");
getContentPane().add(Bucket);
setBounds(300, 300, 566, 482);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new CardLayout(5, 5));
setResizable(true);
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
NHome window = new NHome();
window.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
/*
*this is the second class where I want to use the variable
*/
Class 2
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.Font;
public class csView extends JPanel {
/**
* Create the panel.
*/
public csView() {
setLayout(null);
/**
* I want to display the String hhhhh in the JLabel Uniqlbl below
*
*/
JLabel Uniqlbl = new JLabel("Cashier Name:");
Uniqlbl.setFont(new Font("Tahoma", Font.PLAIN, 16));
Uniqlbl.setBounds(227, 62, 253, 46);
add(Uniqlbl);
}
}

Try modify the csView
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.Font;
public class csView extends JPanel {
// Declare those variables here
String hhhhh;
JLabel Uniqlbl;
public csView() {
setLayout(null);
Uniqlbl = new JLabel("Cashier Name:");
Uniqlbl.setFont(new Font("Tahoma", Font.PLAIN, 16));
Uniqlbl.setBounds(227, 62, 253, 46);
add(Uniqlbl);
}
// Add a setter here
public void setHhhhh(String hhhhh) {
this.hhhhh = hhhhh;
// Edit: Add this line to update the Uniqlbl text
Uniqlbl.setText(hhhhh);
}
}
And in the ActionListener call the setHhhhh() method
stbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
cl.show(Bucket, "2");
String hhhhh=new String("Peter");
// Call the setter here
Cashier.setHhhhh(hhhhh);
System.out.println(hhhhh);
}
});
I suggest you not to use the "hhhhh" variable in the csView constructor or you could stumble in a NullPointerException. Or, if you want to do so, initialize the "hhhhh" variable first like this
String hhhhh = "";

One way you could do this is a create a static variable in your NHome class that acts as a global variable. This would mean than csView would be able to read and write to the variable.
This is an example of how it could be implemented:
JPanel Bucket = new JPanel(), Start = new JPanel(), Cashier = new csView(), Manager = new JPanel();
JButton stbtn = new JButton("Start"), mnbtn = new JButton("Manager"), csbtn = new JButton("Cashier");
CardLayout cl = new CardLayout();
private final JTextField textField = new JTextField();
private JPasswordField passwordField;
static String hhhhh; //create the variable here
public NHome() {
textField.setBounds(322, 141, 158, 31);
textField.setColumns(10);
Bucket.setLayout(cl);
Bucket.add(Start, "1");
Bucket.add(Cashier, "2");
Bucket.add(Manager, "3");
Start.setLayout(null);
stbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
cl.show(Bucket, "2");
/*
* I want to use this value of this String in the another class (csView)
*/
hhhhh = new String("Peter"); //set the value here
System.out.println(hhhhh);
}
});
So then you could implement it in your csView by saying:
JLabel Uniqlbl = new JLabel(NHome.hhhhh);

Related

When creating an Object of my Gui in another class the frame loads but nothing appears inside

I've made the initialize method public, didn't help and I've set visible to true both here and the external class as seen below, any help would be appreciated. I created the gui using the window builder tool from eclipse
GeneralWindow frame = new GeneralWindow();
frame.setVisible(true);
package gui;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import java.awt.Font;
public class GeneralWindow extends JFrame{
private JFrame frame;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
// If Nimbus is not available, you can set the GUI to another look and feel.
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GeneralWindow window = new GeneralWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public GeneralWindow() {
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);
JButton btnNewButton = new JButton("Order");
btnNewButton.setBounds(309, 12, 115, 23);
frame.getContentPane().add(btnNewButton);
JButton btnNewButton_1 = new JButton("Search");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnNewButton_1.setBounds(309, 46, 115, 23);
frame.getContentPane().add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("Stock");
btnNewButton_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnNewButton_2.setBounds(309, 80, 115, 23);
frame.getContentPane().add(btnNewButton_2);
JButton btnNewButton_3 = new JButton("Emplyoees");
btnNewButton_3.setBounds(309, 114, 115, 23);
frame.getContentPane().add(btnNewButton_3);
JButton btnNewButton_4 = new JButton("Price Amend");
btnNewButton_4.setBounds(309, 148, 115, 23);
frame.getContentPane().add(btnNewButton_4);
JButton btnNewButton_5 = new JButton("Total");
btnNewButton_5.setBounds(309, 182, 115, 23);
frame.getContentPane().add(btnNewButton_5);
textField = new JTextField();
textField.setBounds(10, 228, 178, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
JLabel lblProductcodeBar = new JLabel("Productcode Bar");
lblProductcodeBar.setFont(new Font("Tahoma", Font.BOLD, 11));
lblProductcodeBar.setBounds(10, 209, 125, 14);
frame.getContentPane().add(lblProductcodeBar);
JButton btnEnter = new JButton("Enter");
btnEnter.setBounds(198, 227, 89, 23);
frame.getContentPane().add(btnEnter);
JTextArea textArea = new JTextArea();
textArea.setBounds(10, 11, 277, 196);
frame.getContentPane().add(textArea);
}
}
You're making the frame frame, of type GeneralWindow, visible. But you never add any component to that frame. Instead, your initialize method creates yet another frame, and adds many components to that frame. Don't create another frame, and add the components to this, instead.
In Your initialize() just change the frame to this keyword
e.g
//Remove this line
frame = new JFrame();
//change frame to this keyword
this.setBounds(100, 100, 450, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().setLayout(null);
That its u r done...
Whilst the two answers provide here give a correct solution, they both reinforce the view that you should extend JFrame. This is not good advice in general, as you should favour composition over inheritance. Indeed the way you were writing the code to include a JFrame as a private member was the correct instinct.
I've included a stripped down version of your code that doesn't extend JFrame Instead it creates an instance of the JFrame when you call the createAndDisplayFrame() method.
public class GeneralWindow {
private JFrame frame;
private JButton orderButton;
public static void main(final String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
GeneralWindow window = new GeneralWindow();
window.crateAndDisplayFrame();
}
});
}
public void crateAndDisplayFrame() {
initialize();
frame.setVisible(true);
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
orderButton = new JButton("Order");
orderButton.setBounds(309, 12, 115, 23);
frame.getContentPane().add(orderButton);
}
}

How to open new window after JProgressBar is completed

I created FlashScreen.java as loading screen consist of JProgressBar.
I want that after progressbar percentage is completed current window should be closed and new window should be open.
I made it but after closing first window in next window there is no component in window. Empty window is opening.
Here is code:
FlashScreen.java
package crimeManagement;
import javax.swing.*;
import java.awt.Rectangle;
import java.awt.Font;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class FlashScreen extends JFrame{
JProgressBar jb;
JLabel lblStat;
int i=0,num=0;
FlashScreen(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setBounds(new Rectangle(400, 200, 0, 0));
jb=new JProgressBar(0,2000);
jb.setBounds(100,219,579,22);
jb.setValue(0);
jb.setStringPainted(true);
getContentPane().add(jb);
setSize(804,405);
getContentPane().setLayout(null);
lblStat = new JLabel("");
lblStat.setForeground(Color.CYAN);
lblStat.setHorizontalAlignment(SwingConstants.CENTER);
lblStat.setHorizontalTextPosition(SwingConstants.CENTER);
lblStat.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 18));
lblStat.setBounds(229, 252, 329, 14);
getContentPane().add(lblStat);
JLabel lblBackGround = new JLabel("");
lblBackGround.setHorizontalTextPosition(SwingConstants.CENTER);
lblBackGround.setHorizontalAlignment(SwingConstants.CENTER);
lblBackGround.setIcon(new ImageIcon(FlashScreen.class.getResource("/Images/FlashImage.jpg")));
lblBackGround.setBounds(0, 0, 798, 376);
getContentPane().add(lblBackGround);
}
public void iterate(){
while(i<=2000){
jb.setValue(i);
i=i+20;
try{
Thread.sleep(50);
if(i==20)
{
lblStat.setText("Loading...");
}
if(i==500)
{
lblStat.setText("Please Wait...");
}
if(i==1000)
{
Thread.sleep(100);
lblStat.setText("Loading Police Station Management System...");
}
if(i==1200)
{
lblStat.setText("Please Wait...");
}
if(i==1600)
{
lblStat.setText("Almost Done...");
}
if(i==1980)
{
lblStat.setText("Done");
}
if(i==2000)
{
this.dispose();
LoginPage lp=new LoginPage();
lp.setVisible(true);
}
}
catch(Exception e){}
}
}
public static void main(String[] args) {
FlashScreen fs=new FlashScreen();
fs.setVisible(true);
fs.iterate();
}
}
**LoginPage.java**
package crimeManagement;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.border.*;
public class LoginPage extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JFrame frame;
private JTextField txtUserName;
private JPasswordField txtPass;
public static void main(String[] args) {
LoginPage window = new LoginPage();
window.frame.setVisible(true);
}
public LoginPage() {
frame = new JFrame();
frame.setResizable(false);
frame.getContentPane().setBackground(SystemColor.inactiveCaption);
frame.getContentPane().setFont(new Font("Tahoma", Font.PLAIN, 16));
frame.setBounds(100, 100, 554, 410);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblLoginType = new JLabel("Login Type");
lblLoginType.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblLoginType.setBounds(97, 53, 99, 20);
frame.getContentPane().add(lblLoginType);
JLabel lblUsename = new JLabel("User Name");
lblUsename.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblUsename.setBounds(97, 177, 99, 26);
frame.getContentPane().add(lblUsename);
JLabel lblPaaword = new JLabel("Password");
lblPaaword.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblPaaword.setBounds(97, 223, 99, 26);
frame.getContentPane().add(lblPaaword);
JPanel panel = new JPanel();
FlowLayout flowLayout = (FlowLayout) panel.getLayout();
panel.setBackground(SystemColor.inactiveCaptionBorder);
panel.setBounds(210, 47, 143, 93);
frame.getContentPane().add(panel);
TitledBorder tb=new TitledBorder( "Login");
tb.setTitleJustification(TitledBorder.CENTER);
tb.setTitlePosition(TitledBorder.CENTER);
panel.setBorder(BorderFactory.createTitledBorder(tb));
JRadioButton rdbAdmin = new JRadioButton("Admin");
rdbAdmin.setBackground(SystemColor.inactiveCaption);
rdbAdmin.setFont(new Font("Tahoma", Font.PLAIN, 13));
rdbAdmin.setSelected(true);
panel.add(rdbAdmin);
JRadioButton rdbOthers = new JRadioButton("Others");
rdbOthers.setBackground(SystemColor.inactiveCaption);
rdbOthers.setFont(new Font("Tahoma", Font.PLAIN, 13));
panel.add(rdbOthers);
txtUserName = new JTextField();
txtUserName.setBackground(UIManager.getColor("TextField.background"));
txtUserName.setBounds(210, 177, 158, 26);
frame.getContentPane().add(txtUserName);
txtUserName.setColumns(30);
JButton btnLogin = new JButton("Login");
btnLogin.setFont(new Font("Tahoma", Font.PLAIN, 14));
btnLogin.setBounds(210, 286, 71, 23);
frame.getContentPane().add(btnLogin);
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
btnExit.setFont(new Font("Tahoma", Font.PLAIN, 14));
btnExit.setBounds(297, 286, 71, 23);
frame.getContentPane().add(btnExit);
txtPass = new JPasswordField();
txtPass.setBounds(210, 226, 158, 26);
frame.getContentPane().add(txtPass);
}
}
You're displaying the wrong JFrame. Yes the LoginPage extends JFrame, and yes you display it, but you add no components to it, and instead add all components to a private JFrame field of the class named, frame.
A quick solution is to change your LoginPage class so that it doesn't extend JFrame and then give this class a public getFrame() method:
public JFrame getFrame() {
return frame;
}
and when wanting to show it, call
this.dispose();
LoginPage lp = new LoginPage();
// lp.setVisible(true);
lp.getFrame().setVisible(true);
but having said this, there are still some serious threading issues with your code that you'll eventually want to fix, including trying to avoid calling Thread.sleep() in code that risks being called on the Swing event thread.
Also please check out The Use of Multiple JFrames: Good or Bad Practice? to see why it is often a bad practice to display a bunch of JFrames in your app, and ways around this.
Other issues include use of null layouts. Yes they may seem like an easy way to create complex GUI's quickly -- until you try to show the GUI on another platform and find that they don't look so nice, or have to enhance, debug or change it, and find it very tricky and easy to mess up. Much better to use layout managers.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class FlashScreenTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame mainFrame = new JFrame("Main App");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.add(new MainAppPanel());
mainFrame.pack();
mainFrame.setLocationRelativeTo(null);
FlashScreenPanel dialogPanel = new FlashScreenPanel();
JDialog dialog = new JDialog(mainFrame, "Flash Screen", ModalityType.APPLICATION_MODAL);
dialog.add(dialogPanel);
dialog.pack();
dialog.setLocationRelativeTo(null);
dialogPanel.startProgress();
dialog.setVisible(true);
mainFrame.setVisible(true);
});
}
}
class FlashScreenPanel extends JPanel {
public static final String LOADING = "Loading...";
public static final String PLEASE_WAIT = "Please Wait...";
public static final String LOADING_POLICE_STATION = "Loading Police Station...";
public static final String ALMOST_DONE = "Almost Done...";
public static final String DONE = "Done";
private static final int TIMER_DELAY = 50;
private JProgressBar jb = new JProgressBar(0, 2000);
private JLabel statusLabel = new JLabel("", SwingConstants.CENTER);
public FlashScreenPanel() {
setPreferredSize(new Dimension(800, 400));
statusLabel.setForeground(Color.CYAN);
statusLabel.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 18));
jb.setStringPainted(true);
JPanel bottomPanel = new JPanel(new BorderLayout(20, 20));
bottomPanel.add(jb, BorderLayout.PAGE_START);
bottomPanel.add(statusLabel, BorderLayout.CENTER);
int eb = 40;
setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));
setLayout(new GridLayout(0, 1));
add(new JLabel()); // dummy component to move prog bar lower
add(bottomPanel);
}
public void startProgress() {
statusLabel.setText(LOADING);
new Timer(TIMER_DELAY, new ActionListener() {
private int i = 0;
#Override
public void actionPerformed(ActionEvent e) {
i += 20;
jb.setValue(i);
if (i == 500) {
statusLabel.setText(PLEASE_WAIT);
} else
if (i == 1000) {
statusLabel.setText(LOADING_POLICE_STATION);
} else
if (i == 1200) {
statusLabel.setText(PLEASE_WAIT);
} else
if (i == 1600) {
statusLabel.setText(ALMOST_DONE);
} else
if (i == 1980) {
statusLabel.setText(DONE);
} else
if (i == 2000) {
((Timer) e.getSource()).stop();
Window win = SwingUtilities.getWindowAncestor(FlashScreenPanel.this);
win.dispose();
}
}
}).start();
}
}
class MainAppPanel extends JPanel {
public MainAppPanel() {
setPreferredSize(new Dimension(600, 400));
}
}

Passing info from one Jframe to another

I have my original text field in my first frame and I need it to be displayed in my other jframe. The code is:
JButton btnContinue = new JButton("Continue");
btnContinue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = nameL.getText();
frame2 fram = new frame2 ();
fram.setVisible(true);
frame.dispose();
new order (msg) .setVisible(true);
'nameL' is the textbox the user enters their name in.
This code describe where it should be displayed:
public order(String para){
getComponents();
JLabel lblNewLabel_1 = new JLabel("");
lblNewLabel_1.setBounds(91, 27, 254, 84);
contentPane.add(lblNewLabel_1);
lblNewLabel_1.setText(para);
this is my first class where the user inputs their name
public order(String para){
getComponents();
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Font;
public class frame1 {
public JFrame frame;
public JTextField nameL;
public JTextField textField_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame1 window = new frame1();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public frame1() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setEnabled(false);
frame.setResizable(false);
frame.getContentPane().setBackground(Color.GRAY);
frame.setForeground(Color.WHITE);
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnContinue = new JButton("Continue");
btnContinue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = nameL.getText();
frame2 fram = new frame2 ();
fram.setVisible(true);
frame.dispose();
new order (msg) .setVisible(true);
}
}
);
btnContinue.setBounds(0, 249, 450, 29);
frame.getContentPane().add(btnContinue);
JTextArea txtrPleaseEnterYour = new JTextArea();
txtrPleaseEnterYour.setEditable(false);
txtrPleaseEnterYour.setBackground(Color.LIGHT_GRAY);
txtrPleaseEnterYour.setBounds(0, 0, 450, 32);
txtrPleaseEnterYour.setText("\tPlease enter your name and email below\n If you do not have or want to provide an email, Leave the space blank");
frame.getContentPane().add(txtrPleaseEnterYour);
JTextArea txtrEnterYourFull = new JTextArea();
txtrEnterYourFull.setEditable(false);
txtrEnterYourFull.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
txtrEnterYourFull.setBackground(Color.GRAY);
txtrEnterYourFull.setText("Enter your full name");
txtrEnterYourFull.setBounds(52, 58, 166, 29);
frame.getContentPane().add(txtrEnterYourFull);
nameL = new JTextField();
nameL.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
}
);
nameL.setBackground(Color.LIGHT_GRAY);
nameL.setBounds(52, 93, 284, 26);
frame.getContentPane().add(nameL);
nameL.setColumns(10);
JTextArea txtroptionalEnterYour = new JTextArea();
txtroptionalEnterYour.setEditable(false);
txtroptionalEnterYour.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
txtroptionalEnterYour.setBackground(Color.GRAY);
txtroptionalEnterYour.setText("(Optional) Enter your email");
txtroptionalEnterYour.setBounds(52, 139, 193, 29);
frame.getContentPane().add(txtroptionalEnterYour);
textField_1 = new JTextField();
textField_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
textField_1.setBackground(Color.LIGHT_GRAY);
textField_1.setBounds(52, 180, 284, 26);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
}
}
my second class where the text field has to be set
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.Color;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
public class order extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
public JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
order frame = new order();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public order() {
setAlwaysOnTop(false);
setTitle("Order Details // Finalization");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 451, 523);
contentPane = new JPanel();
contentPane.setBackground(Color.LIGHT_GRAY);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnNewButton = new JButton("Submit Order");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setAlwaysOnTop(true);
JOptionPane.showMessageDialog(null, "Your Order Has Been Confirmed", "enjoy your meal", JOptionPane.YES_NO_OPTION);
}
});
btnNewButton.setBounds(164, 466, 117, 29);
contentPane.add(btnNewButton);
}
public order(String para){
getComponents();
JLabel lblNewLabel_1 = new JLabel("");
lblNewLabel_1.setBounds(91, 27, 254, 84);
contentPane.add(lblNewLabel_1);
lblNewLabel_1.setText(para);
}
}
Open both JFrames, have them listen to the EventQueue for a custom "string display" event.
Wrap the string to be displayed in a custom event.
Throw that on the event queue, allowing both the JFrames to receive the event, which they will then display accordingly.
---- Edited with an update ----
Ok, so you're a bit new to Swing, but hopefully not too new to Java. You'll need to understand sub-classing and the "Listener" design pattern.
Events are things that Components listen for. They ask the dispatcher (the Swing dispatcher is fed by the EventQueue) to "tell them about events" and the dispatcher then sends the desired events to them.
Before you get too deep in solving your problem, it sounds like you need to get some familiarity with Swing and its event dispatch, so read up on it here.

Focus on Keylistener

So what I've got is that I would love to try and make an little login applet. I'm using Java Windowsbuilder for it, to make it easyer for me. I hope the code isn't to messy, because I'm just a starter.
The problem I've got is that My JButton "login" only registers a keyevent when it's selected trought tab, or when you first click it. What I want is that I can use the button always just by pressing the "ENTER" key.
Hope you guys solve my problem :)
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import org.eclipse.wb.swing.FocusTraversalOnArray;
import java.awt.Component;
import java.awt.event.KeyAdapter;
public class nummer1 extends JFrame{
private JPanel contentPane;
public static nummer1 theFrame;
private JTextField textFieldUsername;
private JTextField textFieldPass;
private nummer1 me;
private JLabel lblCheck;
private String password = "test", username = "test";
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
nummer1 frame = new nummer1();
nummer1.theFrame = frame;
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void Check(){
String Pass = textFieldPass.getText();
String Username = textFieldUsername.getText();
System.out.println(Pass);
if (Pass.equals(password) && Username.equals(username)){
lblCheck.setText("Correct Login");
}else{
lblCheck.setText("Invalid username or password");
}
}
/**
* Create the frame.
*/
public nummer1() {
me = this;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 356, 129);
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, 61, 14);
contentPane.add(lblUsername);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setBounds(10, 36, 61, 14);
contentPane.add(lblPassword);
textFieldUsername = new JTextField();
textFieldUsername.setBounds(81, 8, 107, 20);
contentPane.add(textFieldUsername);
textFieldUsername.setColumns(10);
me.textFieldUsername = textFieldUsername;
textFieldPass = new JTextField();
textFieldPass.setBounds(81, 33, 107, 20);
contentPane.add(textFieldPass);
textFieldPass.setColumns(10);
me.textFieldPass = textFieldPass;
JButton btnLogin = new JButton("Login");
contentPane.requestFocusInWindow();
btnLogin.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER){
me.Check();
System.out.println("hi");
}
}
});
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
me.Check();
}
});
btnLogin.setBounds(198, 7, 89, 23);
contentPane.add(btnLogin);
JLabel lblCheck = new JLabel("");
lblCheck.setHorizontalAlignment(SwingConstants.TRAILING);
lblCheck.setBounds(10, 65, 264, 14);
contentPane.add(lblCheck);
me.lblCheck = lblCheck;
contentPane.setFocusTraversalPolicy(new FocusTraversalOnArray(new
Component[]{lblUsername, lblPassword, textFieldUsername, textFieldPass, btnLogin, lblCheck}));
}
}
Thanks Emil!
What I want is that I can use the button always just by pressing the "ENTER" key
Sounds like you want to make the "login" button the default button for the dialog.
See Enter Key and Button for the problem and solution.
When using panels KeyListeners won't work unless the panel is focusable. What you can do is make a KeyBinding to the ENTER key using the InputMap and ActionMap for your panel.
public class Sample extends JPanel{
//Code
Sample() {
//More code
this.getInputMap().put(KeyStroke.getKeyStroke((char)KeyEvent.VK_ENTER), "Enter" );
this.getActionMap().put("Enter", new EnterAction());
}
private class EnterAction extends AbstractAction(){
#Override
public void ActionPerformed(ActionEvent e){
//Acion
}
}
}

Using a variable from another class in an Action Listener outputs 'null'

This is another problem that has come up after having solved my earlier question here:
How to use a variable created in class1, in another class?
The answer to the question above allows me to use a variable created in class 3 to be printed by calling a method in class 4, from class 4.
However, when I try to print that variable as part of an action listener, it prints out 'null' instead of whatever the user inputs in the JTexfield create_u1 (in class 3).
Updated for sajjadG: please try it yourself
class 1
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class class1 extends JFrame {
public static void main(String[] args) {
mainPage MP = new mainPage();
MP.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MP.setLocationRelativeTo(null);
MP.setSize(300,200);
MP.setVisible(true);
}
}
class 2
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class mainPage extends JFrame {
create_account crAcc = new create_account();
change_username chU = new change_username();
change_password chPW = new change_password();
sign_in signIn = new sign_in();
private JButton create_account, change_username, change_password, signIn_button;
public mainPage(){
super("Password Programme");
setPreferredSize (new Dimension (400, 100));
setLayout (null);
create_account = new JButton("Create an Account");
add(create_account);
change_username = new JButton("Change Username");
add(change_username);
change_password = new JButton("Change Password");
add(change_password);
signIn_button = new JButton("Sign in and Access Files");
add(signIn_button);
create_account.setBounds (10, 20, 150, 20);
change_username.setBounds (10, 50, 150, 20);
change_password.setBounds (10, 80, 150, 20);
signIn_button.setBounds (10, 110, 200, 20);
HandlerClass handler = new HandlerClass();
create_account.addActionListener(handler);
change_username.addActionListener(handler);
change_password.addActionListener(handler);
signIn_button.addActionListener(handler);
}
private class HandlerClass implements ActionListener{
public void actionPerformed(ActionEvent event){
if(event.getSource()==create_account) {
crAcc.setLocationRelativeTo(null);
crAcc.setSize(300,200);
crAcc.setVisible(true);
}
if(event.getSource()==change_username) {
chU.setLocationRelativeTo(null);
chU.setSize(300,200);
chU.setVisible(true);
}
if(event.getSource()==change_password) {
chPW.setLocationRelativeTo(null);
chPW.setSize(300,200);
chPW.setVisible(true);
}
if(event.getSource()==signIn_button) {
signIn.setLocationRelativeTo(null);
signIn.setSize(300,200);
signIn.setVisible(true);
}
}
}
}
class 3
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class create_account extends JFrame{
private String u1, pw1;
private JLabel cU1, cpw1, statusBar;
public JTextField create_u1;
public JPasswordField create_pw1;
private JButton change;
public String userName3, passWord3;
public void checkUserName(String u, String pw) {
System.out.println(u); ///// this prints it out correctly
System.out.println(pw);
if (create_u1.getText()==u){
System.out.println("correct");
}else { /// it tests incorrect even though i inputted same thing
System.out.println("incorrect");
System.out.println(create_u1.getText());
System.out.println(userName3); /// prints out null }
}
public create_account() {
super("Create Account");
setPreferredSize (new Dimension (400, 85));
setLayout (null);
statusBar = new JLabel("Create a username");
add(statusBar, BorderLayout.SOUTH);
statusBar.setBounds(20, 110, 250, 30);
cU1 = new JLabel("Username");
cpw1 = new JLabel("Password");
create_u1 = new JTextField(10);
create_pw1 = new JPasswordField(10);
cU1.setBounds(10, 10, 150, 30);
create_u1.setBounds(100, 10, 100, 30);
cpw1.setBounds(10, 50, 150, 30);
create_pw1.setBounds(100, 50, 100, 30);
add(create_u1);
add(cU1);
create_u1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event){
JOptionPane.showMessageDialog(null, "Username saved. Now create a password");
statusBar.setText("Create a password");
add(cpw1);
add(create_pw1);
cpw1.repaint();
create_pw1.repaint();
create_pw1.requestFocus();
}
}
);
create_pw1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event){
JOptionPane.showMessageDialog(null, "Password saved");
statusBar.setText("Account created. Return to main programme");
statusBar.requestFocus();
}
}
);
}
}
class 4
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class change_username extends JFrame {
private JLabel uT1, pwT, uCh, statusBar;
private JTextField username_input, username_change;
private JPasswordField password_input;
create_account objOfClass3 = new create_account();
public void checkUserName() {
objOfClass3.checkUserName(username_input.getText(), password_input.getText());
}
public change_username() {
super("Change Username");
setPreferredSize (new Dimension (400, 85));
setLayout (null);
statusBar = new JLabel("Enter your username");
add(statusBar, BorderLayout.SOUTH);
statusBar.setBounds(20, 130, 250, 30);
uT1 = new JLabel("Username");
username_input = new JTextField(10);
pwT = new JLabel("Password");
password_input = new JPasswordField(10);
uCh = new JLabel("New Username");
username_change = new JTextField(10);
uT1.setBounds(10, 10, 150, 30);
username_input.setBounds(100, 10, 100, 30);
pwT.setBounds(10, 50, 150, 30);
password_input.setBounds(100, 50, 100, 30);
uCh.setBounds(10, 90, 150, 30);
username_change.setBounds(100, 90, 100, 30);
add(uT1);
add(username_input);
username_input.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event){
statusBar.setText("Enter your password");
add(pwT);
add(password_input);
pwT.repaint();
password_input.repaint();
password_input.requestFocus();
}
}
);
password_input.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event){
statusBar.setText("Enter your new username");
add(uCh);
add(username_change);
uCh.repaint();
username_change.repaint();
username_change.requestFocus();
checkUserName();
}
}
);
username_change.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event){
statusBar.setText("Username Changed. Return to main programme");
username_change.requestFocus();
}
}
);
}
}
That is because you are not setting userName attribute first. you should set usernName first then try getUserName()
Try adding below line in your actionPerformed method before printing userName
setUserName(username_input.getText());
here is the corrected and tested code:
package test;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class ChangeUsername extends JFrame {
private JLabel uT1, pwT, uCh, statusBar;
private JTextField usernameInput, usernameChange;
private JPasswordField passwordInput;
public String userName, passWord;
public String getUserName() {
return this.userName;
}
public void setUserName(String givenUserName) {
this.userName = givenUserName;
System.out.println(getUserName()); /////// this correctly prints the variable
}
public ChangeUsername() {
super("Change Username");
setPreferredSize(new Dimension(400, 85));
setLayout(null);
statusBar = new JLabel("Enter your username");
add(statusBar, BorderLayout.SOUTH);
statusBar.setBounds(20, 130, 250, 30);
uT1 = new JLabel("Username");
usernameInput = new JTextField(10);
pwT = new JLabel("Password");
passwordInput = new JPasswordField(10);
uCh = new JLabel("New Username");
usernameChange = new JTextField(10);
uT1.setBounds(10, 10, 150, 30);
usernameInput.setBounds(100, 10, 100, 30);
pwT.setBounds(10, 50, 150, 30);
passwordInput.setBounds(100, 50, 100, 30);
uCh.setBounds(10, 90, 150, 30);
usernameChange.setBounds(100, 90, 100, 30);
add(uT1);
add(usernameInput);
usernameInput.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
statusBar.setText("Enter your password");
add(pwT);
add(passwordInput);
pwT.repaint();
passwordInput.repaint();
passwordInput.requestFocus();
setUserName(usernameInput.getText());// setting the username
// statusBar.setText(statusBar.getText() + " " + getUserName());
System.out.println(getUserName()); ////// this line does not
}
});
}
public static void main(String argv[]) {
new ChangeUsername().setVisible(true);
}
}
Also I should mention that you should start using Java naming convention and use meaningful names for your classes, attributes and methods.
classes start with Upercase letter
methods and attribute start with lower case
all of identifiers are camelCase so don't use _ between them. write getUserName instead of get_user_name
Read this link for more rules on Java naming convention.
And you need to learn more about OOP. So I suggest reading book Thinking in Java. TIJ third edition is free and good.
Here, you are not setting the value for the text field.
Do something like
username_input.setText(userName);
Put the above line in setUserName(){}
OR
public change_username() {
super("Change Username");
setPreferredSize (new Dimension (400, 85));
setLayout (null);
statusBar = new JLabel("Enter your username");
add(statusBar, BorderLayout.SOUTH);
statusBar.setBounds(20, 130, 250, 30);
uT1 = new JLabel("Username");
username_input = new JTextField(10);
pwT = new JLabel("Password");
password_input = new JPasswordField(10);
uCh = new JLabel("New Username");
username_change = new JTextField(10);
uT1.setBounds(10, 10, 150, 30);
username_input.setBounds(100, 10, 100, 30);
pwT.setBounds(10, 50, 150, 30);
password_input.setBounds(100, 50, 100, 30);
uCh.setBounds(10, 90, 150, 30);
username_change.setBounds(100, 90, 100, 30);
add(uT1);
add(username_input);
// SET THE TEXT HERE Before the Listener **************************
username_input.setText(getUserName());
// *****************************************************************
Then your code ahead.....

Categories

Resources