0
無論我做什麼,我都無法讓JFrame顯示任何內容。它只是空白。我將按鈕starter和tutorialer添加到JPanel遊戲中,並將JPanel添加到我設置爲cardLayout的JPanel卡中。爲什麼我的代碼不適用於CardLayout?無論我做什麼,它只顯示一個空白的JFrame
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");
}
}
這'cl.show(卡,「遊戲」);'是'paintComponent'方法中的一個壞主意,你應該永遠不要修改任何paint方法中的任何組件的狀態 – MadProgrammer
謝謝!,這似乎工作!但是爲什麼Null Layout不起作用。我用.setBounds對不對? – SocketPhys
佈局管理器不僅僅是佈局組件,他們向父容器提供關於容器本身需要的空間量的信息(基於它的內容) – MadProgrammer