JButton unresponsive to actionListener - java

I've trouble with actionListener. I created own simple dialog, which has only two JButtons - Yes and No. When I click on button, actionListener doesn't respond.
This is my code:
private void showInfoNewUML() {
Dimension buttonsSize = new Dimension(60, 25);
Dimension programSize = new Dimension(1200, 700);
final JDialog dialogWindow = new JDialog(this, "Erase actual UML diagram"
+ " with his files", true);
JTextArea descDialogWindow = new JTextArea("Do you really erase actual\n"
+ "UML diagram with his files? ");
descDialogWindow.setEditable(false);
descDialogWindow.setBackground(new Color(220, 220, 220));
descDialogWindow.setBorder(null);
dialogWindow.getContentPane().setBackground(new Color(220, 220, 220));
dialogWindow.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
dialogWindow.setModal(true);
dialogWindow.setResizable(false);
dialogWindow.setLayout(new FlowLayout());
dialogWindow.setSize(310, 100);
dialogWindow.setLocation((int) programSize.getWidth() / 2,
(int) programSize.getHeight() / 2);
JButton buttonYes = new JButton("Yes");
JButton buttonNo = new JButton("No");
buttonYes.setPreferredSize(buttonsSize);
buttonNo.setPreferredSize(buttonsSize);
dialogWindow.add(descDialogWindow);
dialogWindow.add(buttonYes);
dialogWindow.add(buttonNo);
dialogWindow.setVisible(true);
buttonYes.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
buttonAnoActionPerformed(e);
}
private void buttonAnoActionPerformed(ActionEvent e) {
dialogWindow.setVisible(false);
}
});
buttonNo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
buttonNeActionPerformed(e);
}
private void buttonNeActionPerformed(ActionEvent e) {
dialogWindow.setVisible(false);
}
});
}
I would like close this dialog after I click on button. When I click to top right button with cross, dialog window closes.
Thank you for help with this trouble.

Try adding the ActionListeners before calling dialogWindow.setVisible(true);.
Your dialog is modal, and so showInfoNewUML will block at dialogWindow.setVisible(true); until after the dialog is closed, which is too late to register any useful listeners.

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);
}
});

How can I connect my JButton to my JTextField to store the int I input into the JTextField?

I have created a simple GUI JFrame that has a textfield and button with their given action listeners. But I am trying to connect the textfield to the button so that whenever I have inputted a series of numbers into the text field and press the button, my code stores the series of numbers to a variable that I will use later on. How do I connect the two to start off with?
I have looked at other stackoverflow posts, but I cannot seem to find a solution.
//textfield
id = new JTextField(7);// accepts up to 7 characters
//buttons
go = new JButton("Go");
go.setBounds(100, 150, 140, 40);
CL = new JButton("Cheap Lock");
CL.setBounds(100,300,140,40);
//JLabel that shows button has stored the input
go1 = new JLabel();
go1.setBounds(10, 160, 200, 100);
//button action listener
go.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
go1.setText("Student ID has been submitted.");
}
});
//textfield actionlistener
id.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
id.getText();
}
});
}
You've got an ActionListener on your button, which is a good start. You should write some logic to grab the text from the JTextField, parse it as you want and store it in a data structure (e.g. an ArrayList).
You don't seem to need the JTextField ActionListener right now - move the id.getText() call into the JButton ActionListener and store it in a variable.
//textfield
id = new JTextField(7);// accepts up to 7 characters
//buttons
go = new JButton("Go");
go.setBounds(100, 150, 140, 40);
CL = new JButton("Cheap Lock");
CL.setBounds(100,300,140,40);
//JLabel that shows button has stored the input
go1 = new JLabel();
go1.setBounds(10, 160, 200, 100);
//button action listener
go.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
go1.setText("Student ID has been submitted.");
String value = id.getText();
// logic here - e.g. Integer.parseInt();
}
});

Getting user input and then printing new text using AWT

I am trying to create a simple program where when I press a button, new text will appear but I have no idea how to do it (I imagine it is very simple).
The code I have right now is:
import java.awt.*;
public class ConsumptionGUI extends Frame
{
public ConsumptionGUI()
{
Frame fr = new Frame();
Button b1 = new Button ("Terminate Program");
Button b2 = new Button ("Start");
b1.setBounds(50,50,50,50);
b2.setBounds(50,50,50,50);
b1.addActionListener(e-> System.exit(0));
Label txt = new Label ("This is my first GUI");
//add to frame (after all buttons and text was added)
fr.add(b2);
fr.add(txt);
fr.add(b1);
fr.setSize(500,300);
fr.setTitle("Vehicles Information System");
fr.setLayout(new FlowLayout());
fr.setVisible(true);
} //end constructor
public static void main(String args[]){
ConsumptionGUI frame1= new ConsumptionGUI();
} //end main
Basically after this point I managed to create a frame with 2 buttons and some text in the middle.
I am really struggling to continue from here.
I need the program to first start by the press of a button then print some new text (something like "please enter your car's speed") and then save this information (to be used in a simple formula).
Afterwards the program needs to display the formula used and print what is the value calculated.
Can anyone please help?
Thanks
To get user input, you can implement a Dialog like in below code. You can use another similar dialog to show the formula and result as well.
import java.awt.*;
import java.awt.event.*;
public class ConsumptionGUI extends Frame
{
public ConsumptionGUI()
{
Frame fr = new Frame();
Button b1 = new Button("Terminate Program");
Button b2 = new Button("Start");
//b1.setBounds(50, 50, 50, 50); // Unnecessary
//b2.setBounds(50, 50, 50, 50); // Unnecessary
b1.addActionListener(e -> System.exit(0));
b2.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
InputDialog dialog = new InputDialog(fr);
dialog.setVisible(true);
System.out.println("User inputted speed = " + dialog.getSpeed());
}
});
Label txt = new Label("This is my first GUI");
//add to frame (after all buttons and text was added)
fr.add(b2);
fr.add(txt);
fr.add(b1);
fr.setSize(500, 300);
fr.setTitle("Vehicles Information System");
fr.setLayout(new FlowLayout());
fr.setVisible(true);
} //end constructor
public static void main(String args[])
{
ConsumptionGUI frame1 = new ConsumptionGUI();
} //end main
}
class InputDialog extends Dialog
{
private int speed;
InputDialog(Frame owner)
{
super(owner, "Input", true);
addWindowListener(new WindowAdapter()
{
#Override
public void windowClosing(WindowEvent e)
{
dispose();
}
});
TextField textField = new TextField(20);
Button okButton = new Button("OK");
okButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
String speedString = textField.getText();
speed = !speedString.isEmpty() ? Integer.parseInt(speedString) : 0;
dispose();
}
});
setLayout(new GridLayout(3, 1));
add(new Label("Please enter your car's speed"));
add(textField);
add(okButton);
pack();
}
int getSpeed()
{
return speed;
}
}

JTabbedPane with button getting the pane

I have a JTappedPane with a button on that I want to make close that tab.
I am doing it like so:
jTabbedPane1.addTab(title, null, panel, null);
JPanel pnl = new JPanel();
JButton close = new JButton();
try {
Image img = ImageIO.read(getClass().getResource("x.png"));
close.setIcon(new ImageIcon(img));
} catch (IOException ex) {
ex.printStackTrace();
}
close.setPreferredSize(new Dimension(10, 10));
close.setBorderPainted(false);
close.addActionListener(new java.awt.event.ActionListener(){
public void actionPerformed(ActionEvent evt) {
//TODO CLOSE THE TAP WHEN BUTTON IS PRESSED
}
}});
JLabel lab = new JLabel(s);
pnl.setOpaque(false);
pnl.add(lab);
pnl.add(close);
jTabbedPane1.setTabComponentAt(jTabbedPane1.getTabCount() - 1, pnl);
I am trying to get the title of the tab on the tab that the button has been pressed on.
I thought i could do something like
close.getContaining() to return the tab it is on but I was wrong.
Any Ideas?
If I understand you correctly, you want to find the index of the tab which has the parent of the button as tabComponent:
public void actionPerformed(ActionEvent evt) {
JComponent source = (JComponent) evt.getSource();
Container tabComponent = source.getParent();
int tabIndex = jTabbedPane1.indexOfTabComponent(tabComponent);
jTabbedPane1.removeTabAt(tabIndex);
}
You could simply write:
jTabbedPane1.removeTabAt(jTabbedPane1.getSelectedIndex());

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.

Categories

Resources