JButton requires two clicks after getting enabled in JAVA - 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);
}
});

Related

Add component every time actionPerformed is called

Hello guys I've been trying to do a small program which is just a window with a JButton that opens a JOptionPane on click and lets me input an entry for a vacation list. I want to add that entry as an JCheckBox to the JLabel every time the action of the JButton is performed. My problem currently is that even though my code seems so work the JCheckBox won't show up after inputting the String into the JOptionPane. It probably has to do something with actionPerformed being a void method? I'd be glad for some help and I'm sorry if that question has already occurred but I didn't find it anywhere.
Thanks in advance!
My Code:
public class Urlaub extends JFrame {
public Urlaub() {
super("Urlaub");
JFrame window = this;
window.setSize(800, 600);
window.setLocationRelativeTo(null);
window.setVisible(true);
JLabel grouped = new JLabel();
window.add(grouped);
grouped.setLayout(new FlowLayout());
JButton addThing = new JButton("Add things");
addThing.setVisible(true);
grouped.add(addThing);
addThing.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String entry = JOptionPane.showInputDialog(this, "Enter item");
JCheckBox checkItem = new JCheckBox(entry);
grouped.add(checkItem); // this is the line which should add the JCheckBox to the JLabel/Window
}
});
}
}
You need to revalidate the container after changing it's children. This forces a repaint.
You're also adding the elements to a JLabel, which is unusual. You're better off with a JPanel:
super("Urlaub");
JFrame window = this;
window.setSize(800, 600);
window.setLocationRelativeTo(null);
window.setVisible(true);
JPanel grouped = new JPanel();
window.getContentPane().add(grouped);
grouped.setLayout(new FlowLayout());
JButton addThing = new JButton("Add things");
grouped.add(addThing);
grouped.add(new JCheckBox("je"));
addThing.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String entry = JOptionPane.showInputDialog(this, "Enter item");
JCheckBox checkItem = new JCheckBox(entry);
grouped.add(checkItem); // this is the line which should add the JCheckBox to the JLabel/Window#
window.getContentPane().revalidate();
}
});

How to make button open the frame in a relevant language?

I have two classes, each one with JFrame.
The first frame contains two buttons, they are supposed to open the next frame in a proper language. My task is: I open the first frame (start program), I want to choose english language, I click on the button with "English" label, it opens the next frame with program. All labels, all buttons are in English.
When I want it to be in e.g. French, I click French button in the first frame, and the second one opens with all labels and button in French
So, my question is this: how to combine action with clicking on the button with opening the frame in a proper language?
Currently all buttons opens the same frame with labels in one language.
Here is a sample of my code of the first frame and "View" is the next JFrame in next class View:
public class StartFrame extends JFrame {
JButton button1 = new JButton(new ImageIcon(((new ImageIcon("flag.png")).getImage()).getScaledInstance(100, 75, java.awt.Image.SCALE_SMOOTH)));
JButton button2 = new JButton(new ImageIcon(((new ImageIcon("flag2.jpg")).getImage()).getScaledInstance(100, 75, java.awt.Image.SCALE_SMOOTH)));
public StartFrame() {
setSize(480,360);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new GridLayout(2,1));
JPanel panel2 = new JPanel();
add(panel2);
panel2.setLayout(null);
panel2.setBackground(Color.white);
panel2.setLayout(new FlowLayout());
button1.setPreferredSize(new Dimension(100, 75));
button2.setPreferredSize(new Dimension(100, 75));
panel2.add(button1);
panel2.add(button2);
panel2.add(button3);
button1.addActionListener (new ActionListener(){
public void actionPerformed(ActionEvent e) {
View f = new View();
f.setVisible(true);
f.setLocationRelativeTo(null);
dispose();
}
});
button2.addActionListener (new ActionListener(){
public void actionPerformed(ActionEvent e) {
View en = new View();
en.setVisible(true);
en.setLocationRelativeTo(null);
dispose();
}
});
}
public static void main(String[] args) {
StartFrame frame = new StartFrame();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
}
You could add a language field to the class View. Then, on your action listener you change the value of that field:
button1.addActionListener (new ActionListener(){
public void actionPerformed(ActionEvent e) {
View f = new View();
f.setLanguage("French");
f.setVisible(true);
f.setLocationRelativeTo(null);
dispose();
}
});
button2.addActionListener (new ActionListener(){
public void actionPerformed(ActionEvent e) {
View en = new View();
en.setLanguage("English");
en.setVisible(true);
en.setLocationRelativeTo(null);
dispose();
}
});

Button in java not doing action

I'm working on a Java assignment. I have many classes linked together and one of the constructors is the following:
public class RemovePatientForm extends JFrame implements ActionListener {
JPanel northPanel = new JPanel();
JPanel southPanel = new JPanel();
JPanel midPanel = new JPanel();
JLabel removeLabel = new JLabel("Please type in the ID of the patient to be removed");
JLabel idLabel= new JLabel("ID");
JTextField idText=new JTextField();
JButton submit = new JButton("Submit");
JButton reset = new JButton("Clear");
boolean externalForm = false;
public RemovePatientForm(){
setTitle("Removing a patient");
setLayout(new BorderLayout());
setSize(400,200);
setLocationRelativeTo(null);
setVisible(true);
setResizable(false);
add("North", northPanel);
add("South", southPanel);
northPanel.add(removeLabel);
southPanel.add(submit);
southPanel.add(reset);
add(idLabel);
add(idText);
submit.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent arg0) {
if(arg0.getSource()==submit){
if(!(idText.getText().equals(""))){
int selectedvalue = JOptionPane.showConfirmDialog(null, "Do you want to proceed with the deletion?", "do you want to proceed with the deletion?", JOptionPane.YES_NO_OPTION);
if(selectedvalue==JOptionPane.YES_OPTION){
int id=Integer.parseInt(idText.getText());
if(searchForId(id)){
removeToDatabase();
dispose();
}
else{
JOptionPane.showMessageDialog(null,"This ID is not available!","Warning",JOptionPane.ERROR_MESSAGE);
}
}
else{
JOptionPane.showMessageDialog(null, "Nothing is affected!");
}
}
else{
JOptionPane.showMessageDialog(null,"You have to fill the ID number!","Warning",JOptionPane.ERROR_MESSAGE);
}
}
if(arg0.getSource()==reset && externalForm==false){
idText.setText("");
}
}
The problem in here is that when I press the submit button, everything is okay and working as written within the code.
But, if I press the reset button, nothing is happening.
What do you think the solution is? is this code enough to determine the problem?
You didn't add an action listener for the reset button.. i think you forgot it. Try to add it and it should work.
Add this code within your constructor:
reset.addActionListener(this);

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