我有一个问题。现在我正在使用 3 个面板,mainPanel 和其他 2 个面板(btnPanel 和 iconPanel)。 所以问题是当我按下“重置”按钮时,我删除了 iconPanel 并再次添加它,它自己稍微向右移动。也许有人可以检查我的代码哪里有问题?
此外,我不想创建另一个问题,所以我提出了 2 个额外的问题。
我是否正确删除了 JPanel? 如果我删除带有内部组件的 JPanel,它们也会从内存中删除吗?
附言我是初学者,所以不要评判我:)
Main.java
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Main extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("Made by Mac4s");
frame.setVisible(true);
frame.setSize(310, 654);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setResizable(false);
MainScreen screenObj = new MainScreen();
screenObj.setPreferredSize(new Dimension(310, 650));
frame.add(screenObj);
}
});
}
}
MainScreen.java
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
public class MainScreen extends JPanel {
private JButton resetBtn;
private JPanel btnPanel;
private JPanel iconPanel;
public MainScreen() {
JPanel mainPanel = new JPanel(new BorderLayout());
this.setBackground(Color.BLACK);
setBtnPanelAndComp();
setIconPanelAndComp();
add(mainPanel);
}
private void setBtnPanelAndComp() {
btnPanel = new JPanel(new BorderLayout());
btnPanel.setBackground(Color.GREEN);
btnPanel.setPreferredSize(new Dimension(295, 30));
setButtons();
this.add(btnPanel, BorderLayout.NORTH);
}
private void setButtons() {
resetBtn = new JButton("Reset");
resetBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
resetIconLabel();
}
});
btnPanel.add(resetBtn, BorderLayout.WEST);
}
private void resetIconLabel() {
this.remove(iconPanel);
this.repaint();
this.revalidate();
setIconPanelAndComp();
}
private void setIconPanelAndComp() {
iconPanel = new JPanel(new BorderLayout());
iconPanel.setBackground(Color.YELLOW);
iconPanel.setPreferredSize(new Dimension(295, 580));
this.add(iconPanel, BorderLayout.SOUTH);
}
}
最佳答案
"the problem is when I push button "reset" I delete iconPanel and add it again it moves slightly to right on its own."
发生这种情况的原因是 JPanel
默认有一个 FlowLayout
。您正在尝试添加到一个不存在的 BorderLayout
位置。
this.add(iconPanel, BorderLayout.SOUTH);
FlowLayout
的边缘有默认间隙,因此当您设置框架大小时,这些间隙不会受到影响。为了克服这个问题,最好使用 pack()
框架,而不是 setSize()
BorderLayout
起作用(不移动)的原因是不考虑首选尺寸。
如果您在构造函数中将布局设置为 this.setLayout(new BorderLayout());
,您将不会发生偏移。
public MainScreen() {
JPanel mainPanel = new JPanel(new BorderLayout());
this.setLayout(new BorderLayout()); <----
setBtnPanelAndComp();
setIconPanelAndComp();
add(mainPanel);
}
注意事项
- 您应该
setVisible()
在 添加组件之后。这就是为什么当你第一次打开它时你的框架会跳动的原因。您正在将框架设置为可见,然后随位置四处移动它,并添加组件。
关于Java JPanel 自己稍微移动 + 额外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21364044/