小编典典

Java JComponent绘制-几乎可以使用

java

我几乎让repaint()Jcomponent工作了。我让它正常工作,然后
尝试进行绝对定位,但现在不起作用。

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;

public class DDHGenericFrame {
        private static final long serialVersionUID = 1L;
        DDHGenericPanel d = new DDHGenericPanel(); 
        //DDHCircleOne o = new DDHCircleOne();

        public DDHGenericFrame() {
            initUI();
        }

        public final void initUI() {
              JFrame frame = new JFrame("AbsoluteLayoutDemo");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setTitle("Draw Circle");
              frame.setBackground(Color.green);
              frame.setLayout(null);
              frame.setSize(300,425);
              frame.add(d);
//            frame.add(o);//didn't work neither
              frame.setVisible(true);
        }

        public static void main(String[] args) {
            DDHGenericFrame ex = new DDHGenericFrame();
        }
}

Class 2: (This is the JComponent that I am trying to set)

import java.awt.Dimension;
import java.awt.Graphics;

import javax.swing.JComponent;

public class DDHTestDraw extends JComponent {
    public DDHTestDraw () {
        settPreferredSize();
    }

    public void settPreferredSize() {
        Dimension d = new Dimension(25,25);
        setPreferredSize(d);
    }

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawString("Text",20,20);
    }
}

我将组件添加到Container中,然后将容器添加到JPanel中,然后将JPanel添加到JFrame中。我认为这
应该可行。我有设定的首选尺寸。我曾经使它工作一次,但现在却不起作用。

我希望能够制作一个圆形的组件。我希望该圆圈能够在Jframe的任何位置绘制,然后希望该圆圈能够基于一定的时间长度移动。我要制作一个游戏,它的圆圈从顶部下降,然后下降到底部。当我工作时,确实将圆写到了JPanel,这是一个
复杂的代码。但是我不得不回到以前写单个图形单词的简单方法。


阅读 257

收藏
2020-11-23

共1个答案

小编典典

  • 当使用空布局时,您完全有责任确保所添加的组件设置了正确的位置和大小(而不是preferredSize)。
  • 您几乎永远不应使用空布局。
  • 通过创建一个逻辑类来表示Circle,而不是组件,这种事情会更好吗?然后,您的绘图JPanel可以容纳逻辑圆的集合,并且绘图JPanel可以负责在其paintComponent方法中绘制每个Circle。

编辑
您的评论/我的回复:

当您说从不使用绝对布局时,我所服务的公司
始终仅使用绝对布局。

有时它很有用,但对于创建典型的组件
填充GUI却没有用。否则,GUI变得很难修改和维护。

当您指的是逻辑类时,您的意思是仅创建一个圆的类。

是的,并且拥有该圆的所有必要属性,例如其
颜色,位置,运动等。

然后,Jpanel将绘制每个圆。

是。我会想象有一个绘图JPanel中ArrayList的他们,和的paintComponent方法迭代througgh名单。

当您说Size时,这是JComponent中的一个属性。

我认为这是JComponent的父组件Component的属性。如果使用空布局,则所有组件都必须
指定其大小和位置。否则,组件默认为位置[0,0],大小为[0,0]。


Edit 2

public Dimension Size(int a, int b) {
   Dimension d = new Dimension();
   d.width = a;
   d.height = b;
   return d;
}

此代码对
Component / JComponent的大小或preferredSize属性都没有影响。它不会帮您,这并不令我感到惊讶。你
要么必须重写getSize()或getPreferredSize()或
显式调用setSize(…)或getPreferredSize(…)改变状态
的属性。

我将尝试与其他布局管理器一起尝试,但是我会看到
一个或另一个布局管理器之间的区别。

我不确定如何解释这一点。

编辑3
您声明:

我在一家公司工作,我们一直都在使用粗略的布局。
绝对布局如何不如BorderLayout()那样好。对我来说,
BorderLayout()很难实现。还是您将Jframe()
与BorderLayout一起使用,然后将Jpanel插入到已经
是BorderLayout()的现有位置中。我总是很难
在与
BorderLayout()不同的布局中正确设置自己的位置和位置。您能发布一个
比使用起来容易的示例吗?

我猜想您想要一个示例,其中使用布局管理器
比使用绝对定位更容易。

让我们以一个非常简单的计算器为例,它带有用于
数字输入和简单操作的按钮。同样,该示例非常基础,并且
不起作用,但是用于说明布局的使用。我可以轻松地
将按钮放置在使用GridLayout的JPanel中,然后将该按钮
JPanel
放置在BorderLayout.CENTER位置的BorderLayout-使用JPanel中,并显示JTextField,并显示在同一BorderLayout-使用JPanel
的BorderLayout.PAGE_START上位置:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.*;

public class CalcEg {
   private static final float BTN_FONT_SIZE = 20f; 
   private static final String[][] BTN_LABELS = {
      {"7", "8", "9", "-"},
      {"4", "5", "6", "+"},      
      {"1", "2", "3", "/"},
      {"0", ".", " ", "="}
   };
   private static final int GAP = 4;
   private JPanel mainPanel = new JPanel(new BorderLayout(GAP, GAP));
   private JPanel buttonPanel = new JPanel();
   private JTextField display = new JTextField();

   public CalcEg() {
      int rows = BTN_LABELS.length;
      int cols = BTN_LABELS[0].length;
      buttonPanel.setLayout(new GridLayout(rows, cols, GAP, GAP));
      for (String[] btnLabelRow : BTN_LABELS) {
         for (String btnLabel : btnLabelRow) {
            if (btnLabel.trim().isEmpty()) {
               buttonPanel.add(new JLabel());
            } else {
               JButton btn = createButton(btnLabel);
               buttonPanel.add(btn);
            }
         }
      }
      display.setFont(display.getFont().deriveFont(BTN_FONT_SIZE));
      display.setEditable(false);
      display.setFocusable(false);
      display.setBackground(Color.white);

      mainPanel.setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
      mainPanel.add(buttonPanel, BorderLayout.CENTER);
      mainPanel.add(display, BorderLayout.PAGE_START);
   }

   private JButton createButton(String btnLabel) {
      JButton button = new JButton(btnLabel);
      button.setFont(button.getFont().deriveFont(BTN_FONT_SIZE));
      return button;
   }

   public JComponent getMainComponent() {
      return mainPanel;
   }

   private static void createAndShowGui() {
      CalcEg mainPanel = new CalcEg();

      JFrame frame = new JFrame("CalcEg");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel.getMainComponent());
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

现在,您可以肯定地说可以使用null布局和来生成它
setbounds(…),这很好,但是现在您说您
对该计算器不满意,现在希望它具有一些科学的
计算功能。假设您现在要添加平方,
平方根,指数和对数
的按钮,但不仅限于此,还说您希望将按钮添加到显示屏下方,数字和基本操作
按钮上方。如果要使用null布局进行此操作,则必须将
所有组件重新定位在添加的任何新组件的下方和右侧,并且
必须扩展JTextField的大小,所有
繁琐且易于计算的计算错误。

如果使用布局管理器,则只需要添加一行
代码,实际上是向数组添加一行:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.*;

public class CalcEg {
   private static final float BTN_FONT_SIZE = 20f; 
   private static final String[][] BTN_LABELS = {
      {"sqr", "sqrt", "exp", "log"}, // ******* Line Added Here *********
      {"7", "8", "9", "-"},
      {"4", "5", "6", "+"},      
      {"1", "2", "3", "/"},
      {"0", ".", " ", "="}
   };
   private static final int GAP = 4;
   private JPanel mainPanel = new JPanel(new BorderLayout(GAP, GAP));
   private JPanel buttonPanel = new JPanel();
   private JTextField display = new JTextField();

   public CalcEg() {
      int rows = BTN_LABELS.length;
      int cols = BTN_LABELS[0].length;
      buttonPanel.setLayout(new GridLayout(rows, cols, GAP, GAP));
      for (String[] btnLabelRow : BTN_LABELS) {
         for (String btnLabel : btnLabelRow) {
            if (btnLabel.trim().isEmpty()) {
               buttonPanel.add(new JLabel());
            } else {
               JButton btn = createButton(btnLabel);
               buttonPanel.add(btn);
            }
         }
      }
      display.setFont(display.getFont().deriveFont(BTN_FONT_SIZE));
      display.setEditable(false);
      display.setFocusable(false);
      display.setBackground(Color.white);

      mainPanel.setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
      mainPanel.add(buttonPanel, BorderLayout.CENTER);
      mainPanel.add(display, BorderLayout.PAGE_START);
   }

   private JButton createButton(String btnLabel) {
      JButton button = new JButton(btnLabel);
      button.setFont(button.getFont().deriveFont(BTN_FONT_SIZE));
      return button;
   }

   public JComponent getMainComponent() {
      return mainPanel;
   }

   private static void createAndShowGui() {
      CalcEg mainPanel = new CalcEg();

      JFrame frame = new JFrame("CalcEg");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel.getMainComponent());
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

再次,这是一个非常简单的示例,但是一般原理适用于
任何包含JButtons,JTextComponents等组件的GUI。

2020-11-23