gpt4 book ai didi

java - Swing 组件不显示

转载 作者:行者123 更新时间:2023-11-30 06:24:15 24 4
gpt4 key购买 nike

这是我的代码,当我执行时,我得到的只是一个空白窗口。首先,当我尝试执行 main.setContentPane() 时,我收到此错误:

"Cannot make a static reference to the non-static field panel"

所以我把它放在构造函数中,但什么也没有显示。

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

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

public class MainFrame extends JFrame{
private JPanel panel;
private JButton performance;
private JButton concordance;
private JButton discordance;
private JButton resultat;

public void MainFrame() {
panel = new JPanel(new GridLayout(4, 1, 10, 10));
performance = new JButton("performance");
concordance = new JButton("concordance");
discordance = new JButton("discordance");
resultat = new JButton("resultat");

performance.setSize(50, 30);
concordance.setSize(50, 30);
discordance.setSize(50, 30);
resultat.setSize(50, 30);

panel.add(performance);
panel.add(concordance);
panel.add(discordance);
panel.add(resultat);
getContentPane().add(panel);

}
public static void main(String[] args) {
MainFrame main = new MainFrame();
main.setSize(300, 200);
main.setDefaultCloseOperation(EXIT_ON_CLOSE);
main.setVisible(true);
}
}

最佳答案

您有一个名为 MainFrame 的方法(返回 void),该方法从未被调用。

您应该将其作为构造函数,或者创建一个调用该方法的构造函数,如下所示:

public class MainFrame extends JFrame {
private JPanel panel;
private JButton performance;
private JButton concordance;
private JButton discordance;
private JButton resultat;

public MainFrame() {
super();
MainFrame();
}

public void MainFrame() {
panel = new JPanel(new GridLayout(4, 1, 10, 10));
performance = new JButton("performance");
concordance = new JButton("concordance");
discordance = new JButton("discordance");
resultat = new JButton("resultat");

performance.setSize(50, 30);
concordance.setSize(50, 30);
discordance.setSize(50, 30);
resultat.setSize(50, 30);

panel.add(performance);
panel.add(concordance);
panel.add(discordance);
panel.add(resultat);
this.getContentPane().add(panel);

}

public static void main(String[] args) {
MainFrame main = new MainFrame();
main.setSize(300, 200);
main.setDefaultCloseOperation(EXIT_ON_CLOSE);
main.setVisible(true);
main.MainFrame();
}
}

关于java - Swing 组件不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47520014/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com