0

好的,我可以显示文本字段和普通文本甚至图像,但我无法显示按钮。我不确定我做错了什么,因为我对其余部分做了相同的步骤。任何帮助都会非常感谢!

package EventHandling2;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

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

import EventHandling.GUITest;

public class EventMain extends JFrame{

    private JLabel label;
    private JButton button;

    public static void main(String[] args) {
        EventMain gui = new EventMain ();
        gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // when click x close program
        //gui.setSize(600, 300);
        gui.setVisible(true);
        gui.setTitle("Button Test");
    }

    public void EventMain(){
        setLayout(new FlowLayout());

        button = new JButton ("click for text");
        add(button);

        label = new JLabel ("");
        add(label);

        Events e = new Events();
        button.addActionListener(e);
    }

    public class Events implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            label.setText("Now you can see words");
        }
    }
}
4

3 回答 3

4

问题出在方法上: void EventMain()

构造函数没有返回类型。只需删除“无效”。该代码将正常工作。

于 2013-06-09T04:19:31.120 回答
0

您的 actionListener(e) 包含一个小的控制结构错误:

public void actionPerformed(ActionEvent e) {
        label.setText("Now you can see words");
}

改成:

public void actionPerformed(ActionEvent e) {
        if (e.getSource() == button) {
           label.setText("Now you can see words");
        }
}
于 2013-06-09T04:17:11.093 回答
0

首先,您必须删除构造函数中的void关键字。EventMain然后,创建JPanel组件并将其添加到其中,然后JPanelJFrame.contentPane.

以下代码应该可以工作:

public class EventMain extends JFrame {

    private final JLabel label;
    private final JButton button;

    public static void main(String[] args) {
        EventMain gui = new EventMain();
        gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // when click x
                                                            // close program
        gui.setSize(600, 300);
        gui.setTitle("Button Test");
        gui.setVisible(true);

    }

    public EventMain() {
        // setLayout(new FlowLayout());
        JPanel panel = new JPanel(new FlowLayout());
        button = new JButton("click for text");
        panel.add(button);

        label = new JLabel("");
        panel.add(label);

        Events e = new Events();
        button.addActionListener(e);

        this.getContentPane().add(panel);
    }

    public class Events implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            label.setText("Now you can see words");
        }
    }
}
于 2013-06-09T07:06:47.963 回答