无论我做什么,我都无法让JFrame显示任何内容。它只是空白。我将按钮starter和tutorialer添加到JPanel游戏中,并将JPanel添加到我设置为cardLayout的JPanel卡中。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class layouter extends JFrame {
public static void main (String[]args){
layouter x = new layouter();
}
public layouter(){
setSize(600,600);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
Pan p = new Pan();
setContentPane(p);
setVisible(true);
}
}
class Pan extends JPanel{
JButton starter;
JButton tutorialer;
JPanel start;
JPanel tutorial;
JPanel game;
JPanel cards;
CardLayout cl;
Pan(){
starter = new JButton("start");
tutorialer = new JButton("tutorial");
start = new JPanel();
tutorial = new JPanel();
game = new JPanel();
cards = new JPanel( new CardLayout());
cl= (CardLayout)(cards.getLayout());
game.setLayout(null);
starter.setBounds(150,150,100,50);
tutorialer.setBounds(150,200,100,50);
game.add(starter);
game.add(tutorialer);
cards.add(game,"game");
add(cards);
repaint();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
cl.show(cards,"game");
System.out.println("hello");
}
}
答案 0 :(得分:2)
game.setLayout(null);
< - 这将导致您的问题,因为您添加到此容器的任何内容都将不再自动布局。默认情况下,组件的大小和位置为0x0
使用适当的布局管理器。有关详细信息,请参阅Laying Out Components Within a Container。
如果您向games
添加更多容器,则可能需要“显示”您希望首先显示的默认视图
cl.show(cards, "game");