Java JFrame actionPerformed - java

I'm not used to Java and JFrame as I'm just starting to learn.
My question is that, I have error at the method actionPerformed. The error given is at the e.getsource == b I believe.
From what I understand, the button I created at the public static void main(String[] args) doesn't passed the value of the button to the actionPerformed.
I'm sorry if my question is not clear.
Here is my code
public static void main(String[] args){
JButton b = new JButton("Click here");
JFrame newWindow = new JFrame("Test");
newWindow.setVisible(true);
newWindow.setSize(250,250);
newWindow.setLayout(null);
newWindow.add(b);
b.addActionListener(this);
}
Here is another part of my code
public void actionPerformed(ActionEvent e)
{
if ( e.getSource() == b )
{
//do something
}
}

From what I understand, the button I created at the public static void
main(String[] args) doesn't passed the value of the button to the
actionPerformed.
Yes, you are right. The JButton object b is not visible at actionPerformed method. You need declare b globally.
class MyClass extends JFrame implements ActionListener{
// Declare here to make visible to actionPerformed
JButton b = new JButton("Click here");
MyClass(){
super("Test");
b.addActionListener(this);
add(b);
setVisible(true);
setSize(250,250);
}
public void actionPerformed(ActionEvent e){
if ( e.getSource() == b ){
//do something
}
}
public static void main(String[] args){
new MyClass();
}
}

It is e.getSource(). It is a method and all methods end in parentheses ().
Also, b is not visible in actionperformed(). Make it a global variable i.e. define it outside of main() and make it static so as to be able to access it in main()
Plus, as Masud asked, did your class implement the ActionListener interface ?

Related

reusing action listener and jframe in main class

So if someone would take a look at the code below and give me hand I would owe you my life. So here's the issue, obviously I can get this to work if I were to put playerCreationSelectionin its own class, my questions is getting it to work, inside class superClass I cannot for the life of me move things around to make it work. Any help would be great, thanks everyone!
forgot to actually put what goes wrong! So what will happen is it says playerCreationSelection is not a symbol
public class superClass
{
public static void main(String[] args)
{
playerCreationSeletion gui = new playerCreationSeletion();
}
public class playerCreateSelection extends JFrame implements ActionListener
{
//create label
public JLabel playerCreatedLabel;
public void playerCreationSeletion()
{
setSize(WIDTH,HEIGHT);
WindowDestroyer listener = new WindowDestroyer();
addWindowListener(listener);
Container contentPane = getContentPane();
contentPane.setBackground(Color.DARK_GRAY);
contentPane.setLayout(new FlowLayout());
//create button
JButton playerCreationButton = new JButton("Create New Player");
playerCreationButton.addActionListener(this);
contentPane.add(playerCreationButton);
//create label
playerCreatedLabel = new JLabel("Welcome New Player!");
playerCreatedLabel.setVisible(false);
}
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand();
Container contentPane = getContentPane();
if(actionCommand.equals("Create New Player"))
{
contentPane.setBackground(Color.LIGHT_GRAY);
playerCreatedLabel.setVisible(true);
}
}
}
}
Well, you have a typo "playerCreationSeletion()". Also, You need to call an inner class constructor like this and use setVisible and setSize.
public static void main(String[] args) {
playerCreateSelection gui = new superClass().new playerCreateSelection();
gui.setSize(500, 500);
gui.setVisible(true);
}
Try that.

What parameters are used when .addActionListener() is called?

I've been learning quite a lot in Java recently but something has been really bugging me. I learned / was taught how to use ActionListeners when the program involves a constuctor, for example,
public class test extends JFrame implements ActionListener {
JButton button;
public test
{
setLayout(null);
setSize(1920,1080);
setTitle("test");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button = new JButton("");
button.setBounds(x,x,x,x);
button.AddActionListener(this); //What can replace the this parameter here.
button.setVisible(true);
add(button);
}
public static void main(String[] args) {
test testprogram = new test();
test.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent clickevent) {
if (clickevent.GetSource() == button) {
//DoSomething
}
}
It can be anything which implements ActionListener.
You might want to consider not making your JFrame implement ActionListener: this means that
It is part of the class' interface that it implements actionPerformed; but you probably don't want other classes to call that directly.
You can only implement it "once", so you end up having to have conditional logic to determine what the source of the event was, and then handle it appropriately.
The alternative is to create a button-specific action listener:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent clickevent) {
// Don't need to check if it is from button, nothing else
// could have created the event.
}
});
and remove implements ActionListener from the test class.
It is instance of class which is going to handle ActionEvent.
From the Documents
Register an instance of the event handler class as a listener on one
or more components. For example:
someComponent.addActionListener(instanceOfMyClass);

How to refresh instance of class if some action in another class was done

I have class DnyMesice what creates many instances of JButton. Every instance contains variable poznamkaDne. This class DnyMesice contains actionListener to find poznamkaDne value of pushed JButton.
I have class Gui what creates one instance of mentioned class DnyMesice and one instance of JTextArea.
How can I refresh value of JTextArea (names poznamkovePole) if some JButton (in class DnyMesice) is pushed?
public class DnyMesice extends JPanel {
public String poznamkaDne="first note";
jButton tlacitkoDen;
public void zobrazMesic(Calendar kalendar){
for (c=1; c<30; c++){
tlacitkoDen = new JButton(Integer.toString(denvMesici));
tlacitkoDen.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt) {
poznamkaDne="New note";
};
});
add(tlacitkoDen);
}
}
}
public class Gui extends JFrame {
...
public void zobrazKalendar(){
...
panel3 = new JPanel();
panel3.setLayout(new FlowLayout());
add(panel3);
JTextArea poznamkovePole;
poznamkovePole = new JTextArea();
poznamkovePole.setColumns(30);
poznamkovePole.setRows(5);
poznamkovePole.setText(panel2.poznamkaDne);
panel3.add(poznamkovePole);
}
Now the program shows in JTextArea only "first note" (which is defined during creating of instance JButton) but hot to refresh it after ActionListener action?
Maybe better if you will use:
Add to DnyMesice JTextArea link and in ActionListener change text.
public class DnyMesice extends JPanel {
private JTextArea poznamkaDne;
jButton tlacitkoDen;
public DnyMesice (JTextArea jTextArea){
this.poznamkaDne = jTextArea;
}
public void zobrazMesic(Calendar kalendar){
for (c=1; c<30; c++){
tlacitkoDen = new JButton(Integer.toString(denvMesici));
tlacitkoDen.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt) {
poznamkaDne.setText("New note");
};
});
add(tlacitkoDen);
}
}
}
P.S. - And please don't forget to use Code Conventions for the Java
Modify as follows:
// add these methods
public void setPoznamkaDne(String s) {
poznamkaDne = s;
}
public String getPoznamkaDne() {
return poznamkaDne;
}
// CHANGE this method (KEEP the rest of the code!)
public void actionPerformed(ActionEvent evt) {
setPoznamkaDne("New note");
};
poznamkovePole.setText(panel2.getPoznamkaDne());
These changes should allow you to update the text. BUT you need to either call poznamekovePole.setText() somehow, or implement an advanced listener class. I recommend combining your class like #Too Strong Magic said, above.

Swing actionPerformed method

I am testing an application that directly implements ActionListener
The below application can be compiled and run:
public class App implements ActionListener {
JButton button;
int count = 0;
public static void main (String[] args)
{
App gui = new App();
gui.go();
}
public void go()
{
button = new JButton("Click me!");
JFrame frame = new JFrame();
frame.getContentPane().add(button);
frame.setSize(500,500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event)
{
count++;
button.setText("I've been clicked "+count+" times");
}
});
}
}
But Eclipse wants the
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
method in App class as well. is this because the "go" method may sometimes not be called making actionPerformed not called and then against how implementing works?
Thanks in advance for any assistance.
This is simply because of the java rule for implementing an interface. ActionListener interface has actionPerformed method in it. So any class implementing this interface need to provide the implementation for actionPerformed.
Read more about using ActionListener here: http://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html

java thread problem

I wrote a simple program with java swing which suppose to start another thread and in that thread a JForm will show up when I click a button. But JForm is not showing up... I used if (Thread.currentThread().getName() == "Thread1") to do the specific task for that thread, when I comment that program runs perfectly, I can't understand why it is not going to the if block... Please someone help me with this...
Thanks in advance!
Here is the code,
public class Test extends JFrame implements ActionListener {
JPanel panel;
JButton button;
public Test() {
setVisible(true);
setSize(300, 300);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
panel = new JPanel();
button = new JButton("click me");
button.addActionListener(this);
panel.add(button);
add(panel, BorderLayout.CENTER);
}
public static void main(String[] args) {
Test tst=new Test();
}
#Override
public void actionPerformed(ActionEvent arg0) {
if(arg0.getSource()==button){
System.out.println("test");
test2 test = new test2();
Thread tr1 = new Thread(test);
tr1.setName("Thread1");
tr1.start();
}
}
}
class test2 implements Runnable{
public void run() {
//if (Thread.currentThread().getName() == "Thread1") {
System.out.println("inside thread");
JFrame frame2=new JFrame();
frame2.setVisible(true);
frame2.setSize(300, 300);
frame2.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
//}
}
}
Try using getName().equals("Thread1") instead.
equals compares the strings, == checks if the two strings are the same object.
Try:
if (Thread.currentThread().getName().equals("Thread1"))
or
if (Thread.currentThread().getName().compareTo("Thread1") > 0)
why do you have that check for the current threads name anyway? That thread will be the only one to call that method anyway.
You must not compare String values using == as it checks for object identity. You should use Thread.currentThread().getName().equals("Thread1") instead.
You should not interact with any Swing/AWT components outside of the Event Dispatch Thread!

Categories