I created a shop cart login JFrame and I added a "shopkeeperToggle" so that when it's pressed the user logs in to the shopkeeper's JFrame and otherwise to a shopper's jframe. the problem is I don't know how to implement it, I tried to set a boolean "pressed" to false whenever the key is released in the "shopkeeperToggle" key listener, and apparently I'm unable to use the value of pressed inside the sign-in button.
Here's the code for the toggle:
shopkeeperToggle = new JToggleButton("Shopkeeper");
shopkeeperToggle.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
pressed = false;
}
});
and this is what I'm trying to do in the sign in button:
signinButton = new JButton("Sign in ");
signinButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3308/shoppingCart","root","");
// select the users that have the inputted credentials from the database
String sql = "SELECT * FROM users WHERE userUsername = ? AND userEmail =?AND userPassword = ? ";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1,usernamelogin.getText());
ps.setString(2, emaillogin.getText());
ps.setString(3,passwordlogin.getText());
ResultSet rs = ps.executeQuery();
// if query executed and
if (rs.next()) {
// if login succ show window log succ, and go to home shopping page
JOptionPane.showMessageDialog(null,"Login successful! :)");
/////////////////this is where I fail////////////////////
if (pressed) {
OwnerHomePage ownerhome = new OwnerHomePage();
ownerhome.setVisible(true);
setVisible(false);
} else {
UserHomePage home = new UserHomePage();
home.setVisible(true);
setVisible(false);
}
} else {
JOptionPane.showMessageDialog(null,"Wrong Username or Email or Password :(");
}
} catch (Exception e1) {
JOptionPane.showMessageDialog(null,e1);
}
}
}
This may offer some help in fixing your issue. It is a fully compilable demo. The following changes were made.
Used Actions in lieu of KeyListener. A little more involved to setup but they can be configured to monitor only certain keys.
Used a JButton in lieu of a JToggleButton. No specific reason and can be changed.
Created separate inner classes for the listeners. Tends to reduce clutter and is usually more readable.
Changed the name of the button depending on the mode.
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractAction;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
public class ActionMapAndButtons {
JFrame frame = new JFrame("Demo");
public static void main(String[] args) {
SwingUtilities
.invokeLater(() -> new ActionMapAndButtons().start());
}
public void start() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyClass cls = new MyClass();
frame.add(cls);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class MyClass extends JPanel {
JButton button = new JButton("Shopper Sign in");
boolean pause = false;
public MyClass() {
setPreferredSize(new Dimension(300, 300));
button.addActionListener(new ButtonListener());
add(button);
InputMap map = getInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
for (int i = 0; i < 256; i++) {
map.put(KeyStroke.getKeyStroke((char)i), "anyKey");
}
getActionMap().put("anyKey", new MyAction());
setFocusable(true);
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent ae) {
Object obj = ae.getSource();
if (obj instanceof JButton) {
JButton b = (JButton) obj;
pause = !pause;
if (pause) {
b.setText("Shopkeeper Sign in");
} else {
b.setText("Shopper Sign in");
}
}
}
}
private class MyAction extends AbstractAction {
public void actionPerformed(ActionEvent ae) {
String cmd = ae.getActionCommand();
if (pause) {
System.out.println("Shopkeeper - " + cmd);
} else {
System.out.println("Shopper - " + cmd);
}
}
}
}
Inner (or nested) classes and action maps are covered in The Java Tutorials
You can define pressed as a static value;
class c {
static boolean pressed = true;
...
}
and you can access anywhere;
c.pressed; //will return true if you don't change
here's a quick explanation, I make my TextField into false condition inside of .setEnabled area. So basically after the user press check on Cake's check-box, he need to choose either one of the sub-item menu, after he do that, he needs to enter the quantity of the cake. But, after choosing the sub-item menu, the TextField condition should be true(means it should be editable), but it doesn't go as were told. Thank you.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JRadioButton;
import javax.swing.ButtonGroup;
class testingcheckbox
{
public static void main(String[] args)
{
Frame qB = new Frame("Queen Bakery");
JCheckBox cake;
cake = new JCheckBox("Cake");
JCheckBox cakeOpt1 = new JCheckBox("Butter Cake");
JCheckBox cakeOpt2 = new JCheckBox("Cheese Cake");
TextField tfCake = new TextField();
tfCake.setPreferredSize(new Dimension(50,24));
tfCake.setEnabled(false);
ActionListener cakeListener = new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
if(cake.isSelected())
{
cakeOpt1.setEnabled(true);
cakeOpt2.setEnabled(true);
if(cakeOpt1.isSelected())
{
tfCake.setEnabled(true);
}
else
{
tfCake.setEnabled(false);
}
}
else
{
cakeOpt1.setEnabled(false);
cakeOpt2.setEnabled(false);
}
}
};
cake.addActionListener(cakeListener);
qB.add(cake);
cakeOpt1.setEnabled(false);
cakeOpt2.setEnabled(false);
qB.add(cakeOpt1);
qB.add(cakeOpt2);
qB.add(tfCake);
qB.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent windowEvent)
{
System.exit(0);
}
});
qB.setSize(780,470);
qB.setLayout(new FlowLayout(FlowLayout.LEFT));
qB.setVisible(true);
qB.setLocationRelativeTo(null);
qB.setResizable(false);
}
}
cake.addActionListener(cakeListener);
You only add the ActionListener to one check box so no code is execute when you click on the "optonal" check boxes.
You also need to add your ActionListener to your other check boxes:
cakeOpt1.addActionListener(cakeListener);
cakeOpt2.addActionListener(cakeListener);
I have 4 jTextFields that I save the input to a file once a submit button is pressed. I want to be able to keep the submit button disabled until each field is at least not null. Where can i put something like this
if(jTextField1 == null || jTextField2 == null || jTextField3 == null || jTextField4 == null){
jButton2.setEnabled(false);
}
so that the program will enable/disable the button live. Like once the last field even has 1 character in it I want it to be enabled?
You need to add listeners to detect when the user enters text. In order to have it register any change (and not just when the user hits Enter) you should attach a DocumentListener to the underlying document of each JTextField.
Then, have each listener call a function to do your check and update the JButton's enabled status accordingly.
Related
A simple runnable demo:
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.util.List;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class ButtonDemo extends JFrame implements DocumentListener {
/**
*
*/
private static final long serialVersionUID = -68704905659973315L;
private JPanel panel = null;
private JTextField field1 = null;
private JTextField field2 = null;
private JButton btn = null;
private List<JTextField> textFields = null;
public static void main(String[] args) {
new ButtonDemo();
}
private ButtonDemo() {
this.panel = new JPanel();
this.field1 = new JTextField("JTextField_1");
this.field2 = new JTextField("JTextField_2");
this.field1.getDocument().addDocumentListener(this);
this.field2.getDocument().addDocumentListener(this);
this.textFields = new Vector<>();
this.textFields.add(field1);
this.textFields.add(field2);
this.btn = new JButton("Tests-Button");
this.panel.setLayout(new FlowLayout());
this.panel.add(field1);
this.panel.add(field2);
this.panel.add(btn);
this.add(panel);
this.setPreferredSize(new Dimension(200, 200));
this.pack();
this.setVisible(true);
}
#Override
public void insertUpdate(DocumentEvent e) {
updateButtonEnabledStatus(btn, textFields);
}
#Override
public void removeUpdate(DocumentEvent e) {
updateButtonEnabledStatus(btn, textFields);
}
#Override
public void changedUpdate(DocumentEvent e) {
updateButtonEnabledStatus(btn, textFields);
}
private void updateButtonEnabledStatus(JButton btn, List<JTextField> fields) {
boolean enabled = true;
for (JTextField field : fields) {
if (field.getText().length() == 0) {
enabled = false;
break;
}
}
btn.setEnabled(enabled);
}
}
The jTextField may be empty but it wont necessarily be null. You want to test the contents of it.
if(jTextField1.getText() == null || jTextField2.getText() == null || jTextField3.getText() == null || jTextField4.getText() == null){
jButton2.setEnabled(false);
}
If you want to update the button you need to check the contents on edit. You can do that by implementing an action listener to watch the contents of the text fields. You can do that with a DocumentListener (http://docs.oracle.com/javase/tutorial/uiswing/events/documentlistener.html).
use the keyPressed listener for each textfield to run your check wherever the text of a textfield is changed.
the method to disable the buttons is setEnabled(false);
Note that you will have to make the buttons dissabled when the program starts if your textfiends are empty at that time (listeners won't run)
Disable the button while initializing the components
eg:
public Home() {
initComponents();
button.setEnabled(false);
}
2)Enable it by calling the event 'KeyReleased' in the last jTextField.
eg:
private void jTextFieldKeyReleased(java.awt.event.KeyEvent evt) {
button.setEnabled(true);
}
If you do so, the button will automatically enable when any character enter into the last text feild.
Thank You :)
I need to create an application where I need to get a user input from a radio button and then use the selected filename in a different class.I'm not sure how to implement this, beacuse everytime I try to place a getString() method in the MyAction class it gives me a null value. thanks!!
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
public class SelectRadioButton{
public SelectRadioButton(){
// Directory path here
String path = "W:\\materials";
JFrame frame = new JFrame("Material Selection");
JPanel panel = new JPanel(new GridLayout(0, 4));
ButtonGroup bg = new ButtonGroup();
String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
JRadioButton first;
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
files = listOfFiles[i].getName();
if (files.endsWith(".mtl") || files.endsWith(".MTL"))
{
first = new JRadioButton(files);
panel.add(first,BorderLayout.CENTER);
panel.revalidate();
bg.add(first);
first.addActionListener(new MyAction);
}
}
}
frame.add(panel, BorderLayout.NORTH);
frame.getContentPane().add(new JScrollPane(panel), BorderLayout.CENTER);
frame.setSize(1000, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public class MyAction implements ActionListener{
//String m;
public void actionPerformed(ActionEvent e){
String m =e.getActionCommand();
String[] split = m.split("\\.");
m=split[0];
JOptionPane.showMessageDialog(null,"Your Selection is"+m+" radio button.");
}
/*
public String getString(){
return m;
}
*/
}
}
Obviously, the m variable only will be set when the specific radio button receive a click event. If you don't want to change your code so much, do something like this:
public class MyAction implements ActionListener{
String m;
public MyAction(String radioButtonLabel){
m = radioButtonLabel;
}
public void actionPerformed(ActionEvent e){
JOptionPane.showMessageDialog(null,
"Your Selection is"+m+" radio button.");
}
public String getString(){
return m;
}
}
And replace the:
first.addActionListener(new MyAction());
by:
first.addActionListener(new MyAction(files));
And improve the names of your variables... it is a little bit confusing!
Hope it helps.
UPDATE
To get the selected radio button:
public static JRadioButton getSelection(ButtonGroup group) {
for (Enumeration e = group.getElements(); e.hasMoreElements();) {
JRadioButton b = (JRadioButton) e.nextElement();
if (b.getModel() == group.getSelection()) {
return b;
}
}
return null;
}
I have a swing application that includes radio buttons on a form. I have the ButtonGroup, however, looking at the available methods, I can't seem to get the name of the selected JRadioButton. Here's what I can tell so far:
From ButtonGroup, I can perform a getSelection() to return the ButtonModel. From there, I can perform a getActionCommand, but that doesn't seem to always work. I tried different tests and got unpredictable results.
Also from ButtonGroup, I can get an Enumeration from getElements(). However, then I would have to loop through each button just to check and see if it is the one selected.
Is there an easier way to find out which button has been selected? I'm programing this in Java 1.3.1 and Swing.
I got similar problem and solved with this:
import java.util.Enumeration;
import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;
public class GroupButtonUtils {
public String getSelectedButtonText(ButtonGroup buttonGroup) {
for (Enumeration<AbstractButton> buttons = buttonGroup.getElements(); buttons.hasMoreElements();) {
AbstractButton button = buttons.nextElement();
if (button.isSelected()) {
return button.getText();
}
}
return null;
}
}
It returns the text of the selected button.
I would just loop through your JRadioButtons and call isSelected(). If you really want to go from the ButtonGroup you can only get to the models. You could match the models to the buttons, but then if you have access to the buttons, why not use them directly?
You must add setActionCommand to the JRadioButton then just do:
String entree = entreeGroup.getSelection().getActionCommand();
Example:
java = new JRadioButton("Java");
java.setActionCommand("Java");
c = new JRadioButton("C/C++");
c.setActionCommand("c");
System.out.println("Selected Radio Button: " +
buttonGroup.getSelection().getActionCommand());
I suggest going straight for the model approach in Swing. After you've put the component in the panel and layout manager, don't even bother keeping a specific reference to it.
If you really want the widget, then you can test each with isSelected, or maintain a Map<ButtonModel,JRadioButton>.
You can put and actionCommand to each radio button (string).
this.jButton1.setActionCommand("dog");
this.jButton2.setActionCommand("cat");
this.jButton3.setActionCommand("bird");
Assuming they're already in a ButtonGroup (state_group in this case) you can get the selected radio button like this:
String selection = this.state_group.getSelection().getActionCommand();
Hope this helps
The following code displays which JRadiobutton is selected from Buttongroup on click of a button.
It is done by looping through all JRadioButtons in a particular buttonGroup.
JRadioButton firstRadioButton=new JRadioButton("Female",true);
JRadioButton secondRadioButton=new JRadioButton("Male");
//Create a radio button group using ButtonGroup
ButtonGroup btngroup=new ButtonGroup();
btngroup.add(firstRadioButton);
btngroup.add(secondRadioButton);
//Create a button with text ( What i select )
JButton button=new JButton("What i select");
//Add action listener to created button
button.addActionListener(this);
//Get selected JRadioButton from ButtonGroup
public void actionPerformed(ActionEvent event)
{
if(event.getSource()==button)
{
Enumeration<AbstractButton> allRadioButton=btngroup.getElements();
while(allRadioButton.hasMoreElements())
{
JRadioButton temp=(JRadioButton)allRadioButton.nextElement();
if(temp.isSelected())
{
JOptionPane.showMessageDialog(null,"You select : "+temp.getText());
}
}
}
}
import javax.swing.Action;
import javax.swing.ButtonGroup;
import javax.swing.Icon;
import javax.swing.JRadioButton;
import javax.swing.JToggleButton;
public class RadioButton extends JRadioButton {
public class RadioButtonModel extends JToggleButton.ToggleButtonModel {
public Object[] getSelectedObjects() {
if ( isSelected() ) {
return new Object[] { RadioButton.this };
} else {
return new Object[0];
}
}
public RadioButton getButton() { return RadioButton.this; }
}
public RadioButton() { super(); setModel(new RadioButtonModel()); }
public RadioButton(Action action) { super(action); setModel(new RadioButtonModel()); }
public RadioButton(Icon icon) { super(icon); setModel(new RadioButtonModel()); }
public RadioButton(String text) { super(text); setModel(new RadioButtonModel()); }
public RadioButton(Icon icon, boolean selected) { super(icon, selected); setModel(new RadioButtonModel()); }
public RadioButton(String text, boolean selected) { super(text, selected); setModel(new RadioButtonModel()); }
public RadioButton(String text, Icon icon) { super(text, icon); setModel(new RadioButtonModel()); }
public RadioButton(String text, Icon icon, boolean selected) { super(text, icon, selected); setModel(new RadioButtonModel()); }
public static void main(String[] args) {
RadioButton b1 = new RadioButton("A");
RadioButton b2 = new RadioButton("B");
ButtonGroup group = new ButtonGroup();
group.add(b1);
group.add(b2);
b2.setSelected(true);
RadioButtonModel model = (RadioButtonModel)group.getSelection();
System.out.println(model.getButton().getText());
}
}
Typically, some object associated with the selected radio button is required. It is not necessarily a String representing the button's label. It could be an Integer containing the button's index or an object of more complicated type T. You could fill and use a Map<ButtonModel, T> as Tom Hawtin suggested, but I propose to extend the model and place the objects there. Here's an improved ButtonGroup that uses this approach.
import javax.swing.*;
#SuppressWarnings("serial")
public class SmartButtonGroup<T> extends ButtonGroup {
#Override
public void add(AbstractButton b) {
throw new UnsupportedOperationException("No object supplied");
}
public void add(JRadioButton button, T attachedObject) {
ExtendedModel<T> model = new ExtendedModel<>(attachedObject);
model.setSelected(button.isSelected());
button.setModel(model);
super.add(button);
}
#SuppressWarnings("unchecked")
public T getSelectedObject() {
ButtonModel selModel = getSelection();
return selModel != null ? ((ExtendedModel<T>)selModel).obj : null;
}
public static class ExtendedModel<T> extends javax.swing.JToggleButton.ToggleButtonModel {
public T obj;
private ExtendedModel(T object) {
obj = object;
}
}
}
You can use this utility class instead of ButtonGroup. Create an object of this class and add buttons along with associated objects to it. For example,
SmartButtonGroup<Integer> group = new SmartButtonGroup<>();
JPanel panel = new JPanel();
for (int i = 1; i <= 5; i++) {
JRadioButton button = new JRadioButton("Button #" + i, i == 3); // select the 3rd button
group.add(button, i);
panel.add(button);
}
After this, you can get the object associated with the currently selected button anytime you need by simply calling getSelectedObject(), like this:
int selectedButtonIndex = group.getSelectedObject();
In case you need just the buttons themselves, you can use the next non-generic class instead.
import javax.swing.JRadioButton;
#SuppressWarnings("serial")
public class RadioButtonGroup extends SmartButtonGroup<JRadioButton> {
public void add(JRadioButton button) {
super.add(button, button);
}
#Override
public void add(JRadioButton button, JRadioButton attachedObject) {
throw new UnsupportedOperationException("Use the short form of addition instead");
}
public JRadioButton getSelectedButton() {
return getSelectedObject();
}
}
You could use getSelectedObjects() of ItemSelectable (superinterface of ButtonModel) which returns the list of selected items. In case of a radio button group it can only be one or none at all.
Add the radiobuttons to a button group then:
buttonGroup.getSelection().getActionCommand
Use the isSelected() method. It will tell you the state of your radioButton. Using it in combination with a loop(say for loop) you can find which one has been selected.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyJRadioButton extends JFrame implements ActionListener
{
JRadioButton rb1,rb2; //components
ButtonGroup bg;
MyJRadioButton()
{
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
rb1=new JRadioButton("male");
rb2=new JRadioButton("female");
//add radio button to button group
bg=new ButtonGroup();
bg.add(rb1);
bg.add(rb2);
//add radio buttons to frame,not button group
add(rb1);
add(rb2);
//add action listener to JRadioButton, not ButtonGroup
rb1.addActionListener(this);
rb2.addActionListener(this);
pack();
setVisible(true);
}
public static void main(String[] args)
{
new MyJRadioButton(); //calling constructor
}
#Override
public void actionPerformed(ActionEvent e)
{
System.out.println(((JRadioButton) e.getSource()).getActionCommand());
}
}
Ale Rojas's answer works fine:
As alternative you can also use the My_JRadiobutton11.addActionListener(this); on your JButton and then make your actions in the actionPerformed function like this (It just uses an extra variable which you have to instantiate (e.g Private String selection;) but it's not a big deal):
public void actionPerformed(ActionEvent arg0) {
if(arg0.getSource() == My_JRadiobutton11){
//my selection
selection = "Become a dolphin";
}else if(arg0.getSource() == My_JRadiobutton12){
//my selection
selection = "Become a Unicorn";
} ..etc
}
jRadioOne = new javax.swing.JRadioButton();
jRadioTwo = new javax.swing.JRadioButton();
jRadioThree = new javax.swing.JRadioButton();
... then for every button:
buttonGroup1.add(jRadioOne);
jRadioOne.setText("One");
jRadioOne.setActionCommand(ONE);
jRadioOne.addActionListener(radioButtonActionListener);
...listener
ActionListener radioButtonActionListener = new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
radioButtonActionPerformed(evt);
}
};
...do whatever you need as response to event
protected void radioButtonActionPerformed(ActionEvent evt) {
System.out.println(evt.getActionCommand());
}