using java swing - java

I need to put a value in to my class from UI (Swing) and then start my method by clicking a button. What should I do?

Getting started with swing

Here's a super simple example of a text field and a button that, when clicked, will get the text value then you can all the method you'd like to pass that value to.
public class ButtonExample extends JPanel
{
private JTextField _text;
public ButtonExample()
{
_text = new JTextField();
setLayout( new BorderLayout() );
add( _text, BorderLayout.NORTH );
add( new JButton( new CaptureTextAction() ), BorderLayout.SOUTH );
}
private class CaptureTextAction extends AbstractAction
{
private CaptureTextAction()
{
super( "Click Me" );
}
#Override
public void actionPerformed( ActionEvent ae )
{
String textToCapture = _text.getText();
// do something interesting with the text
}
}
}

Swing is just the user interface you provide to to your app.
it works like this....
you have buttons, panels and all the stuff you need for providing a proper interface, which means if you need to take text input you'll put textfield or textArea in your UI
swing applications are based on events, thats the basic difference between console based and window based applications, a console based application is sequential it compiles and then executes code sequentially it has no regard of how you interact with it.
a swing application on the other hand is event based, until any event is fired and caught it won't do anything, in java you just handle the event, which means what happens after an event occurs is decided by the programmer.
suppose there is a button click event fires and there is a listener attached to the element then the actionPerformed function gets called and it is executed
suppose you want to get the user name from the app
JButton btnSubmit = new JButton("Submit");
JTextField txtName = new JTextField("", 4);
btnSubmit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String name = txtName.getText();//see below for explanation
printInfo();//write the function call statements here if you want them to be executed when button is clicked
}
});
whenever button is clicked or more generally any event occurs on the button then it creates a string object in the string pool and assigns to it the value of the text field at the time when the button was clicked

Related

Is there a way to open multiple instances of modeless JDialog in java swing without disabling its components?

I have a GUI which consist of a JLabel named "View":
with a mouseClickEvent attached to it. Upon clicking on the "View" JLabel, i can open multiple instances of a modeless JDialog.
The JDialog itself consist of several disabled JTextFields and a JLabel with a mouseClickEvent attached to it which act as a "Close" button:
However upon opening more than one JDialog, the "close" JLabel is disabled and the mouseClickEvent does not work anymore.
Here is my code:
private void viewDoctorClickedEvent(java.awt.event.MouseEvent evt)
{
javax.swing.JFrame topFrame = (javax.swing.JFrame)
javax.swing.SwingUtilities.getWindowAncestor(this);
viewDoctorDialog = new javax.swing.JDialog(topFrame, "View Doctor Details", false);
viewDoctorDialog.setMinimumSize(new java.awt.Dimension(580, 350));
viewDoctorDialog.setResizable(false);
viewDoctorDialog.setDefaultCloseOperation(javax.swing.JFrame.DISPOSE_ON_CLOSE);
viewDoctorDialog.setLocationRelativeTo(topFrame);
// This part is used to collect the values from the selected row of a Jtable and set the
// values to the disabled JTextFields in the JDialog
try
{
int selectedTableRow = doctorListTB.getSelectedRow();
String doctorName = doctorListTB.getValueAt(selectedTableRow, 0).toString();
String doctorEmail = doctorListTB.getValueAt(selectedTableRow, 1).toString();
String doctorPassword = doctorListTB.getValueAt(selectedTableRow, 2).toString();
String doctorAddress = doctorListTB.getValueAt(selectedTableRow, 3).toString();
String doctorPhone = doctorListTB.getValueAt(selectedTableRow, 4).toString();
String doctorDepartment = doctorListTB.getValueAt(selectedTableRow, 5).toString();
viewDoctorNameTF.setText(doctorName);
viewDoctorEmailTF.setText(doctorEmail);
viewDoctorPasswordTF.setText(doctorPassword);
viewDoctorAddressTF.setText(doctorAddress);
viewDoctorPhoneTF.setText(doctorPhone);
viewDoctorDepartmentTF.setText(doctorDepartment);
viewDoctorDialog.add(viewDoctorDialogPanel);
viewDoctorDialog.setVisible(true);
}
catch(Exception e)
{
javax.swing.JOptionPane.showMessageDialog(viewDoctorDialogPanel, "Please select a row to view.", "No data to view.", javax.swing.JOptionPane.ERROR_MESSAGE);
}
}
// Mouse Click Event to close the JDialog upon clicking on the "close" JLabel
private void closeViewButtonClickedEvent(java.awt.event.MouseEvent evt)
{
viewDoctorDialog.dispose();
}
Is there a way to open multiple instances while still retaining the mouseClickEvent of the "close" JLabel in each opened instance of the JDialog?
The JDialog itself consist of several disabled JTextFields and a JLabel with a mouseClickEvent attached to it which act as a "close" button.
Why would use use a JLabel with a MouseListener to close the dialog? A JLabel was not designed to do processing like this.
Use a JButton with an ActionListener for the "Close" functionality.
If you want the button to look like a label then you can use:
button.setBorderPainted( false );
the mouseClickEvent does not work anymore.
viewDoctorDialog = new javax.swing.JDialog(topFrame, "View Doctor Details", false);
It looks to me like you have an instance variable to track the open dialog. When you create the second dialog, you change the reference of the variable to point to the second dialog so you no longer have a reference to the original dialog.
So when using JButton, as suggested above, the code in your ActionListener for the "Close" button would then be something like:
Jbutton button = (JButton)event.getSource();
Window window = SwingUtilities.windowForComponent( button );
window.dispose();
So you don't even need a special variable to track the dialog.
Your "View Doctor Detials" dialog should be defined in a separate class. All the variables needed for that class should be defined in that class, not your main class that displays the dialog. So when you create an instance of the class you would pass in the JTable.
This will make it easier to structure your code so that each class only contains ActionListeners that are relevant to the class. So the main class will contain listeners to display the child dialogs. The child dialogs will have listener to "Close" the dialogs.

addActionListener argument is incorrect

In the program I want to use actionListener to monitor a TextFrame. I created a class called monitor and there is a constructor which invoke the whole TextFieldFrame, TFFrame.
class Monitor implements ActionListener{
TFFrame tf = null;
public void Monitor(TFFrame tf){
this.tf = tf;
}
In the TFFrame class, I add a actionListener which invoke itself.
class TFFrame extends Frame{
TextField num1, num2, num3;
public void launchFrame(){
num1 = new TextField(10);
num2 = new TextField(10);
num3 = new TextField(20);
Label plus = new Label("+");
Button equal = new Button("=");
equal.addActionListener(new Monitor(this));
However the compiler fails with an error and the error is that the argument in the Monitor is incorrect. What is the problem?
ActionListener is an interface and has only one required method:
actionPerformed(ActionEvent e)
You don't appear to have actually implemented that method here. Normally it's called under the hood when an appropriate event occurs.
I think you may not be using events and listeners correctly. Logically speaking, given what I understand from your example code, you'd have something like this:
TFFrame tf = new TFFrame();
tf.addActionListener( new Monitor() );
One problem is that the frame has it's own set of events and will not communicate the events from clicking buttons or focusing on textfields up through the frame to the listener. The frame's events are what will end up calling the actionPerformed method that you should have in Monitor.
You could certainly add other stuff to your custom listener, but the listener generally doesn't contain a reference to thing its listening to. Perhaps what you really wanted was just an actionlistener to check when the equals button is pressed, in which case you'd have something like this.
TFFrame tf = new TFFrame();
tf.launchFrame();
Inside of the launchFrame method you would add an action listener to the equals button with some kind of listener for buttons.
equals.addActionListener( new ButtonListener() );
Now for that to work you'd have to create a class called button listener that implements action listener, and then write the appropriate event handling code inside of it's actionPerformed method.
P.S.
To be perfectly honest, much of this inference. If I'm wrong about what you want, then I'd recommend you go and read through this: https://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html

Java JButton List Call Back

I am trying to create a JButton that will call back a selected list of items with the number of the items selected.
I have a primitive list made out displaying different JRadioButtons but with the JRadioButtons named rather than listed out. I have looked on another site that uses Vector collections I believe use the basic for iteration method but I just feel like I am getting a bit overwhelmed.
This is my button code right now.
// create new ButtonHandler for button event handling
ButtonHandler handler = new ButtonHandler();
submitButton.addActionListener( handler );
} // end Frame constructor
// inner class for submit button event handler
private class ButtonHandler implements ActionListener
{
//handle button event
public void actionPerformed( ActionEvent event )
{
JOptionPane.showMessageDialog(Frame.this, String.format(
"You entered: %s", event.getActionCommand() ) );
Am I anywhere near the right answer here or am that far off?

Handle RadioButton events after button clicked

help,
my questions are:
why isn't itemStateChanges triggered, I tried to put it in the inner class ButtonHandler and also in RadioButtonHandler Im having trouble with it, what is the right way to do it?
I want to trigger and check the marked JRadioButtons after the user click the "check" button.
What is the right way to check which button was clicked, I feel like comparing the strings is bad programming practise. Maybe using an ID ?
How should I make a "reset" button(start over), I want to uncheck all radio buttons and run the constructor once again.
Thank you for your help !
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;
public class ExamFrame extends JFrame {
static ArrayList<Question> qArrList;
JRadioButton a1,a2,a3,a4;
public ExamFrame() {
super("Quiz");
setLayout(new GridLayout(0, 1));
GridBagConstraints gbc = new GridBagConstraints();
Exam exam = new Exam();
qArrList = exam.getExam();
int count=0;
for(Question q : qArrList){
count++;
JLabel questionLabel = new JLabel(count+". "+q.getQustion()); //swing constant ?
ArrayList<String> ansRand = q.getAllRandomAns();
a1 = new JRadioButton(ansRand.get(0));
a2 = new JRadioButton(ansRand.get(1));
a3 = new JRadioButton(ansRand.get(2));
a4 = new JRadioButton(ansRand.get(3));
add(questionLabel);
add(a1);add(a2,gbc);add(a3);add(a4);
ButtonGroup radioGroup = new ButtonGroup(); //logical relationship
radioGroup.add(a1);radioGroup.add(a2);radioGroup.add(a3);radioGroup.add(a4);
}
//buttons:
JButton checkMe = new JButton("Check Exam");
JButton refresh = new JButton("Start Over");
ButtonHandler handler = new ButtonHandler();
checkMe.addActionListener(handler);
refresh.addActionListener(handler);
add(checkMe);
add(refresh);
}
/** Listens to the radio buttons. */
public class ButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent e) {
if(e.getActionCommand().equals("Start Over")){ //id?
//how to do this?
}
else{
RadioButtonHandler handler = new RadioButtonHandler();
a1.addItemListener(handler);
System.out.println("success?");
}
JOptionPane.showMessageDialog(ExamFrame.this, String.format("You pressed: %s", e.getActionCommand()));
}
public void itemStateChanged(ItemEvent e) //can i add it here?
{
JOptionPane.showMessageDialog(ExamFrame.this, String.format("yes?"));
System.out.println("success!");
}
}
public class RadioButtonHandler implements ItemListener
{
public void itemStateChanged(ItemEvent e)
{
JOptionPane.showMessageDialog(ExamFrame.this, String.format("radio state changed"));
}
}
}
why "itemStateChanges" isn't triggered, i tried to put it in the inner
class "ButtonHandler" and also in "RadioButtonHandler" Im having
troubles with it, what is the right way to do it? I want to trigger
and check the marked JRadioButtons after the user click the "check"
button.
ButtonHandler is implemented with ActionListener only:
public class ButtonHandler implements ActionListener{}
The itemStateChanged(ItemEvent) function belongs to ItemListener. This function is triggered if state of a source component to which this listener is registered gets changed. So implement the ItemListener. However, one more thing to note, that JButton doesn't respond to ItemListener but JRadioButton will. Because this Item events are fired by components that implement the ItemSelectable interface. Some example of such components are: check boxes, check menu items, toggle buttons and combo boxes including Radio Buttons as mentioned above.
What is the right way to check which button was clicked, i feel like
comparing the strings is wrong programming. Maybe using an ID
Well using the event source function: e.getSource(), check whither the type of the source is your expected type and cast it to appropriate type. And then you can use getName(String) function and check the name you were expecting. Of-course you should assign the name using setName(String) after initialization of component. Or using the component reference directly if it is declared in the Class context and you have direct access to the component.
#Override
public void itemStateChanged(ItemEvent e) {
if(e.getSource() instanceof JCheckBox)
{
JCheckBox checkBox = (JCheckBox)e.getSource();
if(checkBox.getName().equals("expectedName"))
; // do my thing
}
}
How should i make a "reset" button(start over), i want to uncheck all
radio buttons and run the constructor once again.
Well you are working with ButtonGroup. And ButtonGroup has a nice function: clearSelection() to help with whatever(I could not understand the part: run the constructor part) you want.
Edit: As you wanted me to see an ItemListener implemented class, Yes i can see that But:
i can not see that you have actually registered an instance of that class(a1.addItemListener(handler);) to any component before performing any action on the component to which ButtonHandler is registered to: checkMe, refresh
In addition to that, in this action performed function, you are checking with
action command, which you haven't even set with JButton.setActionCommand(String) function. You should not assign a (Item)listener depending on event-occurrence of another (Action)listener.
Tutorial:
How to Write an ItemListener
How to Write an ActionListener
How to Use the ButtonGroup Component

Can two JButton have the same mouse clicked event function?

I am developing a calculator in Java language. The problem is that, i put ten buttons for digits(0,1,2..9) and i want that when i clicked one of them, all perform the same mouse clicked function. Is it possible? In netbeans, it does not let me do that, or i couldnt achieve. Thank you for helping.
Yes. Add the same listener to both buttons you are using.
For example, suppose you are using actionListener then:
public class ListenerClass implements Action{
#override
public void actionPerformed(ActionEvent e) {
//here retrieve information on which button has generated the event
}
}
ListenerClass listener = new ListenerClass();
JButton first = new JButton();
JButton second = new JButton();
first.addActionListener(listener);
second.addActionListener(listener);

Categories

Resources