[英]Elegant way to accomplish realization in Java Swing?
我經常遇到Swing方法或屬性需要實現對象的問題。 例如,要在JPanel上繪圖,我可能需要知道特定字體的高度,但是這個信息在面板實現之后才可用,所以在此之前我會得到一個空指針。 更糟糕的是,(至少對我來說)並不總是清楚哪些方法需要實現對象,哪些方法不需要。
顯然我可以做一些愚蠢的事情:
必須要做到這一點似乎非常難以置信。 是否有更優雅的方式來強制實現,以便我可以獲得對字體指標的可靠訪問?
典型示例代碼:
void draw( Point2D center ){
String sLabel = owner.getLabel();
NodeData.DATA_TYPE eType = owner.data_type;
int iSymbolWidth = 10;
// build text
if( sLabel == null ) sLabel = "";
Font font = new Font( "TimesRoman", Font.PLAIN, 12 );
text_node.setTextPaint( Color.DARK_GRAY );
text_node.setText( sLabel );
text_node.setFont( font );
Panel_Main panel = owner.application.getDisplayPanel();
java.awt.FontMetrics fm = panel.canvas.getGraphics().getFontMetrics(); // <--- ERROR HERE
int iText_AdvanceWidth = ( int ) ( fm.stringWidth( sLabel ) * 1.2 ) + LABEL_MARGIN * 2;
int iText_Height = fm.getHeight();
.... etc
問題的一部分是我正在繪制的對象由Piccolo(一個圖形繪制庫)擁有,因此庫擁有paintComponent,而不是我。 在挖掘Piccolo源代碼時,似乎我需要覆蓋它們的一個內部方法paint(PPaintContext paintContext),它基本上應該等同於覆蓋paintComponent。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.