Call actionPerformed Method using normal method of class - java

I am trying to call the actionPerformed() in normal method of class. I know that it get automatically executed on whenever button get pressed. But I want to call that method when ENTER button get pressed on Specific textfield. Is it possible to call actionPerformed() in keyPressed() or in normal function/method.
The following code will give you rough idea what I want to do.
void myFunction()
{
actionPerformed(ActionEvent ae);
}
public void actionPerformed(ActionEvent ae)
{
//my code
}
Thanks in advance

If you want, some actionPerformed() method of a JButton to be executed on pressing ENTER inside a JTextField, then I guess you can use the doClick(), method from AbstractButton class to achieve this. Though this approach, might can override the original behaviour of the JTextField on press of the ENTER key :(
Please have a look at this code pasted below, to see if this is what, stands fit for your needs :-) !!!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonClickExample
{
private JTextField tfield;
private JButton button;
private JLabel label;
private ActionListener actions = new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
if (ae.getSource() == button)
{
label.setText(tfield.getText());
}
else if (ae.getSource() == tfield)
{
button.doClick();
}
}
};
private void displayGUI()
{
JFrame frame = new JFrame("Button Click Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(5, 5));
JPanel centerPanel = new JPanel();
tfield = new JTextField("", 10);
button = new JButton("Click Me or not, YOUR WISH");
tfield.addActionListener(actions);
button.addActionListener(actions);
centerPanel.add(tfield);
centerPanel.add(button);
contentPane.add(centerPanel, BorderLayout.CENTER);
label = new JLabel("Nothing to show yet", JLabel.CENTER);
contentPane.add(label, BorderLayout.PAGE_END);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
new ButtonClickExample().displayGUI();
}
});
}
}

I know this is an old thread, but for other people seeing this my recomendation is something like this:
// This calls the method that you call in the listener method
void performActionPerformedMethod(){
actionPerformed(ActionEvent e);
}
// This is what you want the listener method to do
void actionPerformedMethod(){
// Code...
}
// This is the interface method
public void actionPerformed(ActionEvent e){
actionPerformedMethod()
}

Related

How to make Text Field in GUI submit text into Console?

I am not sure how to make this all work together but I am supposed to make the text field display the text typed but only when we press submit. It is supposed to display the text in the console. So I need some help adding onto this to finish the code.
import java.awt.*;
import javax.swing.*;
public class testExample1 extends JFrame {
JTextField textField1;
JButton mybutton;
public testExample1() {
setSize(300, 100);
setTitle("Text Action");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
textField1 = new JTextField(10);
mybutton = new JButton("Submit");
add(textField1);
add(mybutton);
setVisible(true);
System.out.println()
}
public static void main(String args[]) {
new testExample1();
}
}
You need to add an ActionListener to your submit button.
mybutton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(textField1.getText());
}
});
Or
With Java 8 Lambda expressions:
mybutton.addActionListener(e -> System.out.println(textField1.getText()));

setContentPane() and addActionListener gets a NullPointerException

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Form1 {
private JPanel panel1;
private JButton button1;
public Form1() {
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked");
}
});
}
public static void main(String args[]){
JFrame frame = new JFrame("Form 1");
frame.setContentPane(new Form1().panel1);
frame.pack();
frame.setVisible(true);
}
}
The error relates to the setContentPane in main method and then also the actionListener. I've posted the exact error below. Why is this? I created this using the IntelliJ IDEA GUI form creator.
Exception in thread "main" java.lang.NullPointerException
at Form1.<init>(Form1.java:12)
at Form1.main(Form1.java:22)
In Java you can't use variables that are not initialized, else you will receive a NPE. See the following code and please read a Java book :)
public class Form1 {
private JPanel panel1;
private JButton button1;
public Form1() {
panel1 = new JPanel();
button1 = new JButton1("Press Me");
panel1.add(button1);
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked");
}
});
}
public static void main(String args[]){
JFrame frame = new JFrame("Form 1");
frame.setContentPane(new Form1().panel1);
frame.pack();
frame.setVisible(true);
}
}
So there are 2 issues that you're going to run into that are causing that error. After you create an object (JButton, JPanel in this case), you have to instantiate them. There are a lot of different ways to do this, and it depends on what you're trying to do, but the simplest fix for your issue here is to add the following lines in the constructor:
panel1 = new JPanel();
button1 = new JButton();
Your code should run fine after that.

How to pass value between two jframes

I have two jframes,
I want to get value from opened another jframe to other opened jframe.
when click jframe1 open button showing jframe2 and type some text in text field and click ok button, text field value want to get jframe1 jlable. how to do this i tried but i can't find a way to do this.
Is this possible ?
Use a callback,
add this code to your project:
Define an interface
public interface ICallbackListener{
void onNewEvent(String msg);
}
add to jframe 2:
private ICallbackListener myListener;
public void addCallback(ICallbackListener myListener){
this.myListener = myListener;
}
...
if(myListener!=null){
myListener.onNewEvent("myMessage");
}
...
add to jframe 1:
private ICallbackListener myListener;
ICallbackListener i = new ICallbackListener() {
#Override
public void onNewEvent(String msg) {
// TODO Auto-generated method stub
}
};
public void setCallback( ){
jframe2.addCallback(myListener);
}
now, every thime the jframe2 call the interface method you will get asynchronous a call to the TODO label in the jframe1
Try This
import java.awt.FlowLayout;
import javax.swing.*;
import java.awt.event.*;
class TestFrameExample extends JFrame implements ActionListener{
static JLabel label ;
public static TestFrameExample test;
TestFrameExample()
{
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
label = new JLabel("This is a label!");
JButton button = new JButton("Open");
button.setText("Press me");
button.addActionListener(this);
panel.add(label);
panel.add(button);
add(panel);
setSize(300, 300);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent a)
{
new TestFrameExample1();
}
public static void main(String s[]) {
test=new TestFrameExample();
}
}
class TestFrameExample1 extends JFrame implements ActionListener {
JTextField t;
TestFrameExample test;
public TestFrameExample1()
{
setSize(300, 300);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setLayout(null);
t=new JTextField();
t.setBounds(100,20,150,20);
JButton button=new JButton("oK");
button.setBounds(100,50,100,30);
button.addActionListener(this);
add(t);
add(button);
}
public void actionPerformed(ActionEvent a)
{
test.label.setText(t.getText());
}
}
create a method that takes jframe1 in the jframe2
in the open button action event create a object from jframe2 and call that method that take jframe1.
so when u click Ok button in the jframe2 pass that text field value to the jframe1 object (that u passed to the jframe2) via a methdo
public class jframe1 {
public void actionPerformed(ActionEvent a){
jfame2 jf2 = new jframe2();
jf2.setJframe1(this);
}
public void updateLable(String value){
lblIdk.setText(value);
}
}
public class jframe2 {
private jframe1 jf1;
public void setJframe1(jframe1 jf1){
this.jf1 = jf1;
}
public void actionPerformed(ActionEvent a){
this.jf1.updateLable(txtidk.getText());
}
}

Java Modal Dialog Won't Block Code Execution

Basically.. I made a JDialog using swing. And now I want it to return a value to the JFrame that called it. Problem is, whenever I call the constructor for the JDialog, it won't block the thread even though I've set setModal(true). Am I missing something obvious here?
private final JPanel contentPanel = new JPanel();
private File chosenFile = null;
private JList list;
private File[] files;
public File getInformation()
{
return chosenFile;
}
/**
* Create the dialog.
*/
public PatientPicker(JFrame parent)
{
super(parent);
setModal(true);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setLocationRelativeTo(parent);
setBounds(100, 100, 450, 396);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
files = new File(ClientInfo.GetAppData() + "/patients").listFiles(new TextFileFilter());
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("OK");
okButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
if(files.length != 0)
chosenFile = files[list.getSelectedIndex()];
dispose();
}
});
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
}
{
JButton cancelButton = new JButton("Cancel");
cancelButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
dispose();
}
});
cancelButton.setActionCommand("Cancel");
buttonPane.add(cancelButton);
}
}
}
And then here is how I create it:
PatientPicker patientPicker = new PatientPicker(frmReportGenerator);
File dataFile = patientPicker.getInformation();
You state:
Problem is, whenever I call the constructor for the JDialog, it won't block the thread even though I've set setModal(true). Am I missing something obvious here?
The constructor will never block the event thread. Modality means that the event thread is blocked only when you call setVisible (true) on your modal dialog (as per the api).
Unrelated problem: you should not use MouseListeners on JButtons but rather ActionListeners. Otherwise you will run into major problems now, such as when you press the file via the space bar, and while it does depress, nothing happens, and in later code, such as say when you make the button disabled, and yet it is still functioning, even though it looks disabled.
Now if you are still having problems, then you may wish to post more code, a minimal code example program which would allow us to understand and experience your problem.
Edit
You state:
Yes. The user chooses a file in the JDialog and I want it to return to the JFrame that called it.
Why not just use a JFileChooser modal dialog?
Edit 2
An example using a JOptionPane:
import java.awt.event.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class SwingFoo extends JPanel {
private JTextField fileField = new JTextField(20);
private JButton showDialog = new JButton(new ShowDialogAction("Show Dialog",
KeyEvent.VK_D, this));
public SwingFoo() {
fileField.setEditable(false);
fileField.setFocusable(false);
add(new JLabel("File Selected:"));
add(fileField);
add(showDialog);
}
public void setFileFieldText(String text) {
fileField.setText(text);
}
private static void createAndShowGui() {
SwingFoo mainPanel = new SwingFoo();
JFrame frame = new JFrame("SwingFoo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class ShowDialogAction extends AbstractAction {
private SwingFoo swingFoo;
public ShowDialogAction(String name, int mnemonic, SwingFoo swingFoo) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
this.swingFoo = swingFoo;
}
#Override
public void actionPerformed(ActionEvent e) {
PatientPicker patientPicker = new PatientPicker();
int result = JOptionPane.showConfirmDialog(swingFoo, patientPicker,
"Select Something", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
swingFoo.setFileFieldText(patientPicker.getSelectedItem());
}
patientPicker.setVisible(true);
}
}
#SuppressWarnings("serial")
class PatientPicker extends JPanel {
private static final String[] ITEMS = {"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Sunday", "Fubar", "Snafu", "DILLIGAF", "BOHICA"};
private JList<String> selectionList = new JList<>(ITEMS);
public PatientPicker() {
add(new JScrollPane(selectionList));
selectionList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
public String getSelectedItem() {
return selectionList.getSelectedValue();
}
}
What you need to do is have a way to send a notification to your main window once the user has completed interacting with the dialog assuming they clicked the ok button.
You can do this by creating an anonymous class and passing that along in the constructor of your Dialog.
let's assume that you open the dialog with a button called openDialogBtn from the main window:
openDialogBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new PatientPicker(this, new FileSelectionNotifier() {
public void okButtonPressed(File chosenFile) {
// do whatever you need to do with the file (assign to a member variable
// or call another thread to do some kind of processing
}
});
In your dialog window you would need to have something like this:
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
// notify that the ok button was pressed
fileSelectionNotifier.okButtonPressed(chosenFile);
}
}

Adding jinternalframe class to jdesktoppane using other jinternalframe class

I'm creating a very simple program.
I have created this classes :
MainJframeClass, JDesktopPaneClass, JinternalFrameClass1 and JinternalFrameClass2.
what ive done is that i instantiated my jdesktoppaneclass and named it desktoppane1 and i added it to the MainJframeclass. i have also instantiated the 2 jinternalframes and named it internal1 and internal2. Now, i have button in mainjframeclass that when i press, i add the internal1 to desktoppane1. what my problem now is how to add the internal2 to desktoppane1 using a button placed somewhere in internal1. i know that why could i just add another button to desktoppane1 and add the internal2. but i have done it already, i just want to solve this problem. if you can help me please. sorry for my english by the way.
It's simply a matter of references. The code that adds something to the JDesktopPane must have a reference to it, and so you will need to pass that reference into the class that needs it say via either a constructor parameter or a method parameter.
Edit 1
For example:
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
public class ReferenceExample extends JPanel {
private JDesktopPane desktop = new JDesktopPane();
private Random random = new Random();
public ReferenceExample() {
JButton addInternalFrameBtn = new JButton("Add Internal Frame");
addInternalFrameBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
addInternalFrame();
}
});
JPanel btnPanel = new JPanel();
btnPanel.add(addInternalFrameBtn);
setPreferredSize(new Dimension(600, 450));
setLayout(new BorderLayout());
add(new JScrollPane(desktop), BorderLayout.CENTER);
add(btnPanel, BorderLayout.SOUTH);
}
public void addInternalFrame() {
MyInternalFrame intFrame = new MyInternalFrame(ReferenceExample.this);
int x = random.nextInt(getWidth() - intFrame.getPreferredSize().width);
int y = random.nextInt(getHeight() - intFrame.getPreferredSize().height);
intFrame.setLocation(x, y);
desktop.add(intFrame);
intFrame.setVisible(true);
}
private static void createAndShowUI() {
JFrame frame = new JFrame("Reference Eg");
frame.getContentPane().add(new ReferenceExample());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
class MyInternalFrame extends JInternalFrame {
// pass in the reference in the constructor
public MyInternalFrame(final ReferenceExample refEg) {
setPreferredSize(new Dimension(200, 200));
setClosable(true);
JButton addInternalFrameBtn = new JButton("Add Internal Frame");
addInternalFrameBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// use the reference here
refEg.addInternalFrame();
}
});
JPanel panel = new JPanel();
panel.add(addInternalFrameBtn);
getContentPane().add(panel);
pack();
}
}
how to add the internal2 to desktoppane1 using a button placed somewhere in internal1.
In the ActionListener added to your button you can use code like the following to get a reference to the desktop pane:
Container container = SwingUtilities.getAncestorOfClass(JDesktopPane.class, (Component)event.getSource());
if (container != null)
{
JDesktopPane desktop = (JDesktopPane)container;
JInternalFrame frame = new JInternalFrame(...);
desktop.add( frame );
}

Categories