In the following code, the file runs fine if I take the password.setEchoCar(char) method call out. Why can I not call it when the object is created right above it?
There shoudlnt be a scope problem and I checked the javadoc for the method, it seems to be the correct method for specifying a non-default password character.
Thanks
import javax.swing.*;
public class Authenticator extends javax.swing.JFrame {
JTextField username = new JTextField(15);
JPasswordField password = new JPasswordField(15);
password.setEchoChar('%');
JTextArea comments = new JTextArea(4, 15);
JButton ok = new JButton("OK");
JButton cancel = new JButton("Cancel");
public Authenticator () {
super("Account Information");
setSize(300, 220);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel();
JLabel usernameLabel= new JLabel("Username: ");
JLabel passwordLabel = new JLabel("Password: ");
JLabel commentsLabel = new JLabel("Comments: ");
comments.setLineWrap(true);
comments.setWrapStyleWord(true);
pane.add(usernameLabel);
pane.add(username);
pane.add(passwordLabel);
pane.add(password);
pane.add(commentsLabel);
pane.add(comments);
pane.add(ok);
pane.add(cancel);
add(pane);
setVisible(true);
}
private static void setLookAndFeel() {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Exception exc) {
System.out.println(exc.getMessage());
}
}
public static void main(String[] arguments) {
Authenticator.setLookAndFeel();
Authenticator auth = new Authenticator();
}
}
You're trying to execute code out side of an executable context (within the variable decleration area)...
public class Authenticator extends javax.swing.JFrame {
JTextField username = new JTextField(15);
JPasswordField password = new JPasswordField(15);
password.setEchoChar('%');
//...
public Authenticator () {
//...
Move password.setEchoChar('%'); to the constructor
public class Authenticator extends javax.swing.JFrame {
JTextField username = new JTextField(15);
JPasswordField password = new JPasswordField(15);
//...
public Authenticator () {
super("Account Information");
password.setEchoChar('%');
//...
JPasswordField password = new JPasswordField(15);
{
password.setEchoChar('%');
}
You can do that in an initializer block, but unless you have initialization code that is common to a number of constructors, it's considered good style to do it in the constructor.
Related
this is the code of the Gui Design class and below is the Class that provides functionality to the program. Im trying to get user input from the textfields so i can remove the text using the clearAll method and also save user input using the saveit method.I tried using nameEntry.setText(""); in the clearAll method but it wont work can someone help me please!
//Import Statements
import javax.swing.*;
import java.awt.*;
import javax.swing.JOptionPane;
import java.awt.event.*;
//Class Name
public class Customer extends JFrame {
Function fun = new Function();
public static void main(String[]args){
Customer.setLookAndFeel();
Customer cust = new Customer();
}
public Customer(){
super("Resident Details");
setSize(500,500);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
FlowLayout two = new FlowLayout(FlowLayout.LEFT);
setLayout(two);
JPanel row1 = new JPanel();
JLabel name = new JLabel("First Name",JLabel.LEFT);
JTextField nameEntry = new JTextField("",20);
row1.add(name);
row1.add(nameEntry);
add(row1);
JPanel row2 = new JPanel();
JLabel surname = new JLabel("Surname ",JLabel.LEFT);
JTextField surnameEntry = new JTextField("",20);
row2.add(surname);
row2.add(surnameEntry);
add(row2);
JPanel row3 = new JPanel();
JLabel contact1 = new JLabel("Contact Details : Email ",JLabel.LEFT);
JTextField contact1Entry = new JTextField("",10);
FlowLayout newflow = new FlowLayout(FlowLayout.LEFT,10,30);
setLayout(newflow);
row3.add(contact1);
row3.add(contact1Entry);
add(row3);
JPanel row4 = new JPanel();
JLabel contact2 = new JLabel("Contact Details : Phone Number",JLabel.LEFT);
JTextField contact2Entry = new JTextField("",10);
row4.add(contact2);
row4.add(contact2Entry);
add(row4);
JPanel row5 = new JPanel();
JLabel time = new JLabel("Duration Of Stay ",JLabel.LEFT);
JTextField timeEntry = new JTextField("",10);
row5.add(time);
row5.add(timeEntry);
add(row5);
JPanel row6 = new JPanel();
JComboBox<String> type = new JComboBox<String>();
type.addItem("Type Of Room");
type.addItem("Single Room");
type.addItem("Double Room");
type.addItem("VIP Room");
row6.add(type);
add(row6);
JPanel row7 = new JPanel();
FlowLayout amt = new FlowLayout(FlowLayout.LEFT,100,10);
setLayout(amt);
JLabel amount = new JLabel("Amount Per Day ");
JTextField AmountField = new JTextField("\u20ac ",10);
row7.add(amount);
row7.add(AmountField);
add(row7);
JPanel row8 = new JPanel();
FlowLayout prc = new FlowLayout(FlowLayout.LEFT,100,10);
setLayout(prc);
JLabel price = new JLabel("Total Price ");
JTextField priceField = new JTextField("\u20ac ",10);
row8.add(price);
row8.add(priceField);
add(row8);
JPanel row9 = new JPanel();
JButton clear = new JButton("Clear");
row9.add(clear);
add(row9);
JPanel row10 = new JPanel();
JButton save = new JButton("Save");
save.addActionListener(fun);
row10.add(save);
add(row10);
//Adding ActionListners
nameEntry.addActionListener(fun);
clear.addActionListener(fun);
save.addActionListener(fun);
setVisible(true);
}
private static void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
);
} catch (Exception exc) {
// ignore error
}
}
}
//Import Statements
import javax.swing.*;
import java.awt.*;
import java.awt.Color;
import javax.swing.JOptionPane;
import java.awt.event.*;
//Class Name
public class Function implements ActionListener {
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if(command.equals("Add Customer")) {
Login();
}
else if(command.equals("Register")){
Registration();
}
else if(command.equals("Exit")){
System.exit(0);
}
else if(command.equals("Clear")){
ClearAllFields();
}
else if(command.equals("Save")){
SaveIt();
}
}
public static void Login(){
Customer cust = new Customer();
}
public static void Registration(){
//Do Nothing
}
//This clears all the text from the JTextFields
public static void ClearAllFields(){
}
//This will save Info on to another Class
public static void SaveIt(){
}
}
Alternatively, you can make nameEntry known to the Function class by defining it before calling the constructor for Function and then passing it into the constructor, like:
JTextField nameEntry = new JTextField("",20);
Function fun = new Function(nameEntry);
Then, in Function, add nameEntry as a member variable of Function and make a constructor for Function which accepts nameEntry, (right after the "public class Function..." line), like:
JTextField nameEntry;
public Function(JTextField nameEntry) {
this.nameEntry = nameEntry;
}
Now, the following will compile:
public void ClearAllFields(){
nameEntry.setText("");
}
And, the Clear button will clear the name field.
Again as per comments, one simple way to solve this is to give the gui public methods that the controller (the listener) can call, and then pass the current displayed instance of the GUI into the listener, allowing it to call any public methods that the GUI might have. The code below is simpler than yours, having just one JTextField, but it serves to illustrate the point:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class GUI extends JPanel {
private JTextField textField = new JTextField(10);
private JButton clearButton = new JButton("Clear");
public GUI() {
// pass **this** into the listener class
MyListener myListener = new MyListener(this);
clearButton.addActionListener(myListener);
clearButton.setMnemonic(KeyEvent.VK_C);
add(textField);
add(clearButton);
}
// public method in GUI that will do the dirty work
public void clearAll() {
textField.setText("");
}
// other public methods here to get text from the JTextFields
// to set text, and do whatever else needs to be done
private static void createAndShowGui() {
GUI mainPanel = new GUI();
JFrame frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
class MyListener implements ActionListener {
private GUI gui;
// use constructor parameter to set a field
public MyListener(GUI gui) {
this.gui = gui;
}
#Override
public void actionPerformed(ActionEvent e) {
gui.clearAll(); // call public method in field
}
}
A better and more robust solution is to structure your program in a Model-View-Controller fashion (look this up), but this would probably be overkill for this simple academic exercise that you're doing.
My code is messy so you might not be able to follow it, but I am trying to make a YouTube to MP3 converter.
It opens up a JPanel for the user to type in the YouTube URL. When I try to get the text from the JTextField, I had to make my method return a value so i can use the value in my other class, and I think that is causing my code not to work.
If someone could help me out, that would be great. I am really new to Java coding and I'm not sure why I chose such a complicated program, but I almost have it done. This is the last part then the cosmetics and cleaning up the code starts :)
My code:
public class Bank_Statement extends JFrame {
// width & height of window
private static final int WIDTH = 500;
private static final int HEIGHT = 500;
public static final Keys text = null;
final ActionListener convertButtonHandler = null;
static Scanner console = new Scanner(System.in);
static String M1;
public static String Bank_Statement1() {
//create/set labels
JButton skinny = new JButton("Convert");
skinny.addActionListener(new ButtonListener());
JPanel buttonPane = new JPanel();
buttonPane.add(skinny);
JButton skinny2 = new JButton("Paste");
JPanel buttonPane2 = new JPanel();
buttonPane2.add(skinny2);
JTextField text;
text = new JTextField(" ");
JPanel textPane = new JPanel();
textPane.add(text);
JTextField text2 = new JTextField("----------------------------------------WAIT LIST----------------------------------------");
JPanel textPane2 = new JPanel();
textPane2.add(text2);
JFrame frame = new JFrame("Youtube Converter");
frame.setSize(WIDTH, HEIGHT);
frame.add(textPane, BorderLayout.WEST);
frame.add(buttonPane2, BorderLayout.CENTER);
frame.add(buttonPane, BorderLayout.EAST);
frame.add(textPane2, BorderLayout.PAGE_END);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
return text.getText();
}
public static void main(String[] args) {
Bank_Statement recObject = new Bank_Statement();
}
}
class ButtonListener implements ActionListener {
ButtonListener() {}
public void actionPerformed(ActionEvent e) {
WebDriver driver = new HtmlUnitDriver();
driver.get("http://www.youtubeinmp3.com/");
String J = Bank_Statement.Bank_Statement1();
driver.findElement(By.id("video")).sendKeys(J + Keys.ENTER);
driver.findElement(By.id("download")).click();
String L= driver.getCurrentUrl();
System.out.println(L);
try {
Runtime.getRuntime().exec(new String[] {"cmd", "/c","start chrome " + L});
} catch (IOException e1) {
e1.printStackTrace();
}
driver.quit();
}
}
return text.getText();
Will be executed right after the Windows appears. It does not wait until the user enters some text.
Try the following:
public class Bank_Statement extends JFrame {
private JTextField text;
public static Bank_Statement bank_statement;
public Bank_Statement() {
//create/set labels
JButton skinny = new JButton("Convert");
skinny.addActionListener(new ButtonListener());
text = new JTextField(" ");
JPanel textPane = new JPanel();
textPane.add(text);
...
frame.setVisible(true);
}
public String getText(){
return text.getText();
}
public static void main(String[] args) {
bank_statement = new Bank_Statement();
}
}
class ButtonListener implements ActionListener {
ButtonListener() {}
public void actionPerformed(ActionEvent e) {
String J = Bank_Statement.bank_statement.getText();
System.out.println(J);
}
}
I removed a few lines in the middle to keep it compact. I hope it is clear, ask otherwise. The design is quite bad, but I didn't want to change to mutch of your code.
Well, first of all, I assume this is your constructor for the Bank_Statement class
public static String Bank_Statement1() {
//create/set labels
JButton skinny = new JButton("Convert");
skinny.addActionListener(new ButtonListener());
JPanel buttonPane = new JPanel();
buttonPane.add(skinny);
JButton skinny2 = new JButton("Paste");
JPanel buttonPane2 = new JPanel();
buttonPane2.add(skinny2);
JTextField text;
text = new JTextField(" ");
JPanel textPane = new JPanel();
textPane.add(text);
JTextField text2 = new JTextField("----------------------------------------WAIT LIST----------------------------------------");
JPanel textPane2 = new JPanel();
textPane2.add(text2);
JFrame frame = new JFrame("Youtube Converter");
frame.setSize(WIDTH, HEIGHT);
frame.add(textPane, BorderLayout.WEST);
frame.add(buttonPane2, BorderLayout.CENTER);
frame.add(buttonPane, BorderLayout.EAST);
frame.add(textPane2, BorderLayout.PAGE_END);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
return text.getText();
}
This is an incorrect use of a constructor.
In this case, your constructor should be declared as:
public static Bank_Statement(){
//constructor code goes here
}
then you can declare a getter method for your JTextField value like so:
public String getText(){
return text.getText();
}
then you should be able to call that method (getText) in any method once the object is instantiated. Like this:
public static void main(String[] args){
//just an example...you wouldn't really want to do this
Bank_Statement recObject = new Bank_Statement();
recObject.getText();
}
But overall this solution is not a "good" fix because there are many other ways to do it that are considered better. This will simply fix your error you are having. I would look into understanding classes and objects better before you continue. :)
So I am attempting to create a login screen that prompts the user with a text box and 2 buttons (Login and Cancel). When the user hits login, I want the value of the JTextField to be stored in a variable or at least be usable. When I attempt to do anything with the playerNameTxt.getText() method, I get an error as if playerNameTxt doesn't exist.
public class GUI extends JPanel implements ActionListener {
protected JTextField playerNameTxt;
public GUI() {
JTextField playerNameTxt = new JTextField(20);
JLabel playerNameLbl = new JLabel("Enter Player Name");
JButton loginBtn = new JButton("Login");
loginBtn.setVerticalTextPosition(AbstractButton.BOTTOM);
loginBtn.setHorizontalTextPosition(AbstractButton.LEFT);
loginBtn.setMnemonic(KeyEvent.VK_D);
loginBtn.setActionCommand("login");
loginBtn.addActionListener(this);
loginBtn.setToolTipText("Click this to Login");
JButton cancelBtn = new JButton("Cancel");
cancelBtn.setVerticalTextPosition(AbstractButton.BOTTOM);
cancelBtn.setHorizontalTextPosition(AbstractButton.RIGHT);
cancelBtn.setMnemonic(KeyEvent.VK_M);
cancelBtn.setActionCommand("cancel");
cancelBtn.addActionListener(this);
cancelBtn.setToolTipText("Click this to Cancel");
add(playerNameLbl);
add(playerNameTxt);
add(loginBtn);
add(cancelBtn);
}
public void actionPerformed(ActionEvent e) {
if ("login".equals(e.getActionCommand())) {
System.out.println(playerNameTxt);
} else {
System.exit(0);
}
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("-- Munitions Login --");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(400, 200);
GUI newContentPane = new GUI();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
You firstly declare the field outside of the constructor, then you declare it inside the constructor again, so that it will be deleted after the constructor returns and the GUI was destroyed, and it will not be usable for your class after the constructor has finished. You should change this line:
JTextField playerNameTxt = new JTextField(20);
to this:
playerNameTxt = new JTextField(20);
In your constructor, you aren't referencing the instance variable playerNameTxt - you're making a new local variable. You should change JTextField playerNameTxt = new JTextField(20); to playerNameTxt = new JTextField(20); (or this.playerNameTxt = new JTextField(20);) to properly initialize the variable. You should then be able to call methods on it without warnings or errors, assuming everything else is correct.
I have a GUI that verifies a username and password. The other part of the assignment is to read from a file that contains a username and a password and checks to see if it matches what the user put in the text field. If it does match then it will hide the Login page and another page will appear with a "Welcome" message. I have zero experience with text files, where do I put that block of code? I assume it would go in the ActionListener method and not the main method but i'm just lost. I just need a little push in the right direction. Here is what I have so far. Any help would be greatly appreciated. Thanks!
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Color;
import java.awt.Font;
import java.awt.*;
import javax.swing.*;
import java.io.*;
/**
*/
public class PassWordFrame extends JFrame
{
private static final int FIELD_WIDTH = 10;
private static final int FRAME_WIDTH = 500;
private static final int FRAME_HEIGHT = 300;
private JLabel fileRead;
private JLabel instruct;
private JLabel username;
private JLabel password;
private JTextField usertext;
private JTextField passtext;
private JButton login;
private ActionListener listener;
//String text = "";
public PassWordFrame()
{
createComponents();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
listener = new ClickListener();
}
class ClickListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String inputFileName = ("users.txt");
File userFile = new File(inputFileName);
}
}
public void createComponents()
{
Color blue = new Color(0,128,155);
Font font = new Font("Times New Roman", Font.BOLD, 14);
instruct = new JLabel("Please enter your username and password.");
instruct.setFont(font);
username = new JLabel("Username: ");
username.setFont(font);
password = new JLabel("Password: ");
password.setFont(font);
usertext = new JTextField(FIELD_WIDTH);
passtext = new JTextField(FIELD_WIDTH);
login = new JButton("Login");
login.setFont(font);
instruct.setForeground(Color.BLACK);
login.setForeground(Color.BLACK);
username.setForeground(Color.BLACK);
password.setForeground(Color.BLACK);
login.addActionListener(listener);
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
panel1.setBackground(blue);
panel2.setBackground(blue);
panel3.setBackground(blue);
panel4.setBackground(blue);
panel1.add(instruct);
panel2.add(username);
panel2.add(usertext);
panel3.add(password);
panel3.add(passtext);
panel4.add(login);
add(panel1, BorderLayout.NORTH);
add(panel2, BorderLayout.WEST);
add(panel3, BorderLayout.CENTER);
add(panel4, BorderLayout.SOUTH);
pack();
}
}
import javax.swing.*;
import java.awt.*;
/**
*/
public class PassWordFrameViewer
{
public static void main(String[] args)
{
JFrame frame = new PassWordFrame();
frame.setTitle("Password Verification");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
First of all you initialize the listener (listener = new ClickListener()) after the call to #createComponents() method so this means you will add a null listener to the login button. So your constructor should look like this:
public PassWordFrame() {
listener = new ClickListener();
createComponents();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
Then, because you want to change the GUI with a welcome message, you should use a SwingWorker, a class designed to perform GUI-interaction tasks in a background thread. In the javadoc you can find nice examples, but here is also a good tutorial: Worker Threads and SwingWorker.
Below i write you only the listener implementation (using a swing worker):
class ClickListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
new SwingWorker<Boolean, Void>() {
#Override
protected Boolean doInBackground() throws Exception {
String inputFileName = ("users.txt");
File userFile = new File(inputFileName);
BufferedReader reader = new BufferedReader(new FileReader(userFile));
String user;
String pass;
try {
user = reader.readLine();
pass = reader.readLine();
}
catch (IOException e) {
//
// in case something is wrong with the file or his contents
// consider login failed
user = null;
pass = null;
//
// log the exception
e.printStackTrace();
}
finally {
try {
reader.close();
} catch (IOException e) {
// ignore, nothing to do any more
}
}
if (usertext.getText().equals(user) && passtext.getText().equals(pass)) {
return true;
} else {
return false;
}
}
#Override
protected void done() {
boolean match;
try {
match = get();
}
//
// this is a learning example so
// mark as not matching
// and print exception to the standard error stream
catch (InterruptedException | ExecutionException e) {
match = false;
e.printStackTrace();
}
if (match) {
// show another page with a "Welcome" message
}
}
}.execute();
}
}
Another tip: don't add components to a JFrame, so replace this:
add(panel1, BorderLayout.NORTH);
add(panel2, BorderLayout.WEST);
add(panel3, BorderLayout.CENTER);
add(panel4, BorderLayout.SOUTH);
with:
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.add(panel1, BorderLayout.NORTH);
contentPane.add(panel2, BorderLayout.WEST);
contentPane.add(panel3, BorderLayout.CENTER);
contentPane.add(panel4, BorderLayout.SOUTH);
setContentPane(contentPane);
assume there is a textfile named password.txt in g driver and it contain usename and password separate by # symbol.
like following
password#123
example code
package homework;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Color;
import java.awt.Font;
import java.awt.*;
import javax.swing.*;
import java.io.*;
public class PassWordFrame extends JFrame
{
private static final int FIELD_WIDTH = 10;
private static final int FRAME_WIDTH = 500;
private static final int FRAME_HEIGHT = 300;
private JLabel fileRead;
private JLabel instruct;
private JLabel username;
private JLabel password;
private JTextField usertext;
private JTextField passtext;
private JButton login;
private ActionListener listener;
//String text = "";
public PassWordFrame()
{
createComponents();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
login.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
String info = ReadFile();
System.out.println(info);
String[] split = info.split("#");
String uname=split[0];
String pass =split[1];
if(usertext.getText().equals(uname) && passtext.getText().equals(pass)){
instruct.setText("access granted");
}else{
instruct.setText("access denided");
}
}
});
}
private static String ReadFile(){
String line=null;
String text="";
try{
FileReader filereader=new FileReader(new File("G:\\password.txt"));
//FileReader filereader=new FileReader(new File(path));
BufferedReader bf=new BufferedReader(filereader);
while((line=bf.readLine()) !=null){
text=text+line;
}
bf.close();
}catch(Exception e){
e.printStackTrace();
}
return text;
}
public void createComponents()
{
Color blue = new Color(0,128,155);
Font font = new Font("Times New Roman", Font.BOLD, 14);
instruct = new JLabel("Please enter your username and password.");
instruct.setFont(font);
username = new JLabel("Username: ");
username.setFont(font);
password = new JLabel("Password: ");
password.setFont(font);
usertext = new JTextField(FIELD_WIDTH);
passtext = new JTextField(FIELD_WIDTH);
login = new JButton("Login");
login.setFont(font);
instruct.setForeground(Color.BLACK);
login.setForeground(Color.BLACK);
username.setForeground(Color.BLACK);
password.setForeground(Color.BLACK);
login.addActionListener(listener);
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
panel1.setBackground(blue);
panel2.setBackground(blue);
panel3.setBackground(blue);
panel4.setBackground(blue);
panel1.add(instruct);
panel2.add(username);
panel2.add(usertext);
panel3.add(password);
panel3.add(passtext);
panel4.add(login);
add(panel1, BorderLayout.NORTH);
add(panel2, BorderLayout.WEST);
add(panel3, BorderLayout.CENTER);
add(panel4, BorderLayout.SOUTH);
pack();
}
}
I have main class with a main GUI from where I want to activate and get values from a new class with a JOptionPane like the code below. Since I already have a main GUI window opened, how and where should I activate/call the class below and finally, how do I get the values from the JOptionPane? Help is preciated! Thanks!
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class OptionPaneTest {
JPanel myPanel = new JPanel();
JTextField field1 = new JTextField(10);
JTextField field2 = new JTextField(10);
myPanel.add(field1);
myPanel.add(field2);
JOptionPane.showMessageDialog(null, myPanel);
}
Edit:
InputNewPerson nyPerson = new InputNewPerson();
JOptionPane.showMessageDialog(null, nyPerson);
String test = nyPerson.inputName.getText();
I guess looking at your question, you need something like this. I had made a small JDialog, where you will enter a UserName and Answer, this will then be passed to the original GUI to be shown in the respective fields, as you press the SUBMIT JButton.
Try your hands on this code and ask any question that may arise :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
* This is the actual GUI class, which will get
* values from the JDIalog class.
*/
public class GetDialogValues extends JFrame
{
private JTextField userField;
private JTextField questionField;
public GetDialogValues()
{
super("JFRAME");
}
private void createAndDisplayGUI(GetDialogValues gdv)
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
JPanel contentPane = new JPanel();
contentPane.setLayout(new GridLayout(0, 2));
JLabel userName = new JLabel("USERNAME : ");
userField = new JTextField();
JLabel questionLabel = new JLabel("Are you feeling GOOD ?");
questionField = new JTextField();
contentPane.add(userName);
contentPane.add(userField);
contentPane.add(questionLabel);
contentPane.add(questionField);
getContentPane().add(contentPane);
pack();
setVisible(true);
InputDialog id = new InputDialog(gdv, "Get INPUT : ", true);
}
public void setValues(final String username, final String answer)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
userField.setText(username);
questionField.setText(answer);
}
});
}
public static void main(String... args)
{
Runnable runnable = new Runnable()
{
public void run()
{
GetDialogValues gdv = new GetDialogValues();
gdv.createAndDisplayGUI(gdv);
}
};
SwingUtilities.invokeLater(runnable);
}
}
class InputDialog extends JDialog
{
private GetDialogValues gdv;
private JTextField usernameField;
private JTextField questionField;
private JButton submitButton;
private ActionListener actionButton = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
if (usernameField.getDocument().getLength() > 0
&& questionField.getDocument().getLength() > 0)
{
gdv.setValues(usernameField.getText().trim()
, questionField.getText().trim());
dispose();
}
else if (usernameField.getDocument().getLength() == 0)
{
JOptionPane.showMessageDialog(null, "Please Enter USERNAME."
, "Invalid USERNAME : ", JOptionPane.ERROR_MESSAGE);
}
else if (questionField.getDocument().getLength() == 0)
{
JOptionPane.showMessageDialog(null, "Please Answer the question"
, "Invalid ANSWER : ", JOptionPane.ERROR_MESSAGE);
}
}
};
public InputDialog(GetDialogValues gdv, String title, boolean isModal)
{
this.gdv = gdv;
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setLayout(new BorderLayout());
setModal(isModal);
setTitle(title);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 2));
JLabel usernameLabel = new JLabel("Enter USERNAME : ");
usernameField = new JTextField();
JLabel questionLabel = new JLabel("How are you feeling ?");
questionField = new JTextField();
panel.add(usernameLabel);
panel.add(usernameField);
panel.add(questionLabel);
panel.add(questionField);
submitButton = new JButton("SUBMIT");
submitButton.addActionListener(actionButton);
add(panel, BorderLayout.CENTER);
add(submitButton, BorderLayout.PAGE_END);
pack();
setVisible(true);
}
}
JOPtionPane provides a number of preset dialog types that can be used. However, when you are trying to do something that does not fit the mold of one of those types, it is best to create your own dialog by making a sub-class of JDialog. Doing this will give you full control over how the controls are laid out and ability to respond to button clicks as you want. You will want to add an ActionListener for the OK button. Then, in that callback, you can extract the values from the text fields.
The process of creating a custom dialog should be very similar to how you created the main window for your GUI. Except, instead of extending JFrame, you should extend JDialog. Here is a very basic example. In the example, the ActionListener just closes the dialog. You will want to add more code that extracts the values from the text fields and provides them to where they are needed in the rest of your code.