简体   繁体   English

Java 图形-绘制矩形

[英]Java Graphics - draw rectangle

I am trying to make a program that paints 16 rectangles in a windows.我正在尝试制作一个在 windows 中绘制 16 个矩形的程序。 When you click on a rectangle with the mouse, it should disappear.当您用鼠标单击一个矩形时,它应该会消失。 The instructions tell me to create a class named Rektangel with the variables x, y, b, h (length and width in Swedish).说明告诉我创建一个名为Rektangel的 class 变量 x、y、b、h(瑞典语中的长度和宽度)。 Then I should create 16 objects of the type Rectangel and store them in a list.然后我应该创建 16 个Rectangel类型的对象并将它们存储在一个列表中。

I made three classes, named Panel14_1 , Frame14_1 and Rektangel .我做了三个类,分别命名为Panel14_1Frame14_1Rektangel I tried to pull the Panel into the frame but it doesn't work.我试图将面板拉入框架,但它不起作用。 When I run the program, it only opens a window and there are no red rectangles in it...当我运行程序时,它只打开一个 window 并且其中没有红色矩形......

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;
    }
}

Panel控制板

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                   

Hello and welcome to stackoverflow:!您好,欢迎来到stackoverflow:! :D :D

To paint a rectangle use Graphics.fillRect(x,y,w,h) or for just the outline use Graphics.drawRect(x,y,w,h .要绘制矩形,请使用Graphics.fillRect(x,y,w,h)或仅绘制轮廓使用Graphics.drawRect(x,y,w,h )。

If you want them to disappear, then you have to paint your JFrame if you click on a rectangle with the mouse.如果你想让它们消失,那么你必须用鼠标点击一个矩形来绘制你的 JFrame。 I would create a JButton and add an ActionListener.我会创建一个 JButton 并添加一个 ActionListener。

Edit: Overwrite the paintComponent method and not printComponent编辑:覆盖paintComponent方法而不是printComponent

The first thing you need to do is to add the JPanel to the JFrame by: add(new Panel14_1()) .您需要做的第一件事是通过add(new Panel14_1())JPanel添加到JFrame中。 There is no need to set a GroupLayout to the JFrame .无需将GroupLayout设置为JFrame The default ( BorderLayout ) will do the job.默认( BorderLayout )将完成这项工作。 So所以

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 
    }
} 

After implementing those changes you'll see the rectangles.实施这些更改后,您将看到矩形。
In Panel14_1 although overriding printComponent should work you should override paintComponent :Panel14_1尽管覆盖printComponent应该可以工作,但您应该覆盖paintComponent

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


Side note: according to Java Naming conventions Rita(Graphics g) should be rita(Graphics g) 旁注:根据 Java 命名约定Rita(Graphics g)应该是rita(Graphics g)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM