java需要设置框架。可设置大小(false)以重新绘制()
我正在努力提高我的java技能(我编写代码已经10年了)。目前我只是想做一个基本的程序,让球从JFrame的边缘反弹。然而,作为这个程序的初学者,我尝试在JPanel上画一条线和一个方框
我发现的问题是我必须调用frame。按顺序设置可调整大小(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);
}
}
# 1 楼答案
这应该是将所有组件添加到框架后执行的最后一条语句
然后所有部件都将正常喷漆