一切都有效,除了按钮。 GUI Java

时间:2013-06-09 04:01:34

标签: java swing button layout

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

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");
        }
    }
}

3 个答案:

答案 0 :(得分:4)

问题在于方法:void EventMain()

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

答案 1 :(得分: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");
        }
}

答案 2 :(得分:0)

首先,您必须删除void构造函数中的EventMain关键字。然后,创建JPanel并在其中添加组件,然后将JPanel添加到JFrame.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");
        }
    }
}