Can't get text from a JTextField via Anonymous class - java

Basically, this is what needs to happen:
Submit button is clicked, the actionlistener picks it up and prints what is in the textfield at the time of submission.
For some reason, it isn't picking up the text inside the textbox?
The "Submit Button Pressed" is getting printed by the way!
This is a silly problem but I am not used to anonymous classes. I believe the problem is the variable modifier. Here is my code simplified:
public class MainWindw extends JFrame {
public static JTextField txt1;
final JButton submit;
public MainWindw()
{
//add panel...add textfield etc..
txt1 = new JTextField();
submit = new JButton("Submit");
submit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println("Submit button pressed" + txt1.getText());}
}
});
}
}

I have tried this solution, and it works. i honestrly don't see any problem in your code except some Compilation Error but i think is cause you have simplified the code
public static JTextField txt1;
final JButton submit;
public MainWindw()
{
JFrame panel = new JFrame();
txt1 = new JTextField();
submit = new JButton("Submit");
panel.setLayout(new FlowLayout());
panel.add(txt1);
panel.add(submit);
submit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("Submit button pressed" + txt1.getText());
}
});
panel.setSize(300, 300);
panel.setVisible(true);
}

Related

JButton requires two clicks after getting enabled in JAVA

I am trying to build a JFrame with four manual input JTextFields: description, hours, minutes, ID
and two JButtons: Submit and Reset
I need to disable the "Submit" button until all text fields have some data. To achieve this, I have used the DocumentListener and that is working fine, that is, initially the "Submit" button is disabled and gets enabled only when all text fields have some input.
PROBLEM: After "Submit" button is enabled, I need to hit the submit button twice to get the actual action trigger (probably first time is to restore focus after getting enabled, second time to do actual work). This issue does not happen with the "Reset" button.
TRIED AND DIDN'T WORK: I tried restoring focus using submit.requestFocusInWindow() and it brought focus to the "Submit" button but the last modified text field lost focus and I had to click it again to restore focus on that field.
Please assist. I am quite new to StackOverflow, so kindly don't close the thread.
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
JPanel titlePanel = new JPanel();
JPanel descPanel = new JPanel();
JPanel timeWorkedPanel = new JPanel();
JPanel iDPanel = new JPanel();
titlePanel.add(title);
mainPanel.add(titlePanel);
descPanel.add(desc);
mainPanel.add(descPanel);
timeWorkedPanel.add(hour);
timeWorkedPanel.add(minute);
mainPanel.add(timeWorkedPanel);
iDPanel.add(iD);
mainPanel.add(iDPanel);
JTextArea reqList = new JTextArea();
reqList.setLineWrap(false);
reqList.setEditable(false);
JScrollPane reqListScroll = new JScrollPane (reqList);
reqListScroll.setPreferredSize(new Dimension(400,400));
reqListScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
reqListScroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
reqListScroll.setColumnHeaderView(new JLabel(" REQUEST CREATED TIME WORKED"));
mainPanel.add(reqListScroll);
List<JTextField> textFieldList = new ArrayList<>();
textFieldList.add(desc);
textFieldList.add(hour);
textFieldList.add(minute);
textFieldList.add(csiID);
JButton submit = new JButton("SUBMIT");
JButton reset = new JButton("RESET");
buttonPanel.add(submit);
buttonPanel.add(reset);
mainPanel.add(buttonPanel);
mainPanel.add(Box.createVerticalStrut(20)); // a spacer
JFrame mainFrame = new JFrame("Test Frame");
mainFrame.getContentPane().add(mainPanel);
mainFrame.setSize(new Dimension(500,600));
mainFrame.setLocationRelativeTo(null);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setVisible(true);
submit.setEnabled(false);
DocumentListener docListener = new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent e) {
changedUpdate(e);
}
#Override
public void removeUpdate(DocumentEvent e) {
changedUpdate(e);
}
#Override
public void changedUpdate(DocumentEvent e) {
boolean isEnabled = true;
for(JTextField tf : textFieldList) {
if(tf.getText().isEmpty())
isEnabled = false;
}
submit.setEnabled(isEnabled);
}
};
for(JTextField tf : textFieldList) {
tf.getDocument().addDocumentListener(docListener);
}
final WebDriver newDriver = driver;
final ChromeOptions newOptions = options;
//Click on "SUBMIT" button
submit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
System.out.println("submitting");
mainFrame.setVisible(false);
createTicket(newDriver, newOptions, subportfolio, title, desc , hour, minute, csiID);
mainFrame.setVisible(true);
} catch (InterruptedException e1) {
}
}
});
//Click on "RESET" button
reset.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
desc.setText(null);
hour.setText(null);
minute.setText(null);
csiID.setText(null);
}
});

Change component of JPanel that has been changed by an ActionListener from another ActionListener

I have some buttons in my JPlane and when I click them, I want each one of them to change the components of the JPanel without interference, as in, when I click one button, two JTextFields are added to the JPlane; however, when I press the other button, I want the previous JTextFields to get removed and instead add one new JTextField. My code looks something like this:
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JLabel name = new JLabel("Name");
JTextField name1 = new JTextField();
JLabel salary = new JLabel("Salary");
JTextField salary1 = new JTextField();
low.add(name);
low.add(name1);
low.add(salary);
low.add(salary1);
}
});
button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JLabel name = new JLabel("Name");
JTextField name1 = new JTextField();
low.add(name);
low.add(name1);
}
});

how do get the account id when clicking submit button then display the client details on the label?

// submit button
JButton btnSubmit = new JButton("Submit");
btnSubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JButton btnSubmit = new JButton("Submit");
//label that used to display the name, house number, postcode
JLabel lblNameDisplay = new JLabel("-");
JLabel lblHouseNoDisplay = new JLabel("-");
JLabel lblPostCodeDisplay = new JLabel("-");
Object accID = e.getSource();
//when clicking the submit, should get account id and display the client details on the label
if(accID==btnSubmit){
}
}
Any code within
public void actionPerformed(ActionEvent e) { ... }
will be executed when clicking the "Submit" button because you created an anonymous action listener specifically for use with the button (hence use of anonymous inner class).
Therefore, all you really need to put in the actionPerformed(...) method would be the assignment of the new labels (assuming that they already exist or you got them somewhere).
e.g.
btnSubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
lblExampleLabel.setText("This is what the label will become after clicking the button");
}
});
In your code you have two btnSubmit variables
JButton btnSubmit = new JButton("Submit"); <-----
btnSubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JButton btnSubmit = new JButton("Submit"); <-----
If you do if(accID==btnSubmit) - Which one are you using?
But anyway,
The actionListener is bound to your btnSubmit button so getSource() is going to return the btnSubmit object.

Java Gui return item

I am wanting to get a return from a gui instance
The code i run to create the GUI:
JFrame frame = new JFrame();
frame.getContentPane().add(new ChatPopup());
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
My GUI (ChatPopUp code is as follows:
public class ChatPopup extends javax.swing.JPanel {
private JButton cancelButton;
private JTextField textFieldchatRoomName;
private JLabel jLabel1;
private JButton okButton;
public ChatPopup() {
super();
initGUI();
}
private void initGUI() {
try {
this.setPreferredSize(new java.awt.Dimension(294, 85));
{
jLabel1 = new JLabel();
this.add(jLabel1);
jLabel1.setText("Please enter the new chat room name:");
}
{
textFieldchatRoomName = new JTextField();
this.add(textFieldchatRoomName);
textFieldchatRoomName.setPreferredSize(new java.awt.Dimension(263, 22));
}
{
cancelButton = new JButton();
this.add(cancelButton);
cancelButton.setText("Cancel");
cancelButton.setPreferredSize(new java.awt.Dimension(84, 22));
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.out.println("Cancel PRESSED");
}
});
}
{
okButton = new JButton();
this.add(okButton);
okButton.setText("Ok");
okButton.setPreferredSize(new java.awt.Dimension(60, 22));
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.out.println("OK PRESSED");
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is a pretty simple GUI which has a text field and 2 buttons one "Ok" one "Chancel".
When i click "Ok" i want the textField value to be sent to the class where the GUI instance is originally run.
Any ideas how to do this??
The JPanel you posted should be added to a modal JDialog content pane. In the same class, you can provide some methods to return the values the user entered into the text fields.
In the original window, you open the dialog.
SomeDialog dialog = new SomeDialog(parent);
dialog.setVisible(true);
The code after setVisible() will only be executed after the modal dialog is closed. At this point you can call the methods I mentioned above for getting the text field values.

Action Listener on a radio button

I would like to set editable option of a text box based on the selection of a radio button? How to code the action listener on the radio button?
This is the solution that I would use in this case.
//The text field
JTextField textField = new JTextField();
//The buttons
JRadioButton rdbtnAllowEdit = new JRadioButton();
JRadioButton rdbtnDisallowEdit = new JRadioButton();
//The Group, make sure only one button is selected at a time in the group
ButtonGroup editableGroup = new ButtonGroup();
editableGroup.add(rdbtnAllowEdit);
editableGroup.add(rdbtnDisallowEdit);
//add allow listener
rdbtnAllowEdit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
textField.setEditable(true);
}
});
//add disallow listener
rdbtnDisallowEdit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
textField.setEditable(false);
}
});
My Java is a little rusty, but this should be what you're looking for.
Here is your listener:
private RadioListener implements ActionListener{
private JTextField textField;
public RadioListener(JTextField textField){
this.textField = textField;
}
public void actionPerformed(ActionEvent e){
JRadioButton button = (JRadioButton) e.getSource();
// Set enabled based on button text (you can use whatever text you prefer)
if (button.getText().equals("Enable")){
textField.setEditable(true);
}else{
textField.setEditable(false);
}
}
}
And here is the code that sets it up.
JRadioButton enableButton = new JRadioButton("Enable");
JRadioButton disableButton = new JRadioButton("Disable");
JTextField field = new JTextField();
RadioListener listener = new RadioListener(field);
enableButton.addActionListener(listener);
disableButton.addActionListener(listener);
Another answer for this question. Modify a little code from zalpha314 's answer.
You could know which radio button is selected by the text of this button, and you could also know it by Action Command. In the oracle's radio button demo code http://docs.oracle.com/javase/tutorial/uiswing/examples/components/RadioButtonDemoProject/src/components/RadioButtonDemo.java , I learnt how to use action command.
First, define two action command
final static String ON = "on"
final static String OFF = "off"
Then add action command to buttons
JRadioButton enableButton = new JRadioButton("Enable");
enableButton.setActionCommand(ON);
JRadioButton disableButton = new JRadioButton("Disable");
disableButton.setActionCommand(OFF);
So in actionPerformed, you could get the action command.
public void actionPerformed(ActionEvent e){
String ac = e.getActionCommand();
if (ac.equals(ON)){
textField.setEditable(true);
}else{
textField.setEditable(false);
}
}
Action command maybe better when the button.getText() is a very long string.
Try this:
JRadioButton myRadioButton = new JRadioButton("");
myRadioButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// Do something here...
}
});
Try this:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class NewStudent {
public static void main(String[] args){
NewStudent st=new NewStudent();
}
public NewStudent(){
JFrame frame=new JFrame("STUDENT REGISTRATION FORM");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800,600);
frame.setVisible(true);
JPanel p1=new JPanel();
p1.setLayout(null);
p1.setBackground(Color.CYAN);
frame.add(p1);
ButtonGroup buttonGroup=new ButtonGroup();
JRadioButton male=new JRadioButton("MALE");
male.setBounds(100,170,100,20);
buttonGroup.add(male);
p1.add(male);
JRadioButton female=new JRadioButton("FEMALE");
female.setBounds(250,170,100,20);
buttonGroup.add(female);
p1.add(female);
JLabel sex =new JLabel("SEX:");
sex.setBounds(10,200,100,20);
p1.add(sex);
final JTextField gender= new JTextField();
gender.setBounds(100,200,300,20);
p1.add(gender);
male.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ie){
gender.setText("MALE");
}
});
female.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ie){
gender.setText("FEMALE");
}
});
}

Categories

Resources