I have a problem in my program. Here's my code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;`
public class click_rep extends JFrame{`
public click_rep(){
super("CLICK");
final JButton btn1 = new JButton("CLICK HERE");
final JLabel label = new JLabel();
FlowLayout flo = new FlowLayout();
setLayout(flo);
add(btn1);
setSize(315,120);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
btn1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
try{
String command = e.getActionCommand();
if (command.equals(btn1)){
label.setText("CLICK");
setVisible(true);
}
}catch(Exception e1){
e1.printStackTrace();
}
}
});
}
public static void main(String[] a){
click_rep cp = new click_rep();
}
}
My problem is that the ActionEvent won't appear. What will I do to make the ActionEvent appear?
Hopefully someone can help me. Thanks for the help.
Take a closer look at this...
String command = e.getActionCommand();
if (command.equals(btn1)){
command is a String and btn1 is a JButton, when are they likely to ever be equal?
There are a few ways you might fix it, you could, for example, do something like this...
if ("CLICK HERE".equals(command)) {
Or something like this...
if (e.getSource() == btn1) {
But I prefer the first one...
But, because the ActionListener is an annoymouse listener registered to btn1, the source of the event can never be anything other then btn1, so you could simply do something like this instead...
btn1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
label.setText("CLICK");
// Not sure what this is meant for, as the component
// must already be visible in order for the user to
// activate the button...
setVisible(true);
}
});
Related
import java.awt.*;
import java.sql.*;
import java.util.*;
import java.awt.event.*;
import javax.swing.*;
public class nava extends JFrame implements ActionListener
{
Button b1=new Button("clear");
TextField t1=new TextField();
public nava()
{
this.setLayout(new GridLayout(2,2));
b1.addActionListener(this);
this.setSize(200,200);
add(t1);
add(b1);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
{
t1.setText(""); //without space
}
}
public static void main(String r[])
{
new nava().show();
}
}
On clicking the button b1 the TextField should get empty but it is not
getting empty.The textfield just remain the same .But when I put space in the actionPerformed function it add a space in textfield. Please tell me what is the problem with the code.
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
{
t1.setText(" "); //with space
}
}
Use Swing components, not AWT components and the code should work. For example use JButton and JTextField not Button and TextField. Also don't call deprecated methods such as show(). Please consider checking the Swing tutorials as they'll teach you much you'll find useful. For example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class Nava extends JFrame implements ActionListener {
JButton b1 = new JButton("Clear");
JTextField t1 = new JTextField("Fubar", 10);
public Nava() {
this.setLayout(new GridLayout(2, 2));
b1.addActionListener(this);
// this.setSize(200, 200);
add(t1);
add(b1);
b1.setMnemonic(KeyEvent.VK_C); // alt-c to activate button
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == b1) {
t1.setText("");
}
}
public static void main(String r[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Nava nava = new Nava();
nava.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
nava.pack(); // let components and layout managers size themselves
nava.setLocationByPlatform(true);
nava.setVisible(true);
}
});
}
}
As an aside, you will want to learn and use Java naming conventions. Variable names should all begin with a lower letter while class names with an upper case letter. Learning this and following this will allow us to better understand your code, and would allow you to better understand the code of others.
As for why your code doesn't work -- I honestly don't know as I don't work directly with AWT library components; very few people do. Edit: note this similar question. The authors of that question don't know why setText("") but offer a work-around:
// first this:
tf.setText(" ");
// followed by this:
tf.setText("");
I am having problems clearing contents of TextField in AWT using setText() method. Apparently, setText("") does not clear the contents of the TextField on pressing the 'Reset' button. Here's my program:
import java.awt.*;
import java.awt.event.*;
public class form extends Frame
{
Label lbl = new Label("Name:");
TextField tf = new TextField();
Button btn = new Button("Reset");
public form()
{
tf.setColumns(20);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
btn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
tf.setText(""); //Problem occurs here. This does not clear the contents of the text field on pressing the 'Reset' button.
}
});
add(lbl);
add(tf);
add(btn);
setLayout(new FlowLayout());
setSize(400,100);
setVisible(true);
setTitle("Form");
}
public static void main(String[] args)
{
new form();
}
}
Can someone please tell me where I went wrong or suggest an alternative? Thanks.
I see the problem as well using Java 8u11. I seem to remember this being filed as a known bug, but I can't seem to find it now.
A solution that works for me is to add an intermediate step:
public void actionPerformed(ActionEvent e) {
tf.setText(" ");
tf.setText("");
}
I'm not sure why this is necessary, I think it's a bug with the setText() function specifically ignoring empty Strings. If somebody finds the filed bug there would be more information there.
Add space in setText(" ") in function and see if it works. But there after there will be one space.
I have my JButton set up and everything but it does absolutely nothing. Could someone tell me how to add a command such as system.out.println or some Scanner commands to a JButton?
Here is my line of code. It is very simple and I'm just testing JButton to add it to some of my other programs
import javax.swing.*;
public class Swing extends JFrame {
JButton load = new JButton("Load");
JButton save = new JButton("Save");
JButton unsubscribe = new JButton("Unsubscribe");
public ButtonFrame() {
super ("ButtonFrame");
setSize(140, 170);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel();
pane.add(load);
pane.add(save);
pane.add(unsubscribe);
add(pane);
setVisible(true);
}
public static void main(String[] arguments) {
ButtonFrame bf = new ButtonFrame();
}
}
See How to Write an Action Listener.
I suggest you read the entire tutorial (or keep a link to it for reference) as it contains all the Swing basics.
Hope this helps
load.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Here goes the action (method) you want to execute when clicked
System.out.println("You clicked the button load");
}
});
//The same for save button
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Here goes the action (method) you want to execute when clicked
System.out.println("You clicked the button save");
}
});
How can I call a method by pressing a JButton?
For example:
when JButton is pressed
hillClimb() is called;
I know how to display messages etc when pressing a JButton, but want to know if it is possible to do this?
Many thanks.
If you know how to display messages when pressing a button, then you already know how to call a method as opening a new window is a call to a method.
With more details, you can implement an ActionListener and then use the addActionListener method on your JButton. Here is a pretty basic tutorial on how to write an ActionListener.
You can use an anonymous class too:
yourButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
hillClimb();
}
});
Here is trivial app showing how to declare and link button and ActionListener. Hope it will make things more clear for you.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class ButtonSample extends JFrame implements ActionListener {
public ButtonSample() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(100, 100);
setLocation(100, 100);
JButton button1 = new JButton("button1");
button1.addActionListener(this);
add(button1);
setVisible(true);
}
public static void main(String[] args) {
new ButtonSample();
}
#Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("button1")) {
myMethod();
}
}
public void myMethod() {
JOptionPane.showMessageDialog(this, "Hello, World!!!!!");
}
}
Fist you initialize the button, then add ActionListener to it
JButton btn1=new JButton();
btn1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
hillClimb();
}
});
You need to add an event handler (ActionListener in Java) to the JButton.
This article explains how to do this.
btnMyButton.addActionListener(e->{
JOptionPane.showMessageDialog(null,"Hi Manuel ");
});
with lambda
Alright, I have a simple java applet with two buttons and a screen. Both the buttons do the same thing. I want to change this. I can't find what it is that changes the action that is performed when either one of the buttons is pressed. They both to the same thing and I don't want this. So my question is how would I change the Inventory button to display "Hello world" instead of a line count?
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class projectApplet extends JApplet implements ActionListener
{
/**
*
*/
private static final long serialVersionUID = 1L;
private JTextArea textArea;
private int lineNumber = 0; // this is just to test
public void init() {
JPanel panel = new JPanel();
textArea = new JTextArea();
textArea.setBackground(Color.BLACK);
textArea.setForeground(Color.WHITE);
JScrollPane sp = new JScrollPane(textArea);
panel.add(sp);
Container window = getContentPane();
window.setLayout(new BorderLayout());
window.add(sp,BorderLayout.CENTER);
// this is just to test------------------
JButton b = new JButton("Clik to add a line");
b.addActionListener(this);
window.add(b, BorderLayout.SOUTH);
JButton inventory = new JButton("Inventory");
inventory.addActionListener(this);
window.add(inventory, BorderLayout.NORTH);
//---------------------------------------
}
public void actionPerformed(ActionEvent arg0) {
lineNumber++;
textArea.append("\nLine number: " + lineNumber);
}
public void actionPerformed1(ActionEvent arg0) {
lineNumber++;
textArea.append("RPFL");
}
}
Add a new action listener to it. Typically you can use an anonymous inner class:
inventory.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
textArea.append("Hello, world");
}
});
Just have the one actionPerformed method and then find out which button triggered it.
For example:
public void actionPerformed(ActionEvent arg0) {
if(arg0.getLabel()=="Inventory") // Do the following
if(arg0.getLabel()=="Click to add a new line") // Do the following
}
Note, getLabel() method is deprecated so you'll have to use another... can't remember off the top of my head which you should though... maybe getName(). But this is a simple way to test which button was clicked ;)
You can't do arg0.getSOurce() inside the action performed method to checkout which button has generated this event.