java - 卡片布局 - java GUI
问题描述
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);
}
}
}
我应该怎么做才能使面板标题显示我绘制的矩形,因为它没有显示我到目前为止的代码。
解决方案
初始化局部变量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);
}
}
}
推荐阅读
- django-viewflow - 学习 Viewflow 和文档
- css - React Basic Application 在本地工作,但在 Azure 中它不加载 .CSS、.Ico、.JSON
- c# - ASP.NET Core web service does not load appsettings.json into configuration
- css - 应该如何将 Bulma 文件夹集成和构建到现有的 Web 项目文件夹中?
- jms - SimpleMessageListenerContainer 无法在 ems 代理故障转移时重新连接
- google-app-engine - 如何让应用引擎避免冷启动?
- c - 我将如何解析 c 中的字符串并忽略该字符串中的某个单词?
- google-maps - 如何在 KML 文件中显示自定义扩展数据?
- swift - Kotlin 等价于 Swift 期望/承诺
- excel - 从索引数组和匹配数组计算数组