在Java中,JFrame是一個頂層容器,用于存放其他組件。當你需要重繪JFrame中的組件時,可以遵循以下步驟:
public class CustomComponent extends JComponent {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g); // 必須首先調用父類的paintComponent方法,以確保正確繪制背景色等
// 在這里繪制你的組件內容
g.drawOval(50, 50, 100, 100); // 繪制一個橢圓
}
}
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("Custom Component Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
CustomComponent customComponent = new CustomComponent();
frame.add(customComponent);
frame.setVisible(true);
}
}
public class CustomComponent extends JComponent {
// ... 其他代碼 ...
@Override
public void componentResized(ComponentEvent e) {
// 在這里繪制調整大小后的組件內容
repaint(); // 調用repaint()方法,以便觸發paintComponent方法的調用
}
}
遵循以上步驟,你就可以處理JFrame類組件的重繪了。注意,為了確保正確的繪制順序,你可能需要在自定義組件類中重寫其他方法,例如getPreferredSize()和paintBorder()等。