簡體   English   中英

圖形的最小代碼?

[英]Minimum code for graphics?

什么是絕對主義的最小代碼,我可以使用它給GraphicsJFrame ,那么例如我可以擺脫paint()方法? ,我需要調用super.update(g)嗎?

你不應該覆蓋paint()。 這通常是針對AWT的。

你不應該觸摸update()。 這也適用於AWT。

在Swing中,您覆蓋JPanel (或JComponent )的paintComponent()方法,並將面板添加到框架中。

你根本不接觸JFrame

閱讀自定義繪畫的Swing教程以獲取更多信息和示例。

paint()方法仍可用於覆蓋JFrame。 一個更好的解決方案是添加一個擴展JPanel的小類,並覆蓋“paintComponent(Graphics g)”方法,作為繪制形狀的畫布。 然后,您只需將該面板添加為JFrame中的另一個組件。 並且為了更新內容,您可以調用repaint()方法。 例如:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DoNotEnterSign extends JPanel {
public void paintComponent(Graphics g) {
    super.paintComponent(g);

    Point center = new Point(getWidth() / 2, getHeight() / 2);
    int radius = Math.min(getWidth() / 2, getHeight() / 2) - 5;
    int innerRadius = (int)(radius * 0.9);
    int barWidth = (int)(innerRadius * 1.4);
    int barHeight = (int)(innerRadius * 0.35);
    g.fillRect(center.x - barWidth/2, center.y - barHeight/2,
               barWidth, barHeight);
}

public static void main(String[] args) {
    JFrame frame = new JFrame("A simple graphics program");
    frame.setSize(400, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new DoNotEnterSign();
    panel.setBackground(Color.GREEN.darker());
    frame.getContentPane().add(panel, BorderLayout.CENTER);
    frame.setVisible(true);
}}

這是Swing類的基本組件。 雖然可以有更簡單的解決方案。 現在你可能不必更新()的東西,例如,如果你有一個textarea你可以輸入文本和一個按鈕轉換為大寫然后

public void actionPerformed(ActionEvent e) {
                area.setText(area.getText().toUpperCase());

一找到setTextarea()就會自動更新

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM