gpt4 book ai didi

java - repaint() 方法不绘制新帧

转载 作者:行者123 更新时间:2023-12-01 17:57:17 25 4
gpt4 key购买 nike

我看了很多答案,但仍然找不到解决方案。我有一个 JFrame 和两个 JPanel。我想在按下按钮时删除第一个面板并将其替换为第二个面板,但 repaint() 方法不会刷新框架。请帮忙。

这是我的框架代码:

import javax.swing.*;
import java.awt.*;
import static javax.swing.JFrame.EXIT_ON_CLOSE;

public class MainFrame
{
static JFrame mainFrame;

int height = 650;
int width = 1042;

public MainFrame()
{
mainFrame = new JFrame();
mainFrame.setBounds(0, 0, width, height);
mainFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
mainFrame.setResizable(false);
}

public static void main(String[] args)
{
new MainMenu();
mainFrame.setVisible(true);
}
}

这是我的 MainMenu 面板的代码

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import static java.awt.Color.CYAN;
import static java.awt.Color.red;

public class MainMenu extends MainFrame
{
public MainMenu()
{
components();
}

//variable decleration
JPanel menuPanel;
JLabel title;
JButton periodicTable;

private void components()
{
int buttonW = 500;
int buttonH = 50;

//creating panel
menuPanel = new JPanel();
menuPanel.setLayout(null);
menuPanel.setBackground(CYAN);

//creating title label
title = new JLabel("Application Title", SwingConstants.CENTER);
title.setFont(new Font("Calibri Body", 0, 50));
title.setBounds(width / 3 - buttonW / 2, 50, buttonW, buttonH + 10);

//creating periodic table button
periodicTable = new JButton();
periodicTable.setText("Periodic Table");
periodicTable.setBounds(width / 3 - buttonW / 2, 50 + buttonH + 60, buttonW, buttonH);
periodicTable.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
periodicTableActionPerformed(event);
}
});

//adding components to panel
menuPanel.add(title);
menuPanel.add(periodicTable);

//adding panel to MainFrame
mainFrame.add(menuPanel);
}

private void periodicTableActionPerformed(ActionEvent event)
{
mainFrame.remove(menuPanel);
mainFrame.repaint();
new PeriodicTable();
mainFrame.repaint();
}
}

最后是我的周期表面板

import javax.swing.*;
import java.awt.*;

public class PeriodicTable extends MainFrame
{
public PeriodicTable()
{
periodicComponents();
}

JPanel ptPanel;

private void periodicComponents()
{
ptPanel = new JPanel();
ptPanel.setLayout(null);
ptPanel.setBackground(Color.RED);
mainFrame.add(ptPanel);
}
}

最佳答案

我不知道你为什么要扩展 MainFrame。对我来说似乎没有必要。

I want to remove the one panel and replace it with the second when a button is pressed

然后使用CardLayout。阅读 Swing 教程中关于 How to Use CardLayout 的部分一个工作示例。

本教程将向您展示如何更好地构建代码。

关于java - repaint() 方法不绘制新帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43686158/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com