How do I make my JPasswordField use a specific password? - java

Hello Guys I need a password that I want to be writen in the JPasswordField
(JPasswordFieldAnon) and attach submit action to the two JButtons
(AnonButton and AnonButton1).
Here is the code:
package javafx;
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class Anonymous {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Anonymous window = new Anonymous();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Anonymous() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setTitle("Anonymous Terminal. Enter Password");
frame.setResizable(false);
frame.setVisible(true);
frame.setSize(952, 785);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel JLabelAnon = new JLabel("We are Anonymous. We are Legion. We do not forgive. We do not forget. Expect Us.");
JLabelAnon.setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
JLabelAnon.setBackground(Color.BLACK);
JLabelAnon.setFont(new Font("hooge 05_53", Font.PLAIN, 13));
JLabelAnon.setForeground(Color.GREEN);
JLabelAnon.setBounds(116, 566, 695, 14);
frame.getContentPane().add(JLabelAnon);
JPasswordField JPasswordFieldAnon = new JPasswordField("Enter Password: ", 1);
JPasswordFieldAnon.setBackground(new Color(0, 128, 0));
JPasswordFieldAnon.setToolTipText("Enter Password\r\n");
JPasswordFieldAnon.setText("");
JPasswordFieldAnon.setName("Anonymous Password");
JPasswordFieldAnon.setBounds(367, 535, 206, 22);
frame.getContentPane().add(JPasswordFieldAnon);
JButton AnonButton = new JButton("Expect Us!");
AnonButton.setBackground(new Color(34, 139, 34));
AnonButton.setName("Log In");
AnonButton.setBounds(579, 535, 115, 22);
frame.getContentPane().add(AnonButton);
JButton AnonButton1 = new JButton("Expect Us!");
AnonButton1.setName("Log In");
AnonButton1.setBackground(new Color(34, 139, 34));
AnonButton1.setBounds(246, 535, 115, 22);
frame.getContentPane().add(AnonButton1);
JTextPane textPane1 = new JTextPane();
textPane1.setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
textPane1.setEditable(false);
textPane1.setBackground(Color.BLACK);
textPane1.setBounds(108, 563, 703, 20);
frame.getContentPane().add(textPane1);
JLabel lblNewLabel = new JLabel("");
lblNewLabel.setIcon(new ImageIcon("F:\\FBI-Terminal_1.png"));
lblNewLabel.setBounds(0, 0, 948, 759);
frame.getContentPane().add(lblNewLabel);
}
public void actionPerformed(ActionEvent e) {
}
}
My problem is that I tried around 5 days now just trying a lot methods...

Some notes about your code.
Your password field variable does not have scope enough to retrieve the typed password later because it's a local variable within initialize() method. I'd define it as a class variable.
You have to attach an ActionListener to the buttons to actually "submit" the password.
You have an actionPerformed() method but the implementation of ActionListener interface is missing in your class header. This is why we should use #Override annotation when we implement or override existing methods.
See these tutorials:
How to Use Buttons
How to Use Password Fields
Variables (about different variable scopes)
Off-topic
Swing is designed to work with Layout Managers. and the use of methods such as setLocation(...), setBounds(...) or setXxxSize(...) is highly discouraged.

Related

alternatives to using ".this" for addActionListener? static context issues

created login class for GUI, added all the GUI construction to a method so I can call it from my main class on startup. Calling method throws error "'GUILoginPage.this' cannot be referenced from a static context".
What are the work arounds for this? I understand the reasoning behind not being able to use .this but I haven't seen any solutions
public static void main() {
JFrame frame = new JFrame();
JButton loginButton = new JButton("Login");
JTextField userIDField = new JTextField();
JPasswordField userPasswordField = new JPasswordField();
JLabel userIDLabel = new JLabel("Username:");
JLabel userPasswordLabel = new JLabel("Password:");
userIDLabel.setBounds(50, 100, 75, 25);
userPasswordLabel.setBounds(50, 150, 75, 25);
userIDField.setBounds(125, 100, 200, 25);
userPasswordField.setBounds(125, 150, 200, 25);
loginButton.setBounds(125, 200, 100, 25);
loginButton.addActionListener(this);
frame.add(userIDLabel);
frame.add(userPasswordLabel);
frame.add(userIDField);
frame.add(userPasswordField);
frame.add(loginButton);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setLayout(null);
frame.setVisible(true);
}
this doesn't have any meaning in a static context. your main is Static so it means that there is no instance of a class to work with.
Here you will need to define and use your own action listener that will handle the button click, such as :
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
performLogin();
}
} );

JAR file messes GUI?

I've got some homework to make a simple login window.
After I finished with my coding I tried exporting the file into a runnable jar file, and after running the jar file I saw that it had messed up the GUI.
The JPasswordField fills up my entire JFrame for some reason. I have no clue what might be the problem because it runs fine from the IDE. any help?
here is the code (works fine in eclipse IDE):`
public class Login extends JFrame {
private static final long serialVersionUID = 1L;
private static JTextField user = new JTextField();
private static JPasswordField pass = new JPasswordField();
private static JButton Loginbtn = new JButton("Login");
protected String[] args;
private static JFrame frame = new JFrame("Log In");
public Login(){
Loginbtn.addActionListener(new ActionListener(){
#SuppressWarnings("deprecation")
public void actionPerformed(ActionEvent e){
if(user.getText().equals("Admin") && pass.getText().equals("Nimda")){
//System.out.println("Hello ADMIN!");
JOptionPane.showMessageDialog(null, "Logged In!");
MyLog.main(args);
frame.setVisible(false);
}
else{
//System.out.println("Login error!");
JOptionPane.showMessageDialog(null, "Login Error!");
}
}
});
}
public static void main(String[] args) {
#SuppressWarnings("unused")
Login login = new Login();
JLabel username = new JLabel("Username");
JLabel password = new JLabel("Password");
frame.setSize(260, 200);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
username.setBounds(20, 60, 100, 20);
password.setBounds(20, 85, 100, 20);
pass.setBounds(85, 85, 150, 20);
user.setBounds(85, 60, 150, 20);
Loginbtn.setBounds(88, 110, 50, 20);
frame.add(username);
frame.add(password);
frame.add(Loginbtn);
frame.add(user);
frame.add(pass);
}
}
thanks in advance guys!
cheers!
Calling setVisible on the JFrame before adding your components to it causes the problem most likely. You should add all the components that you want to the JFrame before calling setVisible, as setVisible validates those components (lays them out).
What setVisible does from the API, you'll see it talks about validating the components
What validate does from API

How to use a text area?

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

Area Calculator not working and not sure why

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.

Appending text to a JTextArea on button press?

I've got a simple Swing GUI and I want to add a new line of text to a JTextArea after a button is pressed, simple right?
The Button and it's ActionListener function correctly (printing stuff to the console works fine), but when I use .append()or .setText() to add text to the textarea, I get a nullpointer exception.
As always, code it below. Any input would be greatly appreciated, thanks!!!
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.LineBorder;
public class GUI extends JFrame implements ActionListener {
private JFrame frame;
private JLabel paneHeader;
public JTextArea ipArea, portArea, outputLog, orderLog, cookLog;
private JButton newServer;
public String ipAddress, portNumber, cashierName, cookName;
public GUI() {
initGUI();
}
public void initGUI() {
frame = new JFrame("Restaurant Overview");
Container contentPane = frame.getContentPane();
JLabel paneHeader = new JLabel("Restaurant Monitoring System");
paneHeader.setBounds(200, 0, 200, 25);
paneHeader.setFont(new Font("Calibri", Font.BOLD, 14));
JLabel ipLabel = new JLabel("IP Address: ");
ipLabel.setBounds(25, 30, 75, 20);
ipLabel.setFont(new Font("Calibri", Font.PLAIN, 12));
final JTextArea ipArea = new JTextArea();
ipArea.setBorder(new LineBorder(Color.GRAY));
ipArea.setBounds(105, 30, 100, 20);
JLabel portLabel = new JLabel("Port Number: ");
portLabel.setBounds(25, 55, 75, 20);
portLabel.setFont(new Font("Calibri", Font.PLAIN, 12));
final JTextArea portArea = new JTextArea();
portArea.setBorder(new LineBorder(Color.GRAY));
portArea.setBounds(105, 55, 100, 20);
JButton newServer = new JButton("Create new Server");
newServer.setBorder(new LineBorder(Color.GRAY));
newServer.setBounds(250, 30, 150, 40);
newServer.setActionCommand("createserver");
newServer.addActionListener(this);
JTextArea outputLog = new JTextArea(" ");
outputLog.setBorder(new LineBorder(Color.GRAY));
outputLog.setBounds(25, 90, 150, 150);
//outputLog.setEditable(false);
JTextArea cashierLog = new JTextArea();
cashierLog.setBorder(new LineBorder(Color.GRAY));
cashierLog.setBounds(185, 90, 150, 150);
//cashierLog.setEditable(false);
JTextArea cookLog = new JTextArea();
cookLog.setBorder(new LineBorder(Color.GRAY));
cookLog.setBounds(345, 90, 150, 150);
//cookLog.setEditable(false);
contentPane.add(paneHeader);
contentPane.add(ipLabel);
contentPane.add(ipArea);
contentPane.add(portLabel);
contentPane.add(portArea);
contentPane.add(outputLog);
contentPane.add(cashierLog);
contentPane.add(cookLog);
contentPane.add(newServer);
frame.setLayout(null);
frame.pack();
frame.setSize(600,400);
frame.setVisible(true);
}
public void test() {
//ipAddress = ipArea.getText() + "\n";
//portNumber = portArea.getText() + "\n";
String text = "lemons";
//System.out.println(text);
outputLog.append(text);
//outputLog.append(portNumber);
}
public void actionPerformed(ActionEvent e) {
if ("createserver".equals(e.getActionCommand())) {
//test();
outputLog.append("lemons");
} else {
//Do Nothing
}
}
}
You are likely shadowing a variable -- declaring it more than once, but initializing a local variable not the class field, and so the class field remains null.
Edit:
Yep, sure enough you do. In your constructor you have
JTextArea outputLog = new JTextArea(" ");
This re-declares the outputLog variable, and so you are initializing only the variable local to the constructor. The solution is not to redeclare the variable but instead initialize the class field. So change the above to
outputLog = new JTextArea(" ");
You will need to do this for every variable that needs to be accessed in the class scope. For those that are OK to declare locally, do so, but in the sake of safety, get rid of their corresponding class declaration so as not to risk causing the same error in the future.
Your error is that the instance variable outputLog is not initialized.
your code not done on EDT, you have to wrap tht into invokeLater()
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
outputLog.setText(outputLog.getText()
+ System.getProperty("line.separator") + text);
}
});

Categories