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.
Related
The code below works as such:
User clicks the run button
Program reads the file from designated location
Program removes content from <script> </script>, including tags themselves
Program returns edited text into JTextArea called textArea
I've tried making it a global variable since it's in two different classes. The run down is that once the user clicks the "run button", the text area initialised in the GUI class will update.
public class GUI{
static JTextArea textArea;
public GUI() {
JFrame frame = new JFrame();
textArea = new JTextArea(5,30);
JButton runButton = new JButton("Remove JS");
JButton importButton = new JButton("Import File");
JPanel panel = new JPanel();
runButton.addActionListener(new runApp());
runButton.setBounds(100, 100, 100, 80);
importButton.addActionListener(new importFile());
importButton.setBounds(100, 100, 80, 60);
panel.setBorder(BorderFactory.createEmptyBorder(300, 300 , 150, 150));
panel.setLayout(new GridLayout(0, 1));
panel.add(textArea);
panel.add(runButton);
panel.add(importButton);
frame.add(panel, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("JavaScript Extractor");
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
new GUI();
}
}
class runApp implements ActionListener{
public void actionPerformed(ActionEvent arg0) {
RemoveScript run = new RemoveScript();
try {
File fileObject = new File("C:\\Users\\coker\\Documents\\readJS.txt");
Scanner reader = new Scanner(fileObject);
while(reader.hasNextLine()) {
String output = reader.nextLine();
textArea.setText(run.removeScript(output));
}
reader.close();
}catch(FileNotFoundException e) {
System.out.println("An error has occured.");
e.printStackTrace();
}
}
}
3 options:
Make your listener class an inner class of GUI, then it will have access to all fields of it's outer class (no need for static in that case)
Keep the 2 classes completely separate, and pass a reference to the text field to the listener (e.g. via constructor parameter).
access the static field via GUI.textArea
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. :)
I've been working on creating a simple GUI through the use of JPanels. I've managed to what I believe fluke a reasonably looking layout and now I would like the user to be able to input values into the Mass textbox and the Acceleration textbox so when they hit calculate they are given a message telling them the Force.
The issue I am having is within the public void that is added to the buttons, I can't seem to figure out how to refer to values within the text field. I've tried to just refer to it generally by:
String mass = txts[1].getText();
However this doesn't recognise txts as existing?
Any help on this would be much appreciated.
Below is the full code in case it helps.
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.event.*;
import java.awt.*;
public class InitScreen {
public static void createHomeScreen() {
/*Creates a Java Frame with the Window Name = HomeScreen*/
JFrame frame = new JFrame("HomeScreen");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.getContentPane().setPreferredSize(new Dimension(400,300));
frame.pack();
/*Creates the main JPanel in form of GridLayout*/
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
mainPanel.setBorder(new EmptyBorder(new Insets(20,20,20,20)));
/*Creates the first sub panel*/
JPanel firstPanel = new JPanel();
firstPanel.setLayout(new GridLayout(1,2,75,100));
firstPanel.setMaximumSize(new Dimension(300,100));
/*Creates the buttons in the first sub panel*/
JButton[] btns = new JButton[2];
String bText[] = {"Calculate", "Clear"};
for (int i=0; i<2; i++) {
btns[i] = new JButton(bText[i]);
btns[i].setPreferredSize(new Dimension(100, 50));
btns[i].setActionCommand(bText[i]);
btns[i].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
String choice = e.getActionCommand();
/*JOptionPane.showMessageDialog(null, "Clicked "+choice);*/
JOptionPane.showMessageDialog(null, "Force = ");
}
});
firstPanel.add(btns[i]);
}
/*Creates the second sub panel*/
JPanel secondPanel = new JPanel();
secondPanel.setLayout(new BorderLayout());
/*Creates the labels for the second sub panel*/
JLabel label = new JLabel("Calculate the Force of an Object", SwingConstants.CENTER);
secondPanel.add(label,BorderLayout.NORTH);
/*Creates the third sub Panel for entering values*/
JPanel thirdPanel = new JPanel();
thirdPanel.setLayout(new GridLayout(3,1,10,10));
thirdPanel.setMaximumSize(new Dimension(400,100));
/*Create labels and text fields for third sub panel*/
String lText[] = {"Mass of Body", "Acceleration of Body", "Force"};
JLabel[] lbls = new JLabel[3];
JTextField[] txts = new JTextField[3];
for (int i=0; i<3; i++) {
txts[i] = new JTextField();
lbls[i] = new JLabel(lText[i], SwingConstants.LEFT);
lbls[i].setPreferredSize(new Dimension(50, 50));
thirdPanel.add(lbls[i]);
thirdPanel.add(txts[i]);
}
mainPanel.add(secondPanel);
mainPanel.add(thirdPanel);
mainPanel.add(firstPanel);
frame.setContentPane(mainPanel);
frame.setVisible(true);
}
public static void main(final String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createHomeScreen();
}
});
}
}
First drop the reliance on static, and instead, create an instance of InitScreen and call it's createHomeScreen method
public class InitScreen {
public void createHomeScreen() {
//...
}
public static void main(final String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
InitScreen screen = new InitScreen();
screen.createHomeScreen();
}
});
}
Now, make txts and instance field of InitScreen and use it within your methods
public class InitScreen {
private JTextField[] txts;
public void createHomeScreen() {
//...
txts = new JTextField[3];
//...
}
This takes txts from a local context to a class instance context, meaning you can now access it from any method within InitScreen
I am making a Log in window, so after enter username, password and click login button it will direct you to another frame, which is my GUI that use to insert, retrieve, update, and delete database. However, after click, it displayed nothing. Thank you! Here is my code:
It should redirect to GUI like this:
Login
public class Log extends JFrame {
public static void main(String[] args) {
Log frameTabel = new Log();
}
JButton blogin = new JButton("Login");
JPanel panel = new JPanel();
JTextField txuser = new JTextField(15);
JPasswordField pass = new JPasswordField(15);
Log() {
super("Login Autentification");
setSize(300, 200);
setLocation(500, 280);
panel.setLayout(null);
txuser.setBounds(70, 30, 150, 20);
pass.setBounds(70, 65, 150, 20);
blogin.setBounds(110, 100, 80, 20);
panel.add(blogin);
panel.add(txuser);
panel.add(pass);
getContentPane().add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
actionlogin();
}
public void actionlogin() {
blogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String puname = txuser.getText();
String ppaswd = pass.getText();
if ( puname.equals("test") && ppaswd.equals("12345") ) {
CarSearch regFace = new CarSearch();
// regFace.setVisible(true);
dispose();
} else {
JOptionPane.showMessageDialog(null,
"Wrong Password / Username");
txuser.setText("");
pass.setText("");
txuser.requestFocus();
}
}
});
}
Here is the CarSearch
public class CarSearch {
public static void main(String[] args) {
MainPanel logoPanel = new MainPanel();
JFrame frame = new JFrame("Cars Search");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(logoPanel, BorderLayout.NORTH);
JTabbedPane tabPage = new JTabbedPane();
// tabPage.addTab("Log In", new Log());
tabPage.addTab("Insert Data", new InsertPanel());
tabPage.addTab("Retrieve Data", new RetrievePanel());
tabPage.addTab("Update Data", new UpdatePanel());
tabPage.addTab("Delete Data", new DeletePanel());
frame.getContentPane().add(tabPage, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}
First of all, I don't encourage the use of multiple frames, instead you should use a CardLayout, how ever. Your CarSearch class doesn't do anything, it only has static main method, which you never call.
I would change the class so it has a constructor which initialises the class and a method you can call so you can control when you want to the window shown
public class CarSearch {
private MainPanel logoPanel;
private JFrame frame;
public CarSearch() {
logoPanel = new MainPanel();
frame = new JFrame("Cars Search");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(logoPanel, BorderLayout.NORTH);
JTabbedPane tabPage = new JTabbedPane();
// tabPage.addTab("Log In", new Log());
tabPage.addTab("Insert Data", new InsertPanel());
tabPage.addTab("Retrieve Data", new RetrievePanel());
tabPage.addTab("Update Data", new UpdatePanel());
tabPage.addTab("Delete Data", new DeletePanel());
frame.getContentPane().add(tabPage, BorderLayout.CENTER);
}
public void show() {
frame.pack();
frame.setVisible(true);
}
}
Now, having said that, I'd strongly encourage you to use a CardLayout.
Start by creating a LoginPanel and a CarSearchPanel, then you can add each to the same frame and use the CardLayout to switch between them as needed
For (a slight over the top) example
If that is what you want to do then in your CarSearch class should be a JFrame and in your main method you should have CarSearch frame = new CarSearch("Cars Search") instead of JFrame frame = new JFrame("Cars Search"). Then introduce a method public void authenticated() which should contain the code for enabling the other tabs. Also your initialisation should have all the tabs other than the login tab disabled.
Now in your method public void actionlogin() in your validation condition if ( puname.equals("test") && ppaswd.equals("12345") ) you should have CarSearch frame = (CarSearch)getRootPane(); and after that you could call frame.authenticated(); which will disable the login tab and enable the other tabs.
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.