【问题标题】:Need to add a "public static void main(String[] args)",需要添加一个“public static void main(String[] args)”,
【发布时间】:2016-02-07 11:21:37
【问题描述】:

我正在尝试在 Eclipse 中编写代码,以在单击时更改 MyButton 上的颜色和文本。

编辑:得到一些帮助,问题错误得到解决。我现在知道代码需要“public static void main(String[] args)”应该放在哪里?

在我尝试运行此代码后,我收到错误“无法启动选择,并且最近没有启动”。 但是,我用谷歌搜索了一下,发现这个错误可能是 eclipse 中的一个常见问题。我是,虽然是 Java 新手,但我认为如果我的代码有问题而不是 Eclipse 讨厌我会更合乎逻辑。

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

    public class Makke extends JFrame implements ActionListener{


        private JButton MyButton;

        public Makke(){
            setLayout(null);
            setSize(300, 250);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            MyButton = new JButton("Tryck För Blå!");
            MyButton.setBackground(Color.YELLOW);
            MyButton.setBounds(100, 190, 60, 30);
            MyButton.addActionListener(this);
            add (MyButton);
        }

        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == MyButton) {
                MyButton = new JButton("Tryck För Gul!");
                MyButton.setBackground(Color.BLUE);

            }

        }
        }

翻译: 代码中有一些瑞典语 "Tryck för blå" = "Click to get blue", "Tryck för gul" = "Click to get yellow" ^^

【问题讨论】:

  • 我不知道人们还在使用 Swing...如果你有选择,你应该看看 JavaFX。
  • @Satya 我收到错误消息“无法启动选择,并且最近没有启动”
  • @Joffrey 啊,有作业,所以我必须使用 swing。但我会在以后的编码中记住这一点:)
  • @Satya 实际上这对我有帮助,谢谢。 Eclipse 告诉我我需要插入“public static void main(String[] args)”。知道哪里需要这个吗?

标签: java error-handling jbutton


【解决方案1】:

1.您应该将setVisible( boolean b) 设置为true

它根据参数b 的值显示或隐藏此窗口。

setVisible(true);

添加这一行应该在Makke类的构造函数中。

Read setVisible(boolean) doc


2.你的actionPerformed(.)方法

if (e.getSource() == MyButton) {
   //MyButton = new JButton("Tryck För Gul!"); remove this line
  //otherwise every time new button object will be created.
    MyButton.setText("Tryck För Gul!");//to change the button text
    MyButton.setBackground(Color.BLUE);
}

3.需要 main 方法来运行您的应用程序。在 Makke 类的创建对象中创建一个包含 main(-) 的类来运行您的应用程序。

public class Main {
public static void main(String []args)throws Exception {

        new Makke();//now your window will be appeared.
}
}

Read - Why main(-) method needed

【讨论】:

  • 谢谢!这对我帮助很大!你太棒了:)
  • 是的!我的错,我是这个地方的新手
【解决方案2】:

您每次点击它时都会创建一个新按钮,但不会向该新对象添加点击侦听器... 我的建议是这样做(或者如果你转向 javaFX 可能会更好)

JButton myButton = new JButton("Text Button");
myButton.addActionListener(new ActionListener()
{
  public void actionPerformed(ActionEvent e)
  {
      myButton.setText("Tryck För Gul!");
      myButton.setBackground(Color.BLUE);
  }
}

【讨论】:

  • 啊,我明白了,你是对的。没想到。需要使用 Swing.* 来完成我的作业,但我会解决这个问题 :) 谢谢
猜你喜欢
  • 2016-05-22
  • 2012-08-10
  • 1970-01-01
  • 2018-11-12
  • 2019-03-19
  • 2019-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多