Java图形-绘制矩形

问题描述 投票:1回答:2

我正在尝试制作一个在Windows中绘制16个矩形的程序。当您用鼠标单击一个矩形时,它应该消失。这些说明告诉我创建一个名为Rektangel的类,其中包含变量x,y,b,h(瑞典语的长度和宽度)。然后,我应该创建Rectangel类型的16个对象并将它们存储在列表中。

我做了三个类别,分别是Panel14_1Frame14_1Rektangel。我试图将面板拉入框架,但是没有用。当我运行该程序时,它仅打开一个窗口,并且其中没有红色矩形...

Frame

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                   
}

Rektangel

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                   
java swing graphics
2个回答
0
投票

您好,欢迎来到stackoverflow !! :D

要绘制矩形,请使用Graphics.fillRect(x,y,w,h)或仅对轮廓使用Graphics.drawRect(x,y,w,h

如果您希望它们消失,则必须用鼠标单击一个矩形来绘制JFrame。我将创建一个JButton并添加一个ActionListener。

编辑:覆盖paintComponent方法而不是printComponent


0
投票

您需要做的第一件事是通过JPanelJFrame添加到add(new Panel14_1())。无需将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)
© www.soinside.com 2019 - 2024. All rights reserved.