jpanel java删除文字_java – JFrame删除JPanels并添加新的JPanel

我当然有一个发送HTTP请求的SwingWorker,我重写了SwingWorker的done()方法来改变JFrame中的内容.我想基本上删除所有内容并在JFrame上添加一个新的成员面板,具体取决于从服务器返回的值.

现在,我面临的问题是,当我在JFrame上调用以下方法时,它不会从JFrame中删除任何内容,也不会更改Frame中包含的内容.

//TODO: Investigate why JFrame content pane won't repaint.

f.removeAll();

//Pass the frame f reference only into MainDisplay, it doesn't actually do anything apart from allowing a class to add a JMenuBar on the JFrame.

f.add(new MainDisplay(f));

f.getContentPane().invalidate();

f.getContentPane().validate();

f.getContentPane().repaint();

我目前的修复方法如下所示,但我宁愿更改JFrame的内容,而不是加载新的内容.

f.dispose();

f=new ApplicationFrame();

我在这里和谷歌上看过以前的答案,有些州使用validate()或invalidate()同时调用repaint()来重绘JFrame.

任何建议/帮助将不胜感激.

编辑:我想我会调试更多,因为一定有其他问题.

最佳答案

例如

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class MyFrame extends JFrame {

private static final long serialVersionUID = 1L;

public MyFrame() {

final JPanel parentPanel = new JPanel();

parentPanel.setLayout(new BorderLayout(10, 10));

final JPanel childPanel1 = new JPanel();

childPanel1.setBackground(Color.red);

childPanel1.setPreferredSize(new Dimension(300, 40));

final JPanel childPanel2 = new JPanel();

childPanel2.setBackground(Color.blue);

childPanel2.setPreferredSize(new Dimension(800, 600));

JButton myButton = new JButton("Add Component ");

myButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

parentPanel.remove(childPanel1);

parentPanel.add(childPanel2, BorderLayout.CENTER);

parentPanel.revalidate();

parentPanel.repaint();

pack();

}

});

setTitle("My Empty Frame");

setLocation(10, 200);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

parentPanel.add(childPanel1, BorderLayout.CENTER);

parentPanel.add(myButton, BorderLayout.SOUTH);

add(parentPanel);

pack();

setVisible(true);

}

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {

@Override

public void run() {

MyFrame myFrame = new MyFrame();

}

});

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值