Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 重新加载JComponent_Java_Swing_Awt - Fatal编程技术网

Java 重新加载JComponent

Java 重新加载JComponent,java,swing,awt,Java,Swing,Awt,如何在JFrame中从它自己的类中重新加载一个组件,就好像我要删除它、创建一个新组件并再次添加它一样 很像this.repaint(),但如果可能的话,实际上是重建它。首先,不应该直接在框架上添加JComponent,最好是在JFrame上添加JPanel,然后在其上添加组件 要更换JPanel上的组件,可以使用以下功能 jPanel.remove(comp); or jPanel.removeAll(); jPanel.add(comp); jPanel.revalidate(); jpan

如何在JFrame中从它自己的类中重新加载一个组件,就好像我要删除它、创建一个新组件并再次添加它一样


很像
this.repaint()
,但如果可能的话,实际上是重建它。

首先,不应该直接在框架上添加JComponent,最好是在JFrame上添加JPanel,然后在其上添加组件

要更换JPanel上的组件,可以使用以下功能

jPanel.remove(comp);
or
jPanel.removeAll();

jPanel.add(comp);
jPanel.revalidate();
jpanel.repaint();
如果您只想使用JFrame,则在更换组件后需要稍微调整框架的大小,以便使用jf.setSize(x,y)刷新框架


为什么?与其创建新组件,不如重置现有组件的属性。因为在构造函数中,我读取了一个文件,并相应地更新了组件的内容,如果可能的话,它会产生比复制代码读取文件和修改某些数组的范围更干净的结果:)
比复制代码更干净。
-为什么需要复制代码?您可以创建一个方法。该方法将从文件中获取数据并更新组件。当然,但我仍然需要执行许多操作,而不仅仅是一个操作,我只是问这是否可行
import javax.swing.*;
import java.util.concurrent.*;
public class FrameReplaceComp {
  public static void main(String[] args) throws Exception {

    JFrame frame = new JFrame("Hello swing");
    final JLabel label = new JLabel("Label 1");
    frame.add(label);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(300, 100);
    frame.setVisible(true);

    Thread.sleep(1000);

    final JLabel label1 = new JLabel("Label 2");
    frame.remove(label);
    frame.add(label1);
    frame.setSize(300,101);

  }
}