import java.io.*;
public class BoxFun {
public static void main (String[] args) /*throws IOException*/ {
TwoWindows r1 = new TwoWindows ();
TwoWindows r2 = new TwoWindows ();
//System.out.println ("Enter when ready");
//System.in.read();
r1.paint();
r2.paint();
}
}
//////////////////////////////////
import javax.swing.*;
import java.awt.*;
public class TwoWindows {
private int width;
private int height;
private int x;
private int y;
private JFrame window;
private Color color;
public TwoWindows () {
window = new JFrame ("Box Fun");
window.setSize(200, 200);
width = 40;
height = 20;
x = 80;
y = 90;
color = Color.RED;
window.setVisible(true);
}
public void paint () {
Graphics g = window.getGraphics();
g.setColor(color);
g.fillRect(x, y, width, height);
}
}
我就是想画两个窗口,每个窗口中有个 rectangle,为什么在执行 boxfun之后只弹出了窗口,而没有rectangle?
------解决方案--------------------
have a try
public void paint () {
Graphics g = window.getGraphics();
g.setColor(color);
g.fillRect(x, y, width, height);
window.repaint(); // use repaint to have a try
}
最好是用paintComponent
//modify here
window = new JFrame ("Box Fun") {
public void paintComponent(Graphics g) {
super.paintComponent(g);
doUserPaint(g);
}
};
//modify here
public void paint () {
window.repaint();
}
//add code here
protected void doUserPaint(Graphics g) {
g.setColor(color);
g.fillRect(x, y, width, height);
}
仅供参考
------解决方案--------------------
ding
------解决方案--------------------
// 1、推荐方法
// BoxFun.java
import java.io.*;
public class BoxFun {
public static void main (String[] args)
{
new TwoWindows ();
new TwoWindows ();
}
}
///////////////////////////////////////////////
// TwoWindows.java
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Rectangle2D;
class TwoWindows extends JFrame
{
public TwoWindows()
{
setTitle("Box Fune");
setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);
width=40;
height=20;
x=80;
y=90;
DrawPanel panel=new DrawPanel();
getContentPane().add(panel);
color=Color.RED;
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
private static final int DEFAULT_WIDTH= 200;
private static final int DEFAULT_HEIGHT = 200;
private int width;
private int height;
private int x;
private int y;
private JFrame window;
private Color color;
private class DrawPanel extends JPanel
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2=(Graphics2D)g;
Rectangle2D r2d=new Rectangle2D.Double();
r2d.setFrame(x,y,width,height);
g2.setColor(color);
g2.fill(r2d);
}
}
}
//-----------------------------------------------
// 2、不推荐方法
// BoxFun.java
import java.io.*;
public class BoxFun {
public static void main (String[] args)
{
new TwoWindows ();
new TwoWindows ();