I am new to coding and I am trying my best, but I am trying to get the gui to submit a name and then have a pop-window say "Your name is:" I know I am missing something obvious, so please be easy on me.
public class Frame1 extends JFrame {
private JPanel panel;
private JTextField NametextField;
public Frame1() {
setTitle("Confirm Name");
getContentPane().setLayout(null);
JLabel lblEnterName = new JLabel("Enter Name:");
lblEnterName.setBounds(10, 22, 83, 14);
getContentPane().add(lblEnterName);
NametextField = new JTextField();
NametextField.setBounds(10, 47, 274, 20);
getContentPane().add(NametextField);
NametextField.setColumns(10);
JButton btnNewButton = new JButton("Submit");
btnNewButton.addActionListener(new Frame2());
panel = new JPanel();
add(panel);
setVisible(true);
btnNewButton.setBounds(20, 78, 89, 23);
getContentPane().add(btnNewButton);
}
private class Frame2 implements ActionListener {
public void actionPerformed(ActionEvent e) {
String actionCommand = e.getActionCommand();
if (actionCommand.contains(getName())); {
JOptionPane.showInputDialog("Your name is: " + NametextField );
}
}
public static void main(String[] args) {
}
JOptionPane.showInputDialog("Your name is: " + NametextField );
You're basically saying "Your name is this text field object". You'll want to use the getText() method of the text field to get the actual text
NametextField.getText()
Note, if (actionCommand.contains(getName())) looks very suspect to me. I'm not sure this is what you want, though I have no idea what getName() returns. I think you want to check if the action command equals the action command of the button you want to check for. In which case you want if ("Submit.equals(actionCommand))
Also note, as pointed out by #Takendarkk , the ; after your parenthesis is negating the if statement, causing the action to be performed, whether or not the if statement is true.
Also note, as pointed out by #MadProgrammer, stay away from the null layout. Learn to use LayoutManagers, and let them do the sizing and positioning for you. See more at Laying out Components Withing a Container
Also note, you should be following Java naming convention. variable names begin with lower case letters, using camel casing: NametextField → nameTextField
Related
I don't know what I am doing wrong. I am trying to take a JTextField user input to be stored and displayed in a JList, but every time the button is pressed to store the user input the JList remains blank. Any help would be greatly appreciated.
DefaultListModel<String> model = new DefaultListModel<String>();
menuList = new JList<String>(model);
menuList.setBounds(500, 65, 300, 400);
menuList.setSelectionBackground(Color.LIGHT_GRAY);
menuList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
btnCreateMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
childFrame = new JFrame("New Menu");
childFrame.setBounds(340, 300, 400, 200);
childFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
childFrame.getContentPane().setLayout(null);
childFrame.setVisible(true);
lblNewMenu = new JLabel("Menu Name:");
lblNewMenu.setBounds(30, 60, 200, 20);
childFrame.getContentPane().add(lblNewMenu);
input = new JTextField();
String userInput = input.getText();
input.setBounds(lblNewMenu.getX() + 80, lblNewMenu.getY(), 250, 30);
childFrame.getContentPane().add(input);
btnMenuInput = new JButton("Create New Menu");
btnMenuInput.setBounds(120, 100, 200, 30);
btnMenuInput.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
model.addElement(userInput);
menuList.setModel(model);
childFrame.setVisible(false);
Entree selectedEntree = (Entree)cboEntrees.getSelectedItem();
Side selectedSide = (Side)cboSides.getSelectedItem();
Salad selectedSalad = (Salad)cboSalads.getSelectedItem();
Dessert selectedDessert = (Dessert)cboDesserts.getSelectedItem();
Menu menu = new Menu(userInput, selectedEntree, selectedSide, selectedSalad, selectedDessert);
menuArray.add(menu);
}
});
childFrame.getContentPane().add(btnMenuInput);
}
});
mainframe.setVisible(true);
This line
userInput = input.getText();
needs to be called first in the ActionListener. Otherwise you never get the latest String from the text field.
e.g.,
public void actionPerformed(ActionEvent e){
userInput = input.getText();
model.addElement(userInput);
//menuList.setModel(model); // not needed
Also, as mentioned by camickr in comment, avoid using null layouts and setBounds as this fights against the Swing GUI library rather than working with it, making it much harder to create flexible easy to update and edit GUI's.
Also, the childFrame top-level window should be a JDialog and not a second JFrame. Please see The Use of Multiple JFrames: Good or Bad Practice? for more on this.
Also note that you should create the entire dialog or Frame before you make it visible, or else some of the items may not be visible at first.
Another problem is the use of JFrame.HIDE_ON_CLOSE. You should probably be using DISPOSE_ON_CLOSE instead. Otherwise the frame will just be hidden, but will still exist, possibly for the life of the program.
I'm pretty new at Java and doing a basic college project. So I first made this class called ScreenDefiner, with an initialized JFrame called mainscreen as a field, and some JButtons and a JLabel (to set the background image), and other irrelevant stuff. Then I made a method called initializeScreen to set the JFrame's main properties, which would never change. Then another method, setScreenBeginning, which would add the buttons to mainscreen and change them, same with any other element in mainscreen that I wanted to change. The idea was to use various setScreen[something] to change what the user sees. But this really isn't working properly. I can't really describe what is happening, it's just bugging pretty hard. The screenshot below shows the most basic error: setScreenBeginning not making anything visible, but still changing the background (so the screenbg.setIcon line inside it must be working... right? Why isn't anything else working then?)
Btw, it works pretty well if I'm initializing and changing the interface in the same method, but my professor wouldn't like that (would be a gigantic method). So I guess there's some java definition/limitation that I don't know of and that keeps me from altering that stuff with outer methods?
Anyone who helps will get sent a photo of a happy strawberry.
The fail:
This is the code(I'm importing javax.swing.* and java.awt.*, but I couldn't paste that part here, guess I'm just a bit tired already):
public class ScreenDefiner {
JFrame mframe = new JFrame();
JLabel screenbg = new JLabel();
JButton pickClassButton = new JButton();
JButton pickClassBrute = new JButton();
JButton pickClassDetective = new JButton();
JButton pickStats = new JButton();
JButton start = new JButton();
JButton help = new JButton();
public void initializeScreen(){
screenbg.setLayout(new BorderLayout());
mframe.setSize(1280, 720);
mframe.setLayout(null);
mframe.setVisible(true);
mframe.setResizable(false);
mframe.setContentPane(screenbg);
mframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void setScreenBeginning() {
screenbg.setIcon(new ImageIcon("C:\\projectScrewed\\media\\images\\startscreen\\bg_basic.png"));
pickClassButton.setIcon(new ImageIcon("C:\\projectScrewed\\media\\images\\startscreen\\button_pickclass.png"));
pickClassBrute.setIcon(new ImageIcon("C:\\projectScrewed\\media\\images\\startscreen\\button_brute.png"));
pickClassDetective.setIcon(new ImageIcon("C:\\projectScrewed\\media\\images\\startscreen\\button_detective.png"));
help.setIcon(new ImageIcon("C:\\projectScrewed\\media\\images\\startscreen\\button_help.png"));
pickStats.setIcon(new ImageIcon("C:\\projectScrewed\\media\\images\\startscreen\\button_pickstats.png"));
start.setIcon(new ImageIcon("C:\\projectScrewed\\media\\images\\startscreen\\button_start.png"));
pickClassButton.setEnabled(true);
pickClassBrute.setEnabled(false);
pickClassDetective.setEnabled(false);
help.setEnabled(true);
pickStats.setEnabled(false);
start.setEnabled(true);
pickClassButton.setVisible(true);
pickClassBrute.setVisible(false);
pickClassDetective.setVisible(false);
help.setVisible(true);
pickStats.setVisible(false);
start.setVisible(false);
pickClassButton.setBounds(970, 159, 200, 96);
pickClassBrute.setBounds(970, 255, 200, 96);
pickClassDetective.setBounds(970, 351, 200, 96);
help.setBounds(970, 447, 200, 96);
pickStats.setBounds(970, 159, 200, 96);
start.setBounds(970, 159, 200, 96);
mframe.add(pickClassButton);
mframe.add(pickClassBrute);
mframe.add(pickClassDetective);
mframe.add(help);
mframe.add(pickStats);
mframe.add(start);
}
public class Main {
public static void main(String[] args) {
ScreenDefiner mainWindow = new ScreenDefiner();
mainWindow.initializeScreen();
mainWindow.setScreenBeginning();
}
I am trying to clear the text in a JTextArea, and looking at other questions, it seems like calling textArea.setText(""/null) will clear the text area. This does not seem to be happening with my code, and it appends the new text to the text already in the area. Can anyone see something wrong in my code?
public class morseJFrame extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
public JTextPane textPane = new JTextPane();
public JTextArea textArea = new JTextArea();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
morseJFrame frame = new morseJFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public morseJFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 508);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textPane.setBounds(5, 5, 424, 194);
textPane.setText("Enter your alphanumberic text here to translate.");
contentPane.add(textPane);
JButton btnTranslate = new JButton("Translate");
btnTranslate.setBounds(5, 419, 213, 41);
btnTranslate.addActionListener(this);
add(btnTranslate);
contentPane.add(btnTranslate);
textArea.setBounds(5, 210, 424, 203);
contentPane.add(textArea);
JButton btnPlaySound = new JButton("Play Morse Sound");
btnPlaySound.setBounds(228, 419, 201, 41);
contentPane.add(btnPlaySound);
}
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("Translate")) {
String text = textPane.getText();
String translatedText = MorseTranslate.doMorse(text);
textArea.setText("");
textArea.setText(translatedText);
}
}
}
This does not seem to be happening with my code, and it appends the new text to the text already in the area
So based on this code...
String text = textPane.getText();
String translatedText = MorseTranslate.doMorse(text);
textArea.setText("");
textArea.setText(translatedText);
I would suggest that the problem is with your MorseTranslate.doMorse which is probably returning the text appended to itself
But, as you can see, this is a matter of "guess work" as we don't have the complete code to go by.
Consider providing a runnable example which demonstrates your problem. This is not a code dump, but an example of what you are doing which highlights the problem you are having. This will result in less confusion and better responses
Try to reverse the order like this:
textArea.setText(translatedText);
textArea.setText("");
Use either textArea.setText(null) or textArea.setText("") are the same thing.
I think setText() replaces the content (not append), so you don't need to do setText("") and then setText("the text you want"), the latest sentence should be enough.
setText("") doesn't clear the text
Yes it does.
textArea.setText("");
Here you are clearing the text area.
textArea.setText(translatedText);
Here, in the very next line, you are setting it to something else.
You could alternatively try:
textArea.setText(null);
See if that works. But I agree with Wyatt, you are setting other text right after clearing it.
Have you inserted a simple print statement to see what textPane.getText() is actually setting String text to before sending it to doMorse(String)?
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!
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Hello I am writing a simple login programme in Java and I am having issues as even when the correct account number and password is entered I still get the 'Please enter the correct Account number/ Password' and I cannot seem to see where the error is
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Main2 extends JFrame{
public static int x=0;
public JPanel panel;
String accountnumber = "123456";
JTextField inputUser;
String password = "admin";
JPasswordField inputPass;
public JLabel lblctr;
public Main2(){
setTitle("Login");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(500, 450, 500, 500);
panel = new JPanel();
setContentPane(panel);
panel.setLayout(null);
inputUser = new JTextField();
inputUser.setBounds(130, 30,125, 20);
panel.add(inputUser);
inputUser.setColumns(10);
inputPass = new JPasswordField();
inputPass.setBounds(130, 60, 125, 20);
panel.add(inputPass);
inputPass.setColumns(10);
lblctr = new JLabel("Attempts:");
lblctr.setBounds(80, 135, 72, 17);
panel.add(lblctr);
JButton cancelbtn = new JButton("Cancel");
cancelbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
System.exit(0);
}
});
JButton loginbtn = new JButton("Login");
loginbtn.addActionListener(new ActionListener(){
#SuppressWarnings("deprecation") public void actionPerformed(ActionEvent arg0){
if((inputUser.getText().equals(accountnumber)) && (inputPass.getPassword().equals(password))){
JOptionPane.showMessageDialog(null,"Press OK to Continue!","Login success!",JOptionPane.INFORMATION_MESSAGE);
}
else{
x++;
if(x>3){
JOptionPane.showMessageDialog(null,"Too many attempts","Access Denied!",JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
else{
JOptionPane.showMessageDialog(null,"Please input correct Account Number/Password","Login Failed!",JOptionPane.ERROR_MESSAGE);
}
}
lblctr.setText("Attempts : "+x);
}});
cancelbtn.setBounds(170,105, 89, 21);
panel.add(cancelbtn);
loginbtn.setBounds(50,105, 89, 21);
panel.add(loginbtn);
JLabel lbluser = new JLabel("Account Number:");
lbluser.setBounds(12, 34, 100, 10);
panel.add(lbluser);
JLabel lblpass = new JLabel("Password:");
lblpass.setBounds(50, 62, 72, 17);
panel.add(lblpass);
}
public static void main (String[]args){
Main2 proj = new Main2();
proj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
proj.setVisible(true);
proj.setSize(320,190);
proj.setLocationRelativeTo(null);
}
}
JPasswordField#getPassword() returns a char array, not a String, and so comparing "password" and inputPass.getPassword() directly is bound to fail. Use the Arrays method to compare char arrays, not the equals(...) method.
Also, user7 is correct, you're trying to use the password variable name as a String which will also fail. Get rid of the quotes.
e.g.,
if (Arrays.equals(password.toCharArray(), inputPass.getPassword()))
Other issues:
Never have this in your code: #SuppressWarnings("deprecation"). The code is deprecated for a very good reason and should not be used. Instead go to the API to see why the code is deprecated and use the alternatives that the API suggests.
You should avoid use of null layout and setBounds(...) as this makes for very inflexible GUI's that while they might look good on one platform look terrible on most other platforms or screen resolutions and that are very difficult to update and maintain. Instead use the layout managers to help you create good looking, functional and easily maintained GUI's.