對於作業,我試圖創建一個具有框架的「CustomButton」,並在該框架中繪製兩個三角形和一個正方形。它應該給用戶一個按下按鈕後的效果。因此,對於初學者,我試圖設置起始圖形,繪製兩個三角形和一個正方形。我遇到的問題是,雖然我將框架設置爲200,200,並且我繪製的三角形被認爲是我的框架尺寸的正確結尾,但是當我運行該程序時,我必須擴展窗口以製作整個作品,我的「CustomButton」可見。這是正常的嗎?謝謝。簡單的框架和圖形幫助
代碼:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CustomButton
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
CustomButtonFrame frame = new CustomButtonFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class CustomButtonFrame extends JFrame
{
// constructor for CustomButtonFrame
public CustomButtonFrame()
{
setTitle("Custom Button");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
CustomButtonSetup buttonSetup = new CustomButtonSetup();
this.add(buttonSetup);
}
private static final int DEFAULT_WIDTH = 200;
private static final int DEFAULT_HEIGHT = 200;
}
class CustomButtonSetup extends JComponent
{
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
// first triangle coords
int x[] = new int[TRIANGLE_SIDES];
int y[] = new int[TRIANGLE_SIDES];
x[0] = 0; y[0] = 0;
x[1] = 200; y[1] = 0;
x[2] = 0; y[2] = 200;
Polygon firstTriangle = new Polygon(x, y, TRIANGLE_SIDES);
// second triangle coords
x[0] = 0; y[0] = 200;
x[1] = 200; y[1] = 200;
x[2] = 200; y[2] = 0;
Polygon secondTriangle = new Polygon(x, y, TRIANGLE_SIDES);
g2.drawPolygon(firstTriangle);
g2.setColor(Color.WHITE);
g2.fillPolygon(firstTriangle);
g2.drawPolygon(secondTriangle);
g2.setColor(Color.GRAY);
g2.fillPolygon(secondTriangle);
// draw rectangle 10 pixels off border
g2.drawRect(10, 10, 180, 180);
}
public static final int TRIANGLE_SIDES = 3;
}
將首選維存儲在靜態變量中並將其返回到getPreferredSize()中會更好。否則,每次調用getPreferredSize()時都會創建一個新實例,並且這可能會經常發生,具體取決於佈局。 – 2010-05-20 07:32:11
好點。更好的解決方案可能是在組件的構造函數中執行'setPreferredSize()'。希望OP閱讀此內容。 – aioobe 2010-05-20 07:35:28