使用JPanel绘画时无法在屏幕上看到数字

时间:2017-11-23 16:41:14

标签: java swing jframe jpanel paintcomponent

如果有人能解释为什么我在面板上只看到一行运行此代码,请。 当我删除下面的所有frame.add()行并且只保留一行时,我实际上可以选择要查看哪一行但我怎么能看到它们呢?

这是创建JFrame的主要方法

public class Main extends JPanel {
 public static void main(String[] args) {
    JFrame frame = new JFrame("Drawing Board");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 400);
    frame.setVisible(true);
    MyLine line1 = new MyLine(70, 100, 120, 150, Color.BLACK);
    MyLine line2 = new MyLine(60, 80, 120, 150, Color.blue);
    MyLine line3 = new MyLine(50, 65, 120, 150, Color.BLACK);
    MyLine line4 = new MyLine(40, 25, 120, 150, Color.blue);
    MyLine line5 = new MyLine(30, 90, 120, 150, Color.BLACK);
    MyLine line6 = new MyLine(20, 130, 120, 150, Color.blue);
    JPanel panel = new JPanel();

    panel.add(line1);
    panel.add(line2);
    panel.add(line3);
    panel.add(line4);
    panel.add(line5);
    panel.add(line6);
    frame.add(panel);
  }
}

我的线方法扩展了MyShape

import java.awt.*;
import javax.swing.*;

public class MyLine extends MyShape {

 public MyLine(int x1,int y1,int x2,int y2,Color colorOfLine){
    super(x1, y1, x2, y2, colorOfLine);
}
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(shapeColor);
    g.drawLine(x1, y1, x2, y2);
 }
}       

MyShape扩展了jpanel

import java.awt.*;
import javax.swing.*;

public abstract class MyShape extends JPanel {
protected int x1,x2,y1,y2;
protected Color shapeColor;
protected MyShape(int x1,int y1,int x2,int y2,Color colorOfShape) {
    this.x1=x1;
    this.x2=x2;
    this.y1=y1;
    this.y2=y2;
    shapeColor = colorOfShape;
}

0 个答案:

没有答案