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()));
Related
I was trying to make a program that calculates the numbers of the TextField. To let it start calculating you have to press a button and to do that I have to add an ActionListener to the button but it isn't possible as far as I can see, because you can't use this in a static context.
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public abstract class math extends JFrame implements ActionListener {
public static void main(String[] args) {
JFrame frame = new JFrame();
JButton button = new JButton("text");
JPanel mainPanel =new JPanel();
JLabel mainLabel = new JLabel("text");
JTextField mainField = new JTextField(5);
button.addActionListener(this);
mainPanel.add(mainLabel);
mainPanel.add(mainField);
mainPanel.add(button);
frame.setTitle("text");
frame.setSize(1000, 700);
frame.setVisible(true);
frame.add(mainPanel);
//when the button something gets done here
double num = Double.valueOf(mainField.getText());
num * 4;
}
}
I know how to write an ActionListener that is not in the main method but here it has to be, at least I think so. I hope while shortening the code I didn't cut out some important parts of it.
Option 1: instantiate an object that implements ActionListener
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// whatever you need to do
System.out.println("The button was pressed!");
}
});
Option 2: use a lambda function (Java 8 or above)
button.addActionListener(e -> {
// whatever you need to do
System.out.println("The button was pressed!");
});
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());
}
}
By now, I already know my code is flawed. I just want to know why it's flawed. I want to activate the "webButton" so that when it gets clicked, it prints a message on the console that reads "This opens Mozilla Firefox."
package smartphone;
import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.*;
import java.util.Scanner;
public class Smartphone implements ActionListener {
public static void main(String[] args) {
{
{
JFrame container = new JFrame();
container.setLayout(new BorderLayout());
Scanner daniel = new Scanner(System.in);
JButton webButton = new JButton(new ImageIcon("Firefox.png"));
JButton phoButton = new JButton(new ImageIcon("Facebook.png"));
JButton texButton = new JButton(new ImageIcon("Phone.png"));
JButton setButton = new JButton(new ImageIcon("Settings.png"));
JButton smsButton = new JButton(new ImageIcon("sms.png"));
container.setTitle("Smartphone Interface!");
container.setSize(240,340);
container.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
container.add(setButton, BorderLayout.CENTER);
container.add(webButton, BorderLayout.SOUTH);
container.add(texButton, BorderLayout.NORTH);
container.add(phoButton, BorderLayout.EAST);
container.add(smsButton, BorderLayout.WEST);
container.setVisible(true);
webButton.addActionListener(instanceofSmartphone);
}
}
}
}
Do this.
webButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
}
});
If you want to use the ActionListener interface then, implement it in your Frame class and then replace that instanceOfSmartphone with
webButton.addActionListener(this);
And put this outside the method
public void actionPerformed(ActionEvent e) {
if(e.getSource() == webButton) {
}
}
You need to implement the actionPerformed method. An example follows.
public void actionPerformed(ActionEvent e) {
System.out.println("This method opens Mozilla Firefox.");
}
Additionally, you need to change how you add the action listener to the following.
webButton.addActionListener(this);
There are also a number of other issues. Here is a modified version of your code to get it working but far from perfect or what you will want in the end. I strongly recommend you walk through all of the tutorials in order at the below website. It doesn't get any easier than what they have. Also, if your not already using it, you should try Netbeans or some other IDE. It give you feedback that may help while you are starting out.
https://docs.oracle.com/javase/tutorial/
package smartphone;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.util.Scanner;
public class Smartphone extends Frame implements ActionListener {
static JButton webButton = new JButton(new ImageIcon("Firefox.png"));
static JButton phoButton = new JButton(new ImageIcon("Facebook.png"));
static JButton texButton = new JButton(new ImageIcon("Phone.png"));
static JButton setButton = new JButton(new ImageIcon("Settings.png"));
static JButton smsButton = new JButton(new ImageIcon("sms.png"));
Smartphone(){
webButton.addActionListener(this);
}
public static void main(String[] args) {
Smartphone container = new Smartphone();
container.setLayout(new BorderLayout());
Scanner daniel = new Scanner(System.in);
container.setTitle("Smartphone Interface!");
container.setSize(240, 340);
container.add(setButton, BorderLayout.CENTER);
container.add(webButton, BorderLayout.SOUTH);
container.add(texButton, BorderLayout.NORTH);
container.add(phoButton, BorderLayout.EAST);
container.add(smsButton, BorderLayout.WEST);
container.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("This opens a Firefox Webbrowser.");
}
}
You need to add an ActionListener to the buttons INSIDE of the constructor: buttonName.addActionListener(this);.
Then you need to create the following method:
public void actionPerformed(ActionEvent event) {
Object control = event.getSource();
if (control == buttonName) {
//Run code...
}
}
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()
}
I am trying to listen to mouse events coming from both a JLabel and a JTextField. However, I am only able to listen to mouse events from JLabel, but not JTextField.
Consider this code:
class FieldPanel extends JPanel{
JLabel label;
JTextField text;
public FieldPanel(){
label = new JLabel("This is a test label");
text = new JTextField("This is a test field");
add(label);
add(text);
}
}
class OuterPanel extends JPanel{
FieldPanel fieldPanel;
public OuterPanel(){
fieldPanel = new FieldPanel();
fieldPanel.addMouseListener(new MouseAdapter(){
#Override
public void mousePressed(MouseEvent event) {
System.out.println("Mouse pressed !!");
}
});
add(fieldPanel);
}
}
public class UITest{
public static void main (String args[]){
JFrame frame = new JFrame();
OuterPanel outerPanel = new OuterPanel();
frame.getContentPane().add(outerPanel);
frame.pack();
frame.setVisible(true);
}
}
The 'Mouse Pressed !!' message is displayed when I click on the JLabel. However, it does not get displayed when I click on the JTextField. Why is this the case?
Thanks!
I think this is an interesting question which kinda stomp on the finding accidentally. I will explain using the snippet code below.
class FieldPanel extends JPanel
{
//JLabel label;
JTextField text;
public FieldPanel()
{
//label = new JLabel("This is a test label");
text = new JTextField("This is a test field");
//add(label);
add(text);
}
}
when you run the code with the changes above, what we expect the output only the text field right? Then if you click on the area near to the textfield outside region, check in your console output, it actually print out Mouse pressed !!
So I went a little deeper to study into JTextField, it actually consist of the JTextField and JTextComponent. When you called the constructor new JTextField("This is a test field");, the text is actually set into the JTextComponent and not JTextField and I guess that is why when you click the text, it does not trigger the mousePressed event but it trigger only the JTextField only.
Below is my full code. If you want the text field to aware of the mouse pressed, consider implements MouseAdapter() in your FieldPanel class and add addMouseListener(this) for text and label.
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class MyMouseEvent extends JPanel
{
public MyMouseEvent()
{
FieldPanel fieldPanel;
fieldPanel = new FieldPanel();
fieldPanel.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent event)
{
System.out.println("Mouse pressed !!");
}
});
add(fieldPanel);
}
class FieldPanel extends JPanel
{
//JLabel label;
JTextField text;
public FieldPanel()
{
//label = new JLabel("This is a test label");
text = new JTextField("This is a test field");
//add(label);
add(text);
}
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyMouseEvent evt = new MyMouseEvent();
evt.setOpaque(true);
frame.setContentPane(evt);
frame.pack();
frame.setVisible(true);
}
public static void main (String args[])
{
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run()
{
createAndShowGUI();
}
});
}
}
Thanks for all the answers.
I found some sort of workaround. I am changing my code so that I listen directly to the JTextField component, as opposed to listening to the panel.