錯誤代碼如下所示:
JFrame 型別的方法 setColor(Color) 未定義
package task3;
class Execute {
public static void main(String[] args) throws Exception {
Controller c = new Controller();
c.simulate();
}
}
class Model {
int l; //line
int c; //column
int[] loc = {0,0}; //location
JFrame frame;
int m_width;
int m_height;
int R = (int)(Math.random()*256);
int G = (int)(Math.random()*256);
int B = (int)(Math.random()*256);
public int getRectWidth() {
return frame.getContentPane().getWidth() / c;
}
public int getRectHeight() {
return frame.getContentPane().getHeight() / l;
}
Model(int width, int height, int line, int column, JFrame w) {
m_width = width;
m_height = height;
l = line;
c = column;
frame = w;
}
}
class View extends JComponent {
private Model m_Mod;
View(Model mod) {
m_Mod = mod;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for(int i=0; i<m_Mod.l; i) {
for(int j=0; j<m_Mod.c; j) {
g.fillRect(m_Mod.loc[0], m_Mod.loc[1], m_Mod.getRectWidth(), m_Mod.getRectHeight());
m_Mod.loc[0] = m_Mod.loc[0] m_Mod.getRectWidth() 2;
}
m_Mod.loc[0] = 0;
m_Mod.loc[1] = m_Mod.loc[1] m_Mod.getRectHeight() 2;
}
m_Mod.loc[1] = 0;
}
}
class Controller extends JFrame{
private Model m_Mod;
private View m_View;
Controller(){
JFrame window = new JFrame();
Color color = new Color(m_Mod.R, m_Mod.G, m_Mod.B);
m_Mod.frame.setColor(color);
// 此處的錯誤代碼:方法 setColor(Color) 未為 JFrame 型別定義
m_Mod = new Model(500,500,3,8, window);
m_View = new View(m_Mod);
window.add(m_View);
window.setSize(m_Mod.m_width,m_Mod.m_height);
window.setLocationRelativeTo(null);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
void simulate(){
//m_View.repaint();
}
}
如果我將顏色部分注釋掉,程式就可以完美運行。有任何想法嗎?此外,該setColor()方法在 Java Frame 類中,不是嗎?那么為什么它不起作用呢?一些網站告訴我更新我的圖書館
uj5u.com熱心網友回復:
此外 setColor() 方法在 Java Frame 類中,不是嗎?
你讀過 API 嗎?這是您嘗試解決問題時所做的第一步。
您不能設定 JFrame 的顏色。您可以設定添加到框架的組件的前景/背景。
通常,您會使用setBackground()添加到框架的面板上的 :
m_View = new View(m_Mod);
m_View.setBackground(...); // added
window.add(m_View);
但是,這不起作用,因為您正在擴展默認情況下不繪制背景的 JComponent。
如果你想擴展 JComponent 那么你需要添加繪畫代碼:
super.paintComponent( g );
g.setColor( getBackground() );
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor( getForeground() ); // default color for your custom painting
或者,更簡單的方法是擴展JPanel,因為 JPanel 會自動使用您設定的顏色繪制背景。
uj5u.com熱心網友回復:
setColor() method需要在paintComponent method. 那是我在這里的錯誤。現在它可以作業了,矩形被繪制成彩色。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/475244.html
下一篇:linux-bash基礎入門
