我正在努力提高我的 java 技能(自从我编码以来已经有大约 10 年了)。目前我只是想制作一个基本程序,让球从 JFrame 的边缘弹起。然而,作为该程序的初学者,我尝试在 JPanel 上绘制线条和方框。
我发现的问题是我必须按顺序调用frame.setResizable(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);
这应该是所有组件添加到框架后执行的最后一条语句。
然后所有组件都会正常绘制。
关于java - 需要设置frame.setResizable(false)为repaint(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42869816/