我试图用 JPanel 填充 JFrame 并为 JPanel 着色,但由于某种原因,我在右下边缘出现边框。
我的代码:
public class Main extends JFrame {
public MyPanel myPanel = new MyPanel();
public static void main(String args[])
{
Main main = new Main();
main.init();
}
public void init()
{
this.setSize(300,400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setContentPane(myPanel);
this.setVisible(true);
}
@Override
public void paint(Graphics g)
{
myPanel.paintComponents(g);
}
class MyPanel extends JPanel
{
@Override
public void paintComponents(Graphics g)
{
g.fillRect(0, 0, getWidth(), getHeight());
}
}
}
演出:
最佳答案
您正在使用此方法使绘制链短路
@Override
public void paint(Graphics g) {
myPanel.paintComponents(g);
}
这并没有真正做任何有用的事情,因此您可以将其删除。此外,您还需要在 MyPanel
paintComponent
而不是 paintComponents
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillRect(0, 0, getWidth(), getHeight());
}
旁白:
- 您可以简单地创建一个面板并调用
setBackground
来获取此功能
关于java - JFrame 中不需要的 JPanel 边框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28726737/