2017-03-18 46 views
0

我正在嘗試去加強我的Java技能(自從我編寫了大約10年以來)。目前,我只是試圖製作一個基本程序,它將彈出JFrame邊緣的球。然而,作爲這個程序的開端,我嘗試在JPanel上繪製一個線條和框。需要設置frame.setResizable(false)重繪()

我發現的問題是我必須按順序調用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); 
    } 
} 
+0

以'frame.setVisible(true);'使它成爲你添加完所有組件後最後一次調用的東西。你也可以使用'frame.setLocationRelativeTo(null)'將屏幕居中在屏幕上,這可能比使用'Toolkit.getDefaultToolkit()。getScreenSize();' – MadProgrammer

+0

如果你需要更新UI框架變得可見,你可以在你改變的容器上使用'revalidate'和'repaint'來觸發一個佈局和繪製過程 – MadProgrammer

回答

1
frame.setVisible(true); 

這應該是畢竟執行的最後聲明COM支架已被添加到框架中。

然後所有組件都會正常繪製。