I'm going to try GUI programming in Java, but it's going to be messy.

Asked 2 years ago, Updated 2 years ago, 36 views

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class index extends JFrame{
    private JLabel result;

    ButtonTest() {
        setTitle("Button Test");

        JLabel lab = new JLabel("Click one of the buttons.");
        getContentPane().add(lab, "North");

        result = new JLabel(" ");
        getContentPane().add(result, "South");

        JButton yes = new JButton("Yes");
        getContentPane().add(yes, "West");
        yes.addActionListener(new YesHandler());

        JButton no = new JButton("No");
        getContentPane().add(no, "East");
        no.addActionListener(new NoHandler());;
    }
    class YesHandler implements ActionListener {
        public void actionPerformed(ActionEvent evt) {
            result.setText("you pressed the yes button");
        }
    }
    class NoHandler implements ActionListener {
        public void actionPerformed(ActionEvent evt) {
            result.setText("you pressed the no button");
        }
    }
    public static void main(String [] args) {
        JFrame jf = new ButtonTest();
        jf.setSize(250, 150);
        jf.setVisible(true);
    }
}

I wrote this code

A red line is drawn at ButtonTest(). Of course it doesn't work. Why is it like this?

I followed the example.

java

2022-09-22 15:00

1 Answers

ButtonTest was used as a constructor, but it is an error caused by a different class name.

The class name of the code you uploaded is index. Switch to ButtonTest.

You can recheck the basic grammar of Java.


2022-09-22 15:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.