簡體   English   中英

Java 圖形-繪制矩形

[英]Java Graphics - draw rectangle

我正在嘗試制作一個在 windows 中繪制 16 個矩形的程序。 當您用鼠標單擊一個矩形時,它應該會消失。 說明告訴我創建一個名為Rektangel的 class 變量 x、y、b、h(瑞典語中的長度和寬度)。 然后我應該創建 16 個Rectangel類型的對象並將它們存儲在一個列表中。

我做了三個類,分別命名為Panel14_1Frame14_1Rektangel 我試圖將面板拉入框架,但它不起作用。 當我運行程序時,它只打開一個 window 並且其中沒有紅色矩形......

框架

package ovning14__1;

public class Frame14__1 extends javax.swing.JFrame {

    /**
     * Creates new form Frame14__1
     */
    public Frame14__1() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Frame14__1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Frame14__1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Frame14__1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Frame14__1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(() -> {
            new Frame14__1().setVisible(true);
        });
    }

    // Variables declaration - do not modify                     
    // End of variables declaration                   
}

雷克坦格爾

package ovning14__1;

import java.awt.Color;
import java.awt.Graphics;

public class Rektangel {
    private int x = 0;
    private int y = 0;
    private int b = 10;
    private int h = 10;

    public Rektangel(int x, int y, int h, int b) {
        this.x = x;
        this.y = y;
        this.b = b;
        this.h = h;
    }

    public void Rita(Graphics g){
        g.setColor(Color.RED);
        g.fillRect(x, y, b, h);
    }

    public boolean ärTräffad(int musX, int musY){
        boolean träffad = false;
        if (musX > x && musX < (x+h) && musY > y && musY < (y+b)) {
            träffad = true;
        }
        return träffad;
    }
}

控制板

package ovning14__1;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.util.ArrayList;


public class Panel14_1 extends javax.swing.JPanel {
    private final ArrayList<Rektangel> rektanglar = new ArrayList<>();
    private boolean speletÄrSlut = false;

    public Panel14_1() {
        initComponents();
        for (int rad = 0; rad < 4; rad++){
            for (int kolumn = 0; kolumn < 6; kolumn++){
                int x = 10 + 50 * kolumn;
                int y = 10 + 30 * rad;
                int h = 30;
                int b = 20;
                Rektangel rektangel = new Rektangel(x, y, h, b);
                rektanglar.add(rektangel);
            }
        }
    }

    @Override
    protected void printComponent(Graphics g) {
        super.printComponent(g);
        for (int i = 0; i < rektanglar.size(); i++){
            Rektangel rektangel = rektanglar.get(i);
            rektangel.Rita(g);
        }
        if (speletÄrSlut) {
            String text = "Grattis";
            Font font = new Font (Font.SANS_SERIF, Font.PLAIN, 30);
            g.setFont(font);
            g.setColor(Color.BLUE);
            int x = 25;
            int y = 30;
            g.drawString(text, x, y);
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                formMousePressed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );
    }// </editor-fold>                        

    private void formMousePressed(java.awt.event.MouseEvent evt) {                                  
        boolean träff = false;
        for (int i =0; i < rektanglar.size() && !träff; i++){
            Rektangel rektangel = rektanglar.get(i);
            if (rektangel.ärTräffad(evt.getX(), evt.getY())){
                rektanglar.remove(i);
                träff= true;
            }
        }
        if(rektanglar.isEmpty()){
            speletÄrSlut = true;
        }
        repaint();
    }                                 
}
// Variables declaration - do not modify                     
// End of variables declaration                   

您好,歡迎來到stackoverflow:! :D

要繪制矩形,請使用Graphics.fillRect(x,y,w,h)或僅繪制輪廓使用Graphics.drawRect(x,y,w,h )。

如果你想讓它們消失,那么你必須用鼠標點擊一個矩形來繪制你的 JFrame。 我會創建一個 JButton 並添加一個 ActionListener。

編輯:覆蓋paintComponent方法而不是printComponent

您需要做的第一件事是通過add(new Panel14_1())JPanel添加到JFrame中。 無需將GroupLayout設置為JFrame 默認( BorderLayout )將完成這項工作。 所以

public class Frame14__1 extends javax.swing.JFrame {

    public Frame14__1() {
        initComponents();
    }

    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        add(new Panel14_1()); //add a panel to frame
        pack();
    }

    public static void main(String args[]) {
       ..no change is needed 
    }
} 

實施這些更改后,您將看到矩形。
Panel14_1盡管覆蓋printComponent應該可以工作,但您應該覆蓋paintComponent

protected void  paintComponent(Graphics g) { //not printComponent
        super.paintComponent(g);
        ..no change in the following code 
}


旁注:根據 Java 命名約定Rita(Graphics g)應該是rita(Graphics g)

暫無
暫無

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

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