我已经让GUI在我的电脑上运行过,但是这个程序我想尝试实现GridBag,所以我可以做一个简单的游戏。我不知道为什么它没有运行。这是代码:图形用户界面没有显示在我的屏幕上
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class GridBagTest extends JFrame{
public static void main(String[] args){
new GridBagTest();
}
public void GridBagTest(){
JButton atk, mag, fort, pot1, pot2, flee;
JPanel gamePanel = new JPanel();
gamePanel.setLayout(new GridBagLayout());
JFrame gameFrame = new JFrame("FightQuest");
gameFrame.getContentPane().add(gamePanel);
gameFrame.setSize(800, 600);
gameFrame.pack();
gameFrame.setVisible(true);
atk = new JButton("Strike");
mag = new JButton("Magic");
fort = new JButton("Fortify");
pot1 = new JButton("Potion 1");
pot2 = new JButton("Potion 2");
flee = new JButton("Flee");
addItem(gamePanel, atk, 0, 0, 1, 1, GridBagConstraints.SOUTHEAST);
addItem(gamePanel, mag, 1, 0, 1, 1, GridBagConstraints.SOUTH);
addItem(gamePanel, fort, 2, 0, 1, 1, GridBagConstraints.SOUTHWEST);
addItem(gamePanel, pot1, 0, 1, 1, 1, GridBagConstraints.NORTHEAST);
addItem(gamePanel, pot2, 1, 1, 1, 1, GridBagConstraints.NORTH);
addItem(gamePanel, flee, 2, 1, 1, 1, GridBagConstraints.NORTHWEST);
}
private void addItem(JPanel p, JComponent c, int x, int y, int width, int height, int align){
GridBagConstraints gc = new GridBagConstraints();
gc.gridx = x;
gc.gridy = y;
gc.gridwidth = width;
gc.gridheight = height;
gc.weightx = 100.0;
gc.weighty = 100.0;
gc.insets = new Insets(0, 0, 0, 0);
gc.anchor = align;
gc.fill = GridBagConstraints.NONE;
p.add(c, gc);
}
}
我不知道这有什么差别,但我得到了大多数代码从Java参考书的Java 6即使我正在运行的Java 7,因为这是所有我的学校了。我也在XFCE操作系统上执行我所有的代码。
1)为了更好地帮助更快,发布[SSCCE](http://sscce.org/)。 2)请参阅[使用多个JFrames,好/坏实践?](http://stackoverflow.com/a/9554657/418556) –
我不知道如何使这个更短,从代码中删除的东西doesn'使GUI出现。我需要其他人告诉我如何缩短或延长代码。 – JavaNoob
非常恭喜,你完全掌握了四个制作SSCCE的东西中的一个。现在看看***另一个3. *** –