简体   繁体   中英

How would i make a button in Java onto a JFrame

I am coding on Android and using terminal IDE to compile my code. However, for some reason when I compile, it says the Button code is wrong.

package BlahBlahBlah;

import javax.swing.JButton;
import javax.swing.JFrame;

public class blahblahblah extends JFrame{
    JFrame w = new JFrame();
    w.setVisible(true);
    w.setSize(1366, 768);

    Button sb = new JButton();
    sb.addListener(this);
    add(sb);
}

It keeps saying illegal start of type or identifier expected which as you see there's a identifier in the Button .

Button sb = new JButton();

A "Button" without the "J" is not the same as a "JButton".

In Swing components start with a "J".

You should put your code inside a method.

public class blahblahblah extends JFrame{
    public static void main(String[] args) {
        JFrame w = new JFrame();
        w.setVisible(true);
        w.setSize(1366, 768);

        Button sb = new JButton();
        sb.addListener(this);
        add(sb);
    }
}

You can either remove sb.addListener(this); or implement our class with ActionListener and add it's umimplemented methods to your class. Also, do some changes like:

import java.awt.Button;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;

public class blahblahblah extends JFrame implements ActionListener 
{
    public blahblahblah() 
    {
        JFrame w = new JFrame();
        w.setVisible(true);
        w.setSize(1366, 768);

        JButton sb = new JButton();
        sb.addActionListener(this);
        add(sb);
    }

    public static void main(String[] args) {
        blahblahblah b = new blahblahblah();
    }

    @Override
    public void actionPerformed(ActionEvent e) {

        // TODO Your Stuff

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM