需要将 frame.setRessizeable(false) 设置为 repaint()



我正在尝试提高我的Java技能(自从我编码以来已经有大约10年了)。目前,我只是在尝试制作一个基本程序,该程序将使球从JFrame的边缘反弹。但是,作为该程序的初学者,我尝试在 JPanel 上绘制一条线和一框。

我发现的问题是我必须按顺序调用frame.setRessizeable(false)或屏幕来绘制我的框和线条。如果我在 JFrame 出现后调整它的大小,它会绘制它们。但是,我希望它在 JFrame 打开后立即绘制。

投入:

frame.setResizable(false);
frame.setResizable(true);

似乎多余。有没有更干净的方法来做到这一点,以便在 JFrame 打开时绘制?

如果这有帮助,下面是我的代码:

主班

package bbs;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
public class BouncingBalls {
public static void main(String[] args) {
//Create the basic frame, set its size, and tell it to be visible
JFrame frame = new JFrame();
frame.setSize(800, 600);
frame.setVisible(true);
//Get a icon for the Program
ImageIcon logoicon = new ImageIcon("ball.jpg");
Image logo = logoicon.getImage();
frame.setIconImage(logo);
frame.setResizable(false);
frame.setResizable(true);
//find the center of the screen and where the frame should go
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int w = frame.getSize().width;
int h = frame.getSize().height;
int x = (dim.width-w)/2;
int y = (dim.height-h)/2;
//Move the window
frame.setLocation(x, y);
//Tell the program to stop when the X button is selected
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   
Draw object = new Draw();
frame.add(object);
object.drawing();
}
}

绘画课

package bbs;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class Draw extends JPanel {
/**
* This is added to handle the serialization warning and is of the type Long to accommodate the warning
*/
private static final long serialVersionUID = 1L;
public void drawing(){
repaint();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.BLACK);
g.drawLine(10, 20, 300, 200);
g.setColor(Color.BLUE);
g.fillRect(300, 200, 150, 200);
}
}
frame.setVisible(true);

这应该是将所有组件添加到帧后执行的最后一个语句。

然后所有组件将正常绘制。

最新更新