[英]JAVA, GUI JPanel, JFrame, paintComponent, Graphics
關於您的評論更改添加公共顯示(圖形g)
[link] http://www3.canyons.edu/Faculty/biblej/project6.html
1.)Project6類將必須擴展JFrame類。2.)Project6構造函數將必須設置GUI窗口。 3)一種新的抽象方法:public void display(Graphics g); 應該添加到基類和派生類中。4)必須使用paintComponent方法設置自定義的JPanel。5)新的display(Graphics g)方法將必須在GUI窗口上繪制形狀並從循環中調用在paintComponent方法中
public class Project6 extends JFrame {
//project6 constructor without parameters to set up new JFrame
public Project6() {
add(new NewPanel());
}
class NewPanel extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
//所以我需要在這里添加Graphics g嗎? 或者沒有?
for(int i = 0; i < thearray.length && thearray[i] != null; i++) {
thearray[i].display(**Graphics g**);
}}}
public static void main (String [] args) {
JFrame frame = new JFrame();
frame.setSize(800, 700);
frame.setTitle("Shapes");
frame.setLocationRelativeTo(null); //Center Frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
例如,這是類之一,是否可以像這樣將其添加到末尾? 我是否需要向Shape父類添加公共抽象void顯示(圖形g)? 以及如何在project6類中調用它?
public class Rectangle extends Shape {
private int width;
private int height;
public Rectangle() {
setWidth(0);
setHeight(0);
setXPos(0);
setYPos(0);}
public Rectangle(int xPos, int yPos, int height, int width) {
setWidth(xPos);
setHeight(yPos);
setXPos(height);
setYPos(width);}
public int getWidth() {
return width;}
public void setWidth(int width) {
this.width = width;}
public int getHeight() {
return height;}
public void setHeight(int height) {
this.height = height;}
@Override
public void display() {
System.out.println("Rectangle: (" + getXPos() + ", " + getYPos() + ") " + " Height: " + height + " Width: " + width);}
@Override
public void display(Graphics g) {
g.drawRect(getXPos(), getYPos(), width, height); }
一種新的抽象方法: public void display(Graphics g); 應該添加到基類和派生類
您沒有正確完成此步驟,因為我注意到您正在調用thearray[i].display();
當display
旨在具有參數時。
如果正確創建display
方法,則將獲得可以使用的Graphics對象,例如:
class Line extends Shape {
int x1, y1, x2, y2;
@Override
public void display(Graphics g) {
g.drawLine(x1, y1, x2, y2);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.