import java.awt.Graphics; import javax.swing.JFrame; import javax.swing.JPanel;public class MyDraw extends JFrame{ JPanel jp = new JPanel(); MyDraw(){ this.setVisible(true); this.setSize(500,500); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }
public void paint(Graphics g) { MyDrawLine my = new MyDrawLine(); my.paint(g); jp.add(my); this.add(jp); } public static void main(String[] args) { new MyDraw(); } }
import java.awt.Color; import java.awt.Graphics; import javax.swing.JFrame;import javax.swing.JPanel;public class MyDrawLine extends JPanel{ public void paint(Graphics g) { drawRect(g,40,40,300,300); } public void drawRect(Graphics g,int x, int y, int width, int height) { g.setColor(Color.red); if ((width < 0) || (height < 0)) { return; } if (height == 0 || width == 0) { g.drawLine(x, y, x + width, y + height); } else { g.drawLine(x, y, x + width - 1, y); g.drawLine(x + width, y, x + width, y + height - 1); g.drawLine(x + width, y + height, x + 1, y + height); g.drawLine(x, y + height, x, y + 1); } }
public static void main(String[] args) { JFrame ff = new JFrame(); ff.getContentPane().add(new MyDrawLine()); ff.setSize(500, 500); ff.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ff.setVisible(true); } }
jp.add(new MyDrawLine());
this.getContentPane().add(jp);
对于你这个程序来说,还有你为什么不把new MyDrawLine()直接放在JFrame的ContentPane上? this.getContentPane().add(new MyDrawLine());
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;public class MyDraw extends JFrame{ JPanel jp = new JPanel();
MyDraw(){
this.setVisible(true);
this.setSize(500,500);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void paint(Graphics g) {
MyDrawLine my = new MyDrawLine();
my.paint(g);
jp.add(my);
this.add(jp);
}
public static void main(String[] args) {
new MyDraw();
}
}
import java.awt.Graphics;
import javax.swing.JFrame;import javax.swing.JPanel;public class MyDrawLine extends JPanel{
public void paint(Graphics g) {
drawRect(g,40,40,300,300);
}
public void drawRect(Graphics g,int x, int y, int width, int height) {
g.setColor(Color.red);
if ((width < 0) || (height < 0)) {
return;
} if (height == 0 || width == 0) {
g.drawLine(x, y, x + width, y + height);
} else {
g.drawLine(x, y, x + width - 1, y);
g.drawLine(x + width, y, x + width, y + height - 1);
g.drawLine(x + width, y + height, x + 1, y + height);
g.drawLine(x, y + height, x, y + 1);
}
}
public static void main(String[] args) {
JFrame ff = new JFrame();
ff.getContentPane().add(new MyDrawLine());
ff.setSize(500, 500);
ff.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ff.setVisible(true);
}
}
所以自己简单的设计了一个这样的题
jp.setLayout(new BorderLayout());
jp.add(new MyDrawLine());
this.getContentPane().add(jp);
让他们一样大