gpt4 book ai didi

java - 动态删除 JPanel

转载 作者:行者123 更新时间:2023-12-02 00:29:43 38 4
gpt4 key购买 nike

我已经阅读了有关该主题的许多主题和问题,但似乎无法找到解决该问题的可行解决方案。下面是用于添加和删除组件的方法的代码。

public void addAuxPanel (String pType, int pStart, int pEnd) {

int id = mPanels.size();
int xPos = PANEL_START_X;
int yPos = PANEL_START_Y + (PANEL_HEIGHT * id) + 15;

if (id == 0) {
xPos = PANEL_START_X;
}

String type = pType;
int start = pStart;
int end = pEnd;

AuxPanel p = new AuxPanel(type, start, end, id, this);
mPanels.add(p);

p.setBounds(xPos, yPos, 300, 25);

getRootPane().add(p);
getRootPane().repaint();
getRootPane().revalidate();
}

public void removeAuxPanel (AuxPanel pPanel) {

getRootPane().remove(pPanel);
getRootPane().revalidate();
getRootPane().repaint();

}

最佳答案

您只需执行frameObject.remove(yourPanel);

与普通的 revalidate() 和 repaint() 相比。

这里有一个小代码可以为您提供帮助:

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

public class TwoPanels extends JFrame {

public TwoPanels() {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

final JPanel panel1 = new JPanel();
panel1.setBackground(Color.RED);
final JPanel panel2 = new JPanel();
panel2.setBackground(Color.BLUE);

JButton button = new JButton("ADD AND REMOVE PANEL");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
if (panel1.isShowing()) {
remove(panel1);
add(panel2, BorderLayout.CENTER);
revalidate();
repaint();
} else if (panel2.isShowing()) {
remove(panel2);
add(panel1, BorderLayout.CENTER);
revalidate();
repaint();
}
}
});

add(panel1, BorderLayout.CENTER);
add(button, BorderLayout.PAGE_END);

pack();
setLocationByPlatform(true);
setVisible(true);
}

public static void main(String... args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TwoPanels();
}
});
}
}

如果您想从 JPanel 中删除组件,请参阅此代码,remove() 仍然适用:

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

public class TwoPanels extends JFrame {

public TwoPanels() {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

final JPanel panel1 = new JPanel();
final JLabel label = new JLabel("I am a JLabel");
panel1.setBackground(Color.WHITE);
panel1.add(label);

JButton button = new JButton("ADD AND REMOVE PANEL");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
if (label.isShowing()) {
panel1.remove(label);
panel1.revalidate();
panel1.repaint();
} else {
panel1.add(label);
panel1.revalidate();
panel1.repaint();
}
}
});

add(panel1, BorderLayout.CENTER);
add(button, BorderLayout.PAGE_END);

pack();
setLocationByPlatform(true);
setVisible(true);
}

public static void main(String... args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TwoPanels();
}
});
}
}

关于java - 动态删除 JPanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9316930/

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