我正在尝试使用分层窗格为我正在处理的程序创建一个菜单,但该按钮不会显示。我似乎无法弄清楚它是什么......
public class FlashcardGUI {
public static void main(String[] args)
{
JFrame projectFrame = new JFrame("StudyFast Flashcard");
projectFrame.setName("StudyFast Flashcards");
projectFrame.setSize(1000,600);
projectFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
projectFrame.setVisible(true);
JLayeredPane projectLayeredPane = new JLayeredPane();
projectFrame.setContentPane(projectLayeredPane);
JPanel projectMenu1 = new JPanel();
projectLayeredPane.setLayer(projectMenu1, 0);
final JButton startNow = new JButton();
startNow.setText("Exit");
startNow.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
projectFrame.add(projectLayeredPane);
projectLayeredPane.add(projectMenu1);
projectMenu1.add(startNow);
}
}
答案 0 :(得分:2)
将这两行放在main方法的末尾。为了使按钮显示,顺序很重要。
projectFrame.pack();
projectFrame.setVisible(true);
(确保删除第9行已有的projectFrame.setVisible(true);
。)
答案 1 :(得分:2)
我已更新您的代码,现在正在运行。请在代码中查看问题的内联注释。希望这会有所帮助。
public class FlashcardGUI2 {
public static void main(String[] args) {
JFrame projectFrame = new JFrame("StudyFast Flashcard");
projectFrame.setName("StudyFast Flashcards");
projectFrame.setSize(1000,600);
projectFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
projectFrame.setVisible(true);
JLayeredPane projectLayeredPane = new JLayeredPane();
LayoutManager layout = new FlowLayout(); //creating a FlowLayout object
projectLayeredPane.setLayout(layout); //adding the layout to JLayeredPane
//because JLayeredPane do not have default layout of
//its own. The reason you were not
//getting the button displayed
projectLayeredPane.setPreferredSize(new Dimension(300, 310));
JPanel projectMenu1 = new JPanel();
final JButton startNow = new JButton();
startNow.setText("Exit");
startNow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
projectLayeredPane.add(projectMenu1,new Integer(50));
projectLayeredPane.add(startNow,new Integer(10));
projectFrame.add(projectLayeredPane);
projectFrame.pack();
}
}