Button in java not doing action - java

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

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

Java Button disappears after clicking

I'm trying to add a button using an JOptionPane in another button, but after I clicked the original button just keeps disappearing.
I've tried adding the JPanel manually instead of using 'handPanelNPC.getHandPanel()' by iterating through the handPanel.buttons but it stil wont work. I've checked the ArrayList size and it is already inserted properly.
LayoutTesting.java
public class LayoutTesting extends JFrame{
HandPanel handPanelNPC = new HandPanel();
public LayoutTesting(HandPanel handPanel, int type){
Container pane = getContentPane();
if (type==1){
handPanelNPC = handPanel;
}
pane.setLayout(new BorderLayout());
pane.add(handPanelNPC.getHandPanel(), BorderLayout.NORTH);
validate();
repaint();
}
public LayoutTesting(){
Container pane = getContentPane();
pane.setLayout(new BorderLayout());
pane.add(handPanelNPC.getHandPanel(), BorderLayout.NORTH);
}
}
HandPanel.java
public class HandPanel implements ActionListener{
JFrame frame = null;
JPanel panel = new JPanel();
ArrayList<JButton> buttons = new ArrayList<JButton>();
public HandPanel(){
addNewButton();
panel.setLayout(new FlowLayout());
panel.add(buttons.get(0));
}
public JComponent getHandPanel(){
panel = new JPanel();
for(int i=0; i<buttons.size(); i++){
JButton button = buttons.get(i);
panel.add(button);
}
return panel;
}
public void addNewButton(){
JButton button = new JButton();
button.setPreferredSize(new Dimension(40,58));
button.addActionListener(this);
buttons.add(button);
}
public void actionPerformed(ActionEvent e) {
String[] options = {"Summon", "Set", "Add Card"};
int messageType = JOptionPane.QUESTION_MESSAGE;
int code = JOptionPane.showOptionDialog(
frame,
"What would you like to do?",
"Card Name",
0, messageType, null,
options, options[1]);
if (code==2){
addNewButton();
LayoutTesting frame = new LayoutTesting(this, 1);
}
}
}
Main.java
public class Main extends JFrame{
public static void main(String[] args){
LayoutTesting frame = new LayoutTesting();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setVisible(true);
}
}
You have too many odd things happening in your code to give a simple answer.
Try debugging your own code by looking at this line in HandPanel.java:
LayoutTesting frame = new LayoutTesting(this, 1);
What does it really do? Now remove that line and the button will not disappear. Now try and work out what that line was doing, and why the button disappeared.
Also 'panel.add(buttons.get(0));' does nothing because there is never a button in the array when you make that call (You add the button afterwards in another method).
Here is a rough working demo that lets you add as many new cards as you want to the first frame, and each card has a button that will let you summon a new card.
public class LayoutTesting extends JFrame{
Container pane;
//Add card when button is pressed:
public void addCard(){
Container card = new JPanel();
card.setBackground(Color.red);
JButton newButton = addNewButton();
newButton.setBackground(Color.red);
card.add(newButton);
pane.add(card);
revalidate();
repaint();
}
//Setup window and add button:
public LayoutTesting(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
setVisible(true);
setLayout(new FlowLayout());
pane = new JPanel();
pane.setLayout(new GridBagLayout());
JButton firstButton = addNewButton();
firstButton.setBackground(Color.green);
add(pane);
add(firstButton);
}
//Create button and action listener:
public JButton addNewButton(){
JButton button = new JButton();
button.setPreferredSize(new Dimension(40, 58));
button.addActionListener(new java.awt.event.ActionListener(){
#Override
public void actionPerformed(java.awt.event.ActionEvent evt){
buttonAction(evt);
}
});
return button;
}
//Action fer each button:
public void buttonAction(ActionEvent e) {
String[] options = {"Summon", "Set", "Add Card"};
int messageType = JOptionPane.QUESTION_MESSAGE;
int code = JOptionPane.showOptionDialog(
this,
"What would you like to do?",
"Card Name",
0, messageType, null,
options, options[1]);
if (code==2){
addCard();
}
}
}

JButton not displaying

Hi does anyone know why my "button1" is not displaying? I can not seem to figure it out when I execute the program it all works and runs successfully but it does not display this button. Any help would be appreciated thanks.
private Container c;
private JPanel gridPanel;
private JComboBox combo;
final JLabel label = new JLabel();
private JButton button1 = new JButton("Clear");
private JButton button2 = new JButton("Exit");
/**
* Christopher Haddad - 559815X
*/
public Planets() {
c = getContentPane();
gridPanel = new JPanel();
gridPanel.setLayout(new GridLayout(5, 0, 0, 0));
label.setVisible(true);
combo = new JComboBox();
combo.setEditable(false);
combo.addItem("No Planet Selected");
combo.addItem("Mercury");
combo.addItem("Venus");
combo.addItem("Earth");
gridPanel.add(combo);
add(button1);
add(button2);
button1.addActionListener(this);
button2.addActionListener(this);
c.add(gridPanel, BorderLayout.NORTH);
setTitle("Planet Diameter");
setSize(700, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
combo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
JComboBox comboBox = (JComboBox) event.getSource();
Object select = comboBox.getSelectedItem();
if(select.toString().equals("No Planet Selected"))
label.setText("");
else if(select.toString().equals("Mercury"))
label.setText("The planet Mercury is 3100kms in diameter");
else if(select.toString().equals("Venus"))
label.setText("The planet Venus is 7500kms in diameter");
else if (select.toString().equals("Earth"))
label.setText("The planet Earth is 8000kms in diameter");
}
});
getContentPane().add(combo);
getContentPane().add(label);
}
// event handling method, implementing the actionPerformed method of ActionListener
public void actionPerformed(ActionEvent e)
{
// set the button label to number of times it has been clicked
if(e.getSource() == button1) {
label.setText(" ");
}
else if(e.getSource() == button2) {
System.exit(0);
}
}
It is difficult to be sure, but I assume you are adding content directly to a top level container, like a JFrame
JFrame uses a BorderLayout as it's default layout manager, so using
add(button1);
add(button2);
Basially says, add button1 to the CENTER position then add button2 to the CENTER position. BorderLayout will only allow a single component to exist at a specific location.
Try adding the buttons to another panel first...

How to Validate a textfield in java

Hello I need some help validing textfield in my gui. My professor gave me a hint on how to do but it freezes up my program. I've tried other methods but if If I enter text the text field the next window doesn't show.
import javax.swing.*;
import java.awt.GridLayout;
import java.awt.HeadlessException;
import java.awt.event.*;
//import statements here
public class UserWindow extends JFrame
{
private JTextField nameField, ageField, creditCardField;
private JButton backButton, nextButton;
public UserWindow()
{
super("Please enter your information");
setSize(700,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(new GridLayout(4,2));
buildPanel();
setVisible(true);
}
private void buildPanel(){
nameField = new JTextField(10);
ageField = new JTextField(2);
creditCardField = new JTextField(10);
backButton = new JButton("Back");
nextButton = new JButton("Next");
nextButton.addActionListener(new NextButton());
backButton.addActionListener(new BackButton());
JLabel NameLabel = new JLabel("Please enter your name");
JLabel ageLabel = new JLabel("Enter your age");
JLabel creditCardLabel = new JLabel("Enter your credit card number");
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
JPanel panel5 = new JPanel();
JPanel panel6 = new JPanel();
JPanel panel7 = new JPanel();
JPanel panel8 = new JPanel();
add(panel1);
add(panel2);
add(panel3);
add(panel4);
add(panel5);
add(panel6);
add(panel7);
add(panel8);
panel1.add(NameLabel);
panel2.add(nameField);
panel4.add(ageField);
panel6.add(creditCardField);
panel3.add(ageLabel);
panel5.add(creditCardLabel);
panel7.add(backButton);
panel8.add(nextButton);
}//end of panel building
//action listeners for fields/buttons
private class NextButton implements ActionListener{
public void actionPerformed(ActionEvent e){
String str;
int age;
str = nameField.getText();
if (str.equals("")){
JOptionPane.showMessageDialog(null,"Please enter your name.");
while(true){
nameField.requestFocusInWindow();
if(!str.equals(""))
break;
}
}
if(e.getSource() == nextButton)
new MovieSelection();
setVisible(false);
}
}
private class BackButton implements ActionListener{
public void actionPerformed(ActionEvent e){
if (e.getSource() == backButton)
setVisible(false);
new SelectUserWindow();
}
}
}
You never assign a new value to str if it is initially the empty string.
I think you need something like
str = nameField.getText();
inside your while(true) loop.
It is freezing because you have a this:
if (str.equals("")){
JOptionPane.showMessageDialog(null,"Please enter your name.");
while(true){ //<- Runs forever
nameField.requestFocusInWindow();
if(!str.equals(""))
break;
}
}
AcId is correct when he say you never assign any value to str after you enter the loop (or the if). This means you never change the value of str and it will never not be equal to "" and it will run in the loop forever. The loop runs in the same thread as the user interface, so the user interface will not have time to do anything else (hence it is freezing).
It doesn't make sense to have a loop that runs forever in this situation. It seems you are trying to make the GUI busy wait until the user has entered a name. Don't do that. Instead check if the user have entered something, if not, alert the user and wait for the user to click the button again.
So remove the loop and use a simple if-else statement.
if (str.equals("")){ //User have not entered anything.
JOptionPane.showMessageDialog(null,"Please enter your name.");
nameField.requestFocusInWindow();
//Do NOT loop here.
}
else {
//Do everything you need to do when the user have entered something
}

JOptionPane call stacks

I got a little problem with a JOptionPane which I use to warn user if wrong input is found. It works correct first time. But when I close down the JFrame which calls for that JOptionPane, and open it again it will this time call for it twice. And it will stack for every close down I do.
I have tried to look for the problem without any luck. I can provide the code, but it is quite large though.
Third EDIT: I have found and solved the problem now.
Ok, I provided the code I use. I have cut it down so it only show the necessary one. I dont think it will compile, but this is how I use the addActionListener();
public class BorderLayoutDemo extends JFrame implements ActionListener {
private JButton button1 = new JButton("L?gg till kund");
private JButton button2 = new JButton("Ta bort kund");
private JButton button3 = new JButton("Visa kund");
private JButton button4 = new JButton("Lista alla kunder");
private JButton button5 = new JButton("Avsluta");
private JButton button6 = new JButton("Change");
private JTextArea TextWindow = new JTextArea("Hej\nHej\nHej\nHej\nHej\nHej\nHej\nHej\nHej\nHej\nHej\nHej\nHej\n");
private JScrollPane scrollPane = new JScrollPane(TextWindow); //l?gger in TextWindow s? att det f?r en scroll-bar
private JPanel aPanel = new JPanel();
private JFrame aFrame = new JFrame();
private JTextField aTextfield1 = new JTextField();
private JTextField aTextfield2 = new JTextField();
private JButton aButton1 = new JButton("L?gg till kund");
private JButton aButton2 = new JButton("St?ng");
public BorderLayoutDemo() {
setTitle("Bankregister");
setLayout(new BorderLayout());
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 10));
panel.setLayout(new GridLayout(6,1,55,5)); //row, cols, hgap, vgap
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
button4.addActionListener(this);
button5.addActionListener(this);
button6.addActionListener(this);
panel.add(button1);
panel.add(button2);
panel.add(button3);
panel.add(button4);
panel.add(button5);
panel.add(button6);
JPanel panel2 = new JPanel();
panel2.add(panel);
add(panel2,BorderLayout.WEST);
add(scrollPane,BorderLayout.CENTER);
setJMenuBar(menu());
setSize(600,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public void addCustomer(boolean status) {
if(status) {
aFrame.setTitle("L?gg till kund");
aFrame.setSize(200,300);
aFrame.setLayout(new GridLayout(3,1));
aPanel.setLayout(new GridLayout(2,1)); //rad, kolumn
aPanel.add(aTextfield1);
aPanel.add(aTextfield2);
aButton1.addActionListener(this);
aButton2.addActionListener(this);
System.out.println("Foo!!!!!!!!!!!!!");
aFrame.add(aPanel);
aFrame.add(aButton1);
aFrame.add(aButton2);
aFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
aFrame.setLocationRelativeTo(null);
aFrame.setVisible(true);
}
else {
aFrame.setVisible(false);
}
}
public static void main(String[] args) {
new BorderLayoutDemo();
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button1) {
setEnabled(false);
addCustomer(true);
}
//IFs f?r addCustomer();
else if(e.getSource() == aButton1) {
if((aTextfield1.getText().isEmpty() || aTextfield2.getText().isEmpty())) {
JOptionPane.showMessageDialog(null, "You miss to fill out the fields");
}
else {
JOptionPane.showMessageDialog(null, "Added");
Kund kund = new Kund(aTextfield1.getText(),aTextfield2.getText());
setEnabled(true);
register.add(kund);
}
}
else if(e.getSource() == aButton2) {
setEnabled(true);
addCustomer(false);
}
Sounds like you are adding the "validation listener" every time you open the JFrame. So check your "addListenerXXX" code to make sure it is only added/created once.
Which also leads to the question why are you using a JFrame for this? Typically an application has a single JFrame. Then, if you need a window to enter data you create a JDialog.
By passing null as the first parameter of that method you are creating a default JFrame that the JOptionPane uses as its parent component and not the JFrame you have created in your code. If you provide more detail in your question I'm sure someone here will provide you with a much more detailed answer.

Categories

Resources