我希望創建一個簡單的Java應用程序,該應用程序應該在黃色框架上繪製2個方塊 - 紅色和藍色。簡單的父子Java應用程序
appln包含一個窗口(JFrame),它具有作爲子項添加的contentPane(JPanel)。我已經添加了2個格作爲子到JFrame
/**
Squares' container
------------------
This file contiains 2 small squares - red and blue. The user can drag
these squares in the panel. If the user drags these squares out of the
panel, the square is lost forever.
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class sqsCont {
public static void main(String[] args) {
JFrame window = new JFrame();
window.setVisible(true);
sqsContPanel myPanel = new sqsContPanel();
window.setBounds(0,0,500,250);
window.getContentPane().add(myPanel);
window.setDefaultCloseOperation(window.EXIT_ON_CLOSE);
}
}
/**
Contains 2 squares red and blue side-by-side on
*/
class sqsContPanel extends JPanel{
mySquare redSq;
mySquare blueSq;
public sqsContPanel() {
//setBounds(0,0,500,250);
redSq = new mySquare(Color.RED);
blueSq = new mySquare(Color.BLUE);
add(redSq);
add(blueSq);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
setBackground(Color.YELLOW);
}
}
/**
Squares
*/
class mySquare extends JComponent{
int myWidth = 50;
int myHeight = 50;
Color myColor;
/**
myColor = color of the square
*/
public mySquare(Color myColor) {
this.myColor = myColor;
if(myColor == Color.RED) {
setBounds(10,10,10+myWidth,10+myHeight);
} else {
setBounds(20+myWidth,10,10+myWidth,10+myHeight);
}
setVisible(true);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
if (myColor == Color.RED){
setBackground(Color.RED);
g.setColor(Color.RED);
g.fillRect(10,10,10+myWidth,10+myHeight);
} else {
setBackground(Color.BLUE);
g.setColor(Color.BLUE);
g.fillRect(20+myWidth,10,10+myWidth,10+myHeight);
}
}
}
代碼生成與黃色幀中的窗口。但是,正方形不可見。
任何人都可以發現我在這段代碼中缺少的東西,或者我應該以不同的方式讓這個應用程序正常工作?
感謝
感謝您耐心解決我的問題:) – Edwards 2011-03-24 14:36:56