调用创建JButton的代码时出错(不可见)

时间:2018-12-01 04:59:29

标签: java swing jframe jbutton

我创建了一个子手游戏,并想在其周围添加一个JFrame。我从制作主屏幕开始,但是在开始JButton时遇到问题。由于某种原因,它根本没有出现,我尝试了多种解决方案。

import java.util.*;
import javax.swing.*;

public class mainScreen extends JFrame {
      JPanel mainPanel = new JPanel();
      JButton startButton = new JButton("Start");


  public mainScreen() {
   JFrame mainFrame = new JFrame("Main Screen");
  mainFrame.add(new JLabel(new ImageIcon("C:/Users/Owner/Desktop/Java Projects/hangman_image.jpg")));
   mainFrame.setSize(1920, 1080);
   mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE );
   mainPanel = new JPanel();
   startButton = new JButton("Start");
   mainPanel.add(startButton);

   mainFrame.setVisible(true);
   }
} 

显示框架,但不显示按钮本身(我尝试摆脱图像以查看其是否被覆盖)。

2 个答案:

答案 0 :(得分:0)

主要问题是mainPanel没有添加到可见容器中。请参阅代码注释中的其他提示。

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

// no need to extend JFrame ..
//public class mainScreen extends JFrame {
public class mainScreen {

    // this is never addded to a visible container so .. (1)
    JPanel mainPanel = new JPanel();
    JButton startButton = new JButton("Start");

    public mainScreen() {
        JFrame mainFrame = new JFrame("Main Screen");
        mainFrame.add(new JLabel("C:/../hangman_image.jpg"));
        // (1) .. add it!
        mainFrame.add(mainPanel, BorderLayout.PAGE_START);
        // don't guess.. 
        //mainFrame.setSize(1920, 1080);
        // .. instead
        mainFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
        mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        // it is already instantiated, no need to do it twice! 
        //mainPanel = new JPanel();
        startButton = new JButton("Start");
        mainPanel.add(startButton);

        mainFrame.setVisible(true);
    }

    public static void main(String[] args) {
        Runnable r = () -> {
            mainScreen ms = new mainScreen();
        };
        SwingUtilities.invokeLater(r);
    }
}

答案 1 :(得分:0)

您已经创建了面板,但是即使已在面板中添加了按钮,也没有将其添加到大型机中。

import javax.swing.*;

class Test1 extends JFrame {
JPanel mainPanel = new JPanel();
JButton startButton = new JButton("Start");


public Test1() {
    JFrame mainFrame = new JFrame("Main Screen");
    mainFrame.add(new JLabel(new ImageIcon("/filelocation")));
    mainFrame.setSize(1920, 1080);
    mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE );
    mainPanel = new JPanel();
    startButton = new JButton("Start");
    mainPanel.add(startButton);
    //here you add your panel to mainFrame
    mainFrame.add(mainPanel);
    mainFrame.setVisible(true);
}

}


public class Test{
public static void main(String args[]) {
    new Test1();
}
} 

希望这会有所帮助。