-3

嘿伙计们,我正在编写一个用于练习的 java 程序。它涉及一个 JFrame、JButton 和动作侦听器。当我尝试运行程序(通过 Eclipse)时,控制台显示“Window(5) [Java Application]”[...]

有谁知道修复?这是我的代码:

窗口.java

package com.github.dtroll.Carzett.main;

import java.awt.Color;

import javax.swing.JFrame;

public class Window {
public static void startGame() {
    JFrame f = new JFrame("Journey To Carzett");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setResizable(true);
    f.setBackground(Color.GRAY);
    f.setVisible(true);
    f.setSize(750, 500);
    //JPanel p = new JPanel(new BorderLayout());
}
public static void main(String args[]) {

    new Window();
           new StartPanel();
}


}

StartPanel.java (用于在按下按钮时向程序添加面板。)

package com.github.dtroll.Carzett.main;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;
public class StartPanel extends JPanel implements ActionListener{


/**
 * 
 */
private static final long serialVersionUID = 1L;
private JButton start;

public StartPanel(){
    Icon startButton = new ImageIcon("/images/buttons/start.png");
    this.start = new JButton(startButton);
    this.start.addActionListener(this);
    this.add(start);
}

@Override
public void actionPerformed(ActionEvent e) {
    if(e.getSource() == start){
        //insert methods here
    }


}
}
4

2 回答 2

4

看起来您并没有真正连接 JPanel 和 JFrame。基本上,您需要将 JPanel 添加到 JFrame,然后“打包”JFrame 并将其设置为可见。尝试这个:

public static void main(String args[]) {

    Window frame = new Window();
    frame.startGame(new StartPanel());

}

您的窗口代码应如下所示:

public static void startGame(JPanel panel) {
    JFrame f = new JFrame("Journey To Carzett");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setResizable(true);
    f.setBackground(Color.GRAY);
    f.setVisible(true);
    f.setSize(750, 500);
    f.getContentPane(panel);
    f.pack();
    f.setVisible(true);
}
于 2013-02-08T20:06:24.230 回答
0

你在哪里调用startgame(). 如果您不调用它,则不会出现框架。要查看框架,只需在 main 中添加:

startGame()
于 2013-02-08T20:00:28.903 回答