ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

java-是否有更好的方法来设置JPanel图形的初始位置?)

2019-10-12 07:03:35  阅读:243  来源: 互联网

标签:java event-handling swing jpanel mouseevent


在Liang的Java编程简介(第7版)的第15章中,他介绍了一个程序,该程序可以在JPanel上制作一个(2-D)球,并在单击“放大/缩小”按钮时对其进行放大.我已经修改了程序,使其也可以:1)如果用户单击/选项单击,则放大/缩小球; 2)允许您通过按按钮选择球的颜色; 3)​​允许移动圆用鼠标拖动它.

最后的修改是给我一段时间带来麻烦的,因为我想在开始时将球居中,但随后允许用户用鼠标来移动球.我想出的解决方案是让paintComponent方法仅在第一次绘制时相对于getWidth()和getHeight()设置球的x和y坐标.为此,我在BallCanvas类中添加了一个paintCount变量,并创建了一个if语句,使其仅在第一次执行.当我最初试图弄清楚该怎么做时,我看到了其他解决方案,例如此处给出的解决方案:Why can’t I access my panel’s getWidth() and getHeight() functions?,但我发现我的解决方案要简单得多.

所以问题是:我认为编码风格不好吗?专业的程序员会嘲笑这种解决方案吗?还是可以吗?

更重要的是,是否有一种更好的(但也相对简单)的方法可以完成,而又不需要设置计数器?

以下是相关的代码位:

BallCanvas的开始:

public static class BallCanvas extends JPanel {

    private int radius = 20;
    private Color color = Color.BLACK;
    private int ballX;
    private int ballY;
    private int paintCount = 0;

    ...

move方法(响应MouseDragged事件):

public void move(MouseEvent e){

        ballX = e.getX() - radius;
        ballY = e.getY() - radius;
        repaint();

}

paintComponent方法:

protected void paintComponent(Graphics g){

        super.paintComponent(g);
        g.setColor(color);
        if(paintCount < 1){
            ballX = getWidth()/2 - radius;
            ballY = getHeight()/2 - radius;
        }
        g.fillOval(ballX, ballY, 2*radius, 2*radius);
        paintCount++;

}

完整程序:

// Reference: Liang's Intro to Java Programming

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ControlBall extends JFrame{

    private JButton jbtRed = new JButton("Red");
    private JButton jbtGreen = new JButton("Green");
    private JButton jbtBlue = new JButton("Blue");
    private JButton jbtBlack = new JButton("Black");
    private BallCanvas canvas = new BallCanvas();
    private JMenuBar menuBar = new JMenuBar();
    private JMenu menu = new JMenu("Edit");
    private JMenuItem miEnlarge = new JMenuItem("Enlarge");
    private JMenuItem miShrink = new JMenuItem("Shrink");

    public ControlBall(){

        menuBar.add(menu);
        menu.add(miEnlarge);
        menu.add(miShrink);

        JPanel panel = new JPanel();
        panel.add(jbtRed);
        panel.add(jbtGreen);
        panel.add(jbtBlue);
        panel.add(jbtBlack);

        this.add(canvas, BorderLayout.CENTER);
        this.add(panel, BorderLayout.SOUTH);
        this.add(menuBar, BorderLayout.NORTH);

        jbtRed.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e){
                canvas.setColor(Color.RED);
            }
        });

        jbtGreen.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e){
                canvas.setColor(Color.GREEN);
            }
        });

        jbtBlue.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e){
                canvas.setColor(Color.BLUE);
            }
        });

        jbtBlack.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e){
                canvas.setColor(Color.BLACK);
            }
        });

        miEnlarge.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e){ 
                canvas.enlarge();
            }
        });

        miShrink.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e){ 
                canvas.shrink();
            }
        });

        canvas.addMouseListener(new MouseListener() {
            public void mouseClicked(MouseEvent e){
                canvas.changeSize(e);
            }
            public void mousePressed(MouseEvent e){}
            public void mouseReleased(MouseEvent e){}
            public void mouseEntered(MouseEvent e){}
            public void mouseExited(MouseEvent e){}
        });

        canvas.addMouseMotionListener(new MouseMotionAdapter() {

            public void mouseDragged(MouseEvent e) {

                canvas.move(e);

            }
        });

    }

    public static void main(String[] args){

        JFrame frame = new ControlBall();
        frame.setTitle("ControlBall");
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 200);
        frame.setVisible(true);

    }

    public static class BallCanvas extends JPanel {

        private int radius = 20;
        private Color color = Color.BLACK;
        private int ballX;
        private int ballY;
        private int paintCount = 0;

        public BallCanvas(){

            System.out.println(getWidth() + " " + getHeight());

        }

        public BallCanvas(int initialRadius){

            radius = initialRadius;

        }

        public void setColor(Color color){

            this.color = color;
            repaint();

        }

        public void changeSize(MouseEvent e){

            int numClicks = e.getClickCount();

            if(e.isAltDown()){
                if(radius >= 6){
                    this.radius -= 5*numClicks;
                } else{
                    // do nothing
                }
            } else{

                this.radius += 5*numClicks;
            }

            repaint();

        }

        public void enlarge(){

            this.radius += 5;
            repaint();

        }

        public void shrink(){

            if(radius >= 10){
                this.radius -= 5;
            }
            repaint();
        } 

        public void move(MouseEvent e){

            ballX = e.getX() - radius;
            ballY = e.getY() - radius;
            repaint();

        }

        protected void paintComponent(Graphics g){

            super.paintComponent(g);
            g.setColor(color);
            if(paintCount < 1){
                ballX = getWidth()/2 - radius;
                ballY = getHeight()/2 - radius;
            }
            g.fillOval(ballX, ballY, 2*radius, 2*radius);
            paintCount++;

        }

    }

}

解决方法:

需要注意以下几点:

>覆盖getPreferredSize()以建立面板的初始几何.
>使用该几何形状确定球的初始位置.
>调用pack(),然后设置位置&能见度.
>使用Action封装菜单和控件共享的代码.
>始终使用适配器.
>正确使用initial threads.
>请参阅此Q&A,它从多个角度研究了一个相关示例.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ControlBall extends JFrame {

    private JButton jbtRed = new JButton("Red");
    private JButton jbtGreen = new JButton("Green");
    private JButton jbtBlue = new JButton("Blue");
    private JButton jbtBlack = new JButton("Black");
    private BallCanvas canvas = new BallCanvas();
    private JMenuBar menuBar = new JMenuBar();
    private JMenu menu = new JMenu("Edit");
    private JMenuItem miEnlarge = new JMenuItem("Enlarge");
    private JMenuItem miShrink = new JMenuItem("Shrink");

    public ControlBall() {

        menuBar.add(menu);
        menu.add(miEnlarge);
        menu.add(miShrink);

        JPanel panel = new JPanel();
        panel.add(jbtRed);
        panel.add(jbtGreen);
        panel.add(jbtBlue);
        panel.add(jbtBlack);

        this.add(canvas, BorderLayout.CENTER);
        this.add(panel, BorderLayout.SOUTH);
        this.add(menuBar, BorderLayout.NORTH);

        jbtRed.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                canvas.setColor(Color.RED);
            }
        });

        jbtGreen.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                canvas.setColor(Color.GREEN);
            }
        });

        jbtBlue.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                canvas.setColor(Color.BLUE);
            }
        });

        jbtBlack.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                canvas.setColor(Color.BLACK);
            }
        });

        miEnlarge.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                canvas.enlarge();
            }
        });

        miShrink.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                canvas.shrink();
            }
        });

        canvas.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                canvas.changeSize(e);
            }

            @Override
            public void mouseDragged(MouseEvent e) {
                canvas.move(e);
            }
        });
    }

    public static void main(String[] args) {

        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new ControlBall();
                frame.setTitle("ControlBall");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });

    }

    public static class BallCanvas extends JPanel {

        private static final int SIZE = 400;
        private int radius = 20;
        private Color color = Color.BLACK;
        private int ballX = SIZE / 2 - radius;
        private int ballY = SIZE / 2 - radius;

        public BallCanvas() {
            System.out.println(getWidth() + " " + getHeight());
        }

        public BallCanvas(int initialRadius) {
            radius = initialRadius;
        }

        public void setColor(Color color) {
            this.color = color;
            repaint();
        }

        public void changeSize(MouseEvent e) {

            int numClicks = e.getClickCount();

            if (e.isAltDown()) {
                if (radius >= 6) {
                    this.radius -= 5 * numClicks;
                } else {
                    // do nothing
                }
            } else {

                this.radius += 5 * numClicks;
            }

            repaint();

        }

        public void enlarge() {

            this.radius += 5;
            repaint();

        }

        public void shrink() {

            if (radius >= 10) {
                this.radius -= 5;
            }
            repaint();
        }

        public void move(MouseEvent e) {

            ballX = e.getX() - radius;
            ballY = e.getY() - radius;
            repaint();

        }

        @Override
        protected void paintComponent(Graphics g) {

            super.paintComponent(g);
            g.setColor(color);
            g.fillOval(ballX, ballY, 2 * radius, 2 * radius);

        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(SIZE, SIZE);
        }
    }
}

标签:java,event-handling,swing,jpanel,mouseevent
来源: https://codeday.me/bug/20191012/1898529.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有