I'm creating a user name confirm box, and I need to confirm if the text typed into the text field matches with the already defined type in a variable name.
I don't know how to get it. I had been trying by implementing the following code, which in the action performed once the button is pressed it will verify if the textfield matches with the variable name.
code is as follows.
public class Action extends JFrame implements ActionListener
{
JLabel l;
JTextField t;
JButton b;
final String name = "harry";
public Action()
{
l = new JLabel("Name");
l.setBounds(10, 10, 100, 33);
t = new JTextField();
t.setBounds(60, 10, 100, 30);
b = new JButton("send text");
b.setBounds(80, 120, 100, 40);
add(l);
add(t);
add(b);
setSize(300, 300);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e)
{
if (t.getText() == name)
{
JOptionPane.showMessageDialog(this, "you mach");
}
else
{
JOptionPane.showMessageDialog(this, "you dont");
}
}
public static void main(String[] args)
{
new Action();
}
}
In your Action() constructor, you have to add an actionlistener to the frame:
addActionListener(this);
in order for it to work;
Also, you compare strings by .equals() because strings are objects. Stack does not store the string's value, the heap does. To compare the string's value, you have to call t.getText().equals(name)
Change that in your actionPerformed() class and you are good to go!
Related
I want to update JLabel's text when clicking on JButton.
The problem is that they are on different classes.
I minimized my code as much as I can, so this code doesn't contain every code that I actually have.
Below is the 1st Panel's code, which contains a button that will trigger the text updating method.
public class CultureCategorySelectPanel extends JPanel {
public CultureCategorySelectPanel(JFrame mf) {
setVisible(true);
setLayout(null);
setSize(1000, 600);
JButton bookCategoryBtn = new JButton("Book");
// When Clicking on JButton
bookCategoryBtn.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
mf.getContentPane().removeAll();
CultureListPanel myPanel = new CultureListPanel(mf);
mf.getContentPane().add(myPanel);
String text = “This text will be shown”;
myPanel.updateLabel(text);
mf.setVisible(true);
mf.repaint();
}
});
}
}
And the below is the 2nd Panel's code, which has a textLabel that will be updated.
private JLabel plzSelectLabel;
public CultureListPanel(JFrame mf) {
setVisible(true);
setLayout(null);
setSize(1000, 600);
JLabel plzSelectLabel = new JLabel(“This text soon be changed”);
plzSelectLabel.setHorizontalAlignment(SwingConstants.CENTER);
plzSelectLabel.setBounds(138, 89, 367, 34);
rightPanel.add(plzSelectLabel);
// 'rightPanel' is on the top of CultureListPanel, I put plzSelectLabel on the panel called 'rightPanel'
}
public void updateLabel(String text) {
plzSelectLabel.setText(text);
}
When I run, I got Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at com.kh.mini_Project.view.CultureListPanel.updateLabel(CultureListPanel.java:169) error.
I also tried with getter/setter but it shows the same error.
EDIT
The code below is MainFrame.
import javax.swing.JFrame;
public class MainFrame extends JFrame{
public MainFrame() {
this.setTitle("--");
this.setSize(1000, 600);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.getContentPane().add(new WelcomPage(this));
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
EDIT
The Driver class is here.
public class Run {
public static void main(String[] args) {
new MainFrame();
}
}
Your constructor defines a variable plzSelectLabel which has a local (constructor) scope. Therefor the class level variable (with the same name) will not be initialized hence the NPE.
Hint: read some information about variable scopes ;-)
what do I have to add to the code below so that the user has to enter a specific word i.e. "London" to open the JOptionPane input dialog box.
JFrame frame = new JFrame("JTextField");
JTextField textfield = new JTextField(30);
frame.add(textfield);
At the moment I can type in anything in the text field and the dialog box will appear. I only want it to open if the user enters a specific word.
I'm using the action event with action listener and action performed to open the JOptionPane Dialog box.
public class Test9 {
public static void main(String[] args) {
JFrame frame = new JFrame("JTextField");
JTextField textfield = new JTextField(30);
frame.add(textfield);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,200);
JPanel panel = new JPanel();
frame.add(panel);
panel.add(textfield);
textfield.addActionListener(new Action4());
}
}
You can do something like this.
if(museum_name.equals("London")){
JOptionPane.showMessageDialog(null, " You are attending the " + museum_name);
} else{
// show the error message
}
Its encouraged to use equals() method for String comparison. Please note, equals() is used to compare two strings for equality, while operator == compares the reference of an object in java.
Update
To show an error message if the input is not "London", you can do something like this.
static class Action4 implements ActionListener {
#Override
public void actionPerformed(java.awt.event.ActionEvent e) {
String museum_name = ((JTextField) e.getSource()).getText();
if (museum_name.equals("London")) {
JOptionPane.showMessageDialog(null, "You are attending the " + museum_name);
} else {
JOptionPane.showMessageDialog(null, "Wrong input!");
}
}
}
I'm trying to refer to my class in a method within a action listener so I can pass it though the method. My code looks a little something like this:
My MainPanel Class:
public class MainPanel extends JPanel{
private JButton submitButton;
JTextArea consoleOutput;
public MainPanel(){
Border border = BorderFactory.createLineBorder(Color.LIGHT_GRAY);
setLayout(null);
setBackground(Color.WHITE);
Font f1 = new Font("Arial", Font.PLAIN, 14);
submitButton = new JButton("Get Cards");
submitButton.setBounds(35, 285, 107, 49);
submitButton.setFont(f1);
consoleOutput = new JTextArea();
consoleOutput.setBounds(199, 122, 375 , 210);
consoleOutput.setBorder(BorderFactory.createCompoundBorder(border, BorderFactory.createEmptyBorder(3, 4, 0, 0)));
consoleOutput.setEditable(false);
consoleOutput.setFont(f1);
submitButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String username;
String password;
Cards cards = new Cards();
cards.openTabs(username, password, this); //THIS IS THE METHOD IM TRYING TO PASS THE CLASS INTO
}
});
add(submitButton);
add(consoleOutput);
}
}
My Cards Class:
public class Cards{
public void openTabs(String username, String password, MainPanel panel){
panel.consoleOutput.setText(username + ", " + password);
}
In eclipse it underlines the method in my MainPanel and this is the problem or error is has:
The method openTabs(String, String, MainPanel) in the type Cards is not applicable for the arguments (String, String, new ActionListener(){})
What should I do? What should I pass in instead of this because it seems not not be working. I'm lost and have no idea what to do, Any help is appreciated!!
Your problem is that you are using this within an anonymous inner class. In other words: this this has not the usual meaning of this - it doesn't refer the "outer" MainPanel object, but the inner ActionListener object!
You have to use MainPanel.this instead!
I am currently developing a java application.
I want to show a new Window which contains a text area and a button.
Do you have any ideas?
The same answer : JOptionpane with an example :)
package experiments;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class CreateDialogFromOptionPane {
public static void main(final String[] args) {
final JFrame parent = new JFrame();
JButton button = new JButton();
button.setText("Click me to show dialog!");
parent.add(button);
parent.pack();
parent.setVisible(true);
button.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
String name = JOptionPane.showInputDialog(parent,
"What is your name?", null);
}
});
}
}
Hmm it has been a little while but from what I remember...
If you want a custom window you can just make a new frame and make it show up just like you would with the main window.
Java also has a great dialog library that you can check out here:
How to Make Dialogs
That may be able to give you the functionality you are looking for with a whole lot less effort.
Object[] possibilities = {"ham", "spam", "yam"};
String s = (String)JOptionPane.showInputDialog(
frame,
"Complete the sentence:\n"
+ "\"Green eggs and...\"",
"Customized Dialog",
JOptionPane.PLAIN_MESSAGE,
icon,
possibilities,
"ham");
//If a string was returned, say so.
if ((s != null) && (s.length() > 0)) {
setLabel("Green eggs and... " + s + "!");
return;
}
//If you're here, the return value was null/empty.
setLabel("Come on, finish the sentence!");
If you do not care to limit the user's choices, you can either use a form of the showInputDialog method that takes fewer arguments or specify null for the array of objects. In the Java look and feel, substituting null for possibilities results in a dialog that has a text field and looks like this:
JOptionPane is your friend : http://www.javalobby.org/java/forums/t19012.html
Check out Swing Dialogs (mainly focused on JOptionPane, as mentioned by #mcfinnigan).
public class JSONPage {
Logger log = Logger.getLogger("com.prodapt.autotest.gui.design.EditTestData");
public static final JFrame JSONFrame = new JFrame();
public final JPanel jPanel = new JPanel();
JLabel IdLabel = new JLabel("JSON ID*");
JLabel DataLabel = new JLabel("JSON Data*");
JFormattedTextField JId = new JFormattedTextField("Auto Generated");
JTextArea JData = new JTextArea();
JButton Cancel = new JButton("Cancel");
JButton Add = new JButton("Add");
public void JsonPage() {
JSONFrame.getContentPane().add(jPanel);
JSONFrame.add(jPanel);
JSONFrame.setSize(400, 250);
JSONFrame.setResizable(false);
JSONFrame.setVisible(false);
JSONFrame.setTitle("Add JSON Data");
JSONFrame.setLocationRelativeTo(null);
jPanel.setLayout(null);
JData.setWrapStyleWord(true);
JId.setEditable(false);
IdLabel.setBounds(20, 30, 120, 25);
JId.setBounds(100, 30, 120, 25);
DataLabel.setBounds(20, 60, 120, 25);
JData.setBounds(100, 60, 250, 75);
Cancel.setBounds(80, 170, 80, 30);
Add.setBounds(280, 170, 50, 30);
jPanel.add(IdLabel);
jPanel.add(JId);
jPanel.add(DataLabel);
jPanel.add(JData);
jPanel.add(Cancel);
jPanel.add(Add);
SwingUtilities.updateComponentTreeUI(JSONFrame);
Cancel.addActionListener(new ActionListener() {
#SuppressWarnings("deprecation")
#Override
public void actionPerformed(ActionEvent e) {
JData.setText("");
JSONFrame.hide();
TestCasePage.testCaseFrame.show();
}
});
Add.addActionListener(new ActionListener() {
#SuppressWarnings("deprecation")
#Override
public void actionPerformed(ActionEvent e) {
try {
PreparedStatement pStatement = DAOHelper.getInstance()
.createJSON(
ConnectionClass.getInstance()
.getConnection());
pStatement.setString(1, null);
if (JData.getText().toString().isEmpty()) {
JOptionPane.showMessageDialog(JSONFrame,
"Must Enter JSON Path");
} else {
// System.out.println(eleSelectBy);
pStatement.setString(2, JData.getText());
pStatement.executeUpdate();
JOptionPane.showMessageDialog(JSONFrame, "!! Added !!");
log.info("JSON Path Added"+JData);
JData.setText("");
JSONFrame.hide();
}
} catch (SQLException e1) {
JData.setText("");
log.info("Error in Adding JSON Path");
e1.printStackTrace();
}
}
});
}
}
Try Using JOptionPane or Swt Shell .
After the password is entered i want the window to disappear and pop a new window.
JButton btnEnter = new JButton("Enter");
btnEnter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
if(passwordField.equals("test"))
{
frame.setVisible(false);
}
else if(!passwordField.equals("test"))
{
JOptionPane.showMessageDialog(null,"Access Denied!!");
}
}
});
btnEnter.setBounds(149, 184, 117, 29);
frame.getContentPane().add(btnEnter);
I'm assuming passwordField is a JTextField, if so, you need to get the text from it, just .getText() I think and store that in a string. Then test the string. At the moment you are testing if your JTextField equals the string.
Create 2 JFrames and make a reference for each one:
JFrame oldFrame = new JFrame();
// ...
JFrame newFrame = new JFrame();
// ...
// ...
if(passwordField.equals("test"))
{
oldFrame.setVisible(false);
newFrame.setVisible(true);
}