如何在 Java 中绘制一个正好位于小程序窗口中心的实心方框? [英] How to draw a filled square box in Java that is exactly in the center of an applet window?

查看:24
本文介绍了如何在 Java 中绘制一个正好位于小程序窗口中心的实心方框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Java 中绘制一个正好位于小程序窗口中心的实心方框?当调整窗口大小时,它在小程序窗口内水平和垂直居中?我希望它适应屏幕的垂直高度,但即使水平宽度边缘也保持方形.如果窗口调整得太窄,那么侧面可能会被切断?

How do you draw a filled square box in Java that is exactly in the center of an applet window? and when resizing the window, it is centered horizontally and vertically within the applet window? I want it to adapt to the vertical height of the screen but stay square even as the horizontal width edges. If the window is resized to be too narrow, then the sides might cut off?

推荐答案

下面是一个面板示例,该面板将在中间创建一个 30 像素的正方形,或者随面板调整大小.或许它可以给你足够的进步.

Here's an example of a panel that will either make a 30px square in the middle, or resize with the panel. Perhaps it can give you enough to make progress.

  private class MyPanel extends JPanel{
    int height = 30;//30 pixels high.
    int width = 30;//30 pixels wide.
    boolean resize = true;


    @Override
    protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      int verticalCenter = this.getHeight()/2;
      int horizontalCenter = this.getWidth()/2;

      if(!resize){
        int topLeftSquareCornerY = verticalCenter - (height/2);
        int topLeftSquareCornerX = horizontalCenter - (width/2);

        g.setColor(Color.BLUE);
        g.drawRect(topLeftSquareCornerX, topLeftSquareCornerY, width, height);
      }else{
        g.setColor(Color.GREEN);
        g.drawRect(15,15,(this.getWidth()-30), this.getHeight()-30);
      }
    }
  }

这篇关于如何在 Java 中绘制一个正好位于小程序窗口中心的实心方框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆