Java中的CardLayout()如何工作?我使用互联网,似乎无法让CardLayout工作。这是我到目前为止的代码,它不起作用:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class GameManager
{
JFrame frame;
JPanel cards,title;
public GameManager()
{
cards = new JPanel(new CardLayout());
title = new JPanel();
cards.add(title,"title");
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, "title");
}
public static void main(String [] args)
{
GameManager gm = new GameManager();
gm.run();
}
public void run()
{
frame = new JFrame("Greek Olympics");
frame.setSize(1000,1000);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(cards);
frame.setVisible(true);
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, "title");
}
public class title extends JPanel
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.fillRect(100,100,100,100);
}
}
}
我该怎么做才能让面板标题显示我画的矩形,因为它没有显示我目前的代码。
答案 0 :(得分:2)
初始化局部变量title
时,您正在创建JPanel
的实例,而不是您定义的title
类。
为了清楚起见,并且为了遵守Java命名约定,您应该将类名称(Title
)大写。然后,您需要将title
变量的类型更改为Title
。
这是更新后的代码,其中我更改了高位。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class GameManager {
JFrame frame;
JPanel cards; // <-----
Title title; // <-----
public GameManager(){
cards = new JPanel(new CardLayout());
title = new Title(); // <-----
cards.add(title,"title");
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, "title");
}
public static void main(String [] args){
GameManager gm = new GameManager();
gm.run();
}
public void run(){
frame = new JFrame("Greek Olympics");
frame.setSize(1000,1000);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(cards);
frame.setVisible(true);
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, "title");
}
public class Title extends JPanel { // <-----
public void paintComponent(Graphics g){
super.paintComponent(g);
g.fillRect(100,100,100,100);
}
}
}