JFrame 中不需要的 JPanel 边框
Unwanted JPanel border in JFrame
我试图用 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);
}
这实际上没有任何用处,因此您可以将其删除。您还需要覆盖 paintComponent
而不是 MyPanel
中的 paintComponents
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillRect(0, 0, getWidth(), getHeight());
}
旁白:
- 您可以简单地创建一个面板并调用
setBackground
来获得此功能
我试图用 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);
}
这实际上没有任何用处,因此您可以将其删除。您还需要覆盖 paintComponent
而不是 MyPanel
paintComponents
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillRect(0, 0, getWidth(), getHeight());
}
旁白:
- 您可以简单地创建一个面板并调用
setBackground
来获得此功能