Java JComponent paint - 几乎可以工作 [英] Java JComponent paint --Almost working

查看:91
本文介绍了Java JComponent paint - 几乎可以工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I almost have the repaint() Jcomponent working. I had it working and then tried to make an absolute positioning and now it doesn't work.

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

第2类:(这是我的JComponent试图设置)

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。我认为这应该有效。我有一个设定的首选尺寸。我有一次工作,现在它不起作用。

I added my component to the Container and then added the container to the JPanel and then the JPanel is added to the JFrame. I would think that this should work. I have a set preferred size. I had it working once and now it doesn't work.

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

I want to be able to make a component that is a circle. I want that circle to be able to be drawn any where on a Jframe, and then I want that circle to be able to move based on a a certain length of time. I am going to make a game that has circles dropping from the top and then falling to the bottom. When I had it working I did have the circle being written to the JPanel which is a complex piece of code. But I have had to go back to the old simple method of writing a single graphical word.

推荐答案


  • 当您使用空布局时,完全负责确保添加的组件具有正确的位置并设置 size (而不是preferredSize)。

  • 你几乎不应该使用null布局。

  • 通过创建一个逻辑类来表示Circle而不是组件,这种事情会不会更好?然后你的绘图JPanel可以包含一个逻辑圆的集合,并且绘图JPanel可以负责在其paintComponent方法中绘制每个Circle。



    • When you use null layout, you are completely responsible for making sure that components added have proper location and size (not preferredSize) set.
    • You should almost never use null layout.
    • Wouldn't this sort of thing work better by creating a logical class to represent the Circle, not a component? Then your drawing JPanel could hold a collection of logical circles, and the drawing JPanel could be responsible for drawing each Circle in its paintComponent method.
    • 编辑

      您的评论/我的回复:

      Edit
      Your comments/my replies:


      当你说从不使用绝对布局时,我工作的公司总是只使用绝对布局。

      when you say never use an absolute layout, the company that I worked for always used a absolute layout only.

      有时它很有用,但不适用于创建典型的组件填充GUI。否则,GUI变得非常难以修改和维护。

      There are times when it is useful, but not for creating a typical component-filled GUI. Otherwise the GUI becomes very hard to modify and maintain.


      当你的意思是逻辑类时,你指的是一个只创建一个圆的类。 / p>

      When you mean a logical class you mean a class that just creates one circle.

      是的,它包含该圈子的所有必要属性,例如颜色,位置,移动等。

      Yes, and that holds all the necessary properties of that circle such as its Color, location, movement, etc..


      然后Jpanel将绘制每个圆圈。

      Then the Jpanel would draw each circle.

      是。我想象绘图JPanel有一个 ArrayList< MyCircle> ,而paintComponent方法通过这个List迭代。

      Yes. I would imagine the drawing JPanel having an ArrayList<MyCircle> of them, and the paintComponent method iterating througgh this List.

      当你说Size这是JComponent中的属性时。

      when you say Size this is a property in JComponent.

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

      I think that it is a property of Component, JComponent's parent. If you use null layout, then all components must have their size and location specified. Otherwise the component defaults to a location of [0, 0] and a size of [0, 0].

      编辑2


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

      这是我用于首选大小的代码。我迷失了为什么这不起作用。

      This is the code that I used for the preferred size. I am at a lost why this doesn't work.

      此代码对Component / JComponent的size或preferredSize属性没有影响。它不会让我感到惊讶,它对你没有帮助。您可能必须覆盖 getSize() getPreferredSize()或显式调用 setSize( ...) getPreferredSize(...)更改属性的状态。

      This code has no effect on either the size or the preferredSize properties of Component/JComponent. It doesn't surprise me that it will not help you. You would either have to override getSize() or getPreferredSize() or explicitly call setSize(...) or getPreferredSize(...) to change the state of the properties.


      我将尝试使用不同的布局管理器,但是我会看到一个布局管理器或另一个布局管理器之间的区别。

      I am going to try it with a different layout manager and see but I would see the difference between one layout manager or another.

      我不知道如何解释这个。

      I'm not sure how to interpret this.

      编辑3

      您说:

      Edit 3
      You state:


      我在一家公司工作,我们一直使用绝对布局。绝对布局如何不如BorderLayout()那样好。对我来说,BorderLayout()更难实现。或者是您使用带有BorderLayout的Jframe(),然后将Jpanel插入已经存在且已经是BorderLayout()的现有位置。我总是难以在与BorderLayout()不同的布局中使我的错位和位置正确。你能发布一个比

      I worked at one company and we used absulute layouts all of the time. How would an absolute layout not work as good as, say BorderLayout(). To me the BorderLayout() are harder to implement. Or is it that you use a Jframe() with a BorderLayout, and then insert a Jpanel into an already existing position that is already also a BorderLayout(). I always have trouble getting my buttions and positions correct in a layout that is something different than a BorderLayout(). Can you post an example that would be easier to use than

      我猜你想要一个布局管理器使用位置的例子比使用绝对定位更容易。

      I'm guessing you want an example of where use of layout managers is easier than using absolute positioning.

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

      Let's take the example of a very simple calculator, one with buttons for numeric input and simple operations. Again this example is very basic, and is non-functional, but serves to illustrate the use of layouts. I could easily place my buttons in a GridLayout-using JPanel, and then place that button JPanel into a BorderLayout-using JPanel at the BorderLayout.CENTER position with the JTextField, display, placed in the same BorderLayout-using JPanel at the BorderLayout.PAGE_START position:

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

      这会产生如下计算器:

      This would result in a calculator that looks like so:

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

      Now, sure you could say that you could produce this with null layout and setbounds(...), and that's all well and good, but now say that you're not satisfied with this calculator, and now desire that it has some scientific calculation functionality. Say you now want to add buttons for square, square root, exponential, and logarithm, but not only that, say you wish to add the buttons below the display and above the numeric and basic operations buttons. If you were to do this with null layout, you would have to reposition all the components below and to the right of any new components added, and you'd have to expand the size of the JTextField, all calculations that are tedious and prone to error.

      如果你使用了布局管理器,你只需要添加一行代码,实际上是一个额外的行到数组:

      If you used layout managers, you would instead only need to add one line of code, actually an additional row to an array:

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

      会导致此GUI:

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

      Again this is a very simplistic example, but the general principles apply to any GUI that holds components such as JButtons, JTextComponents, etc.

      这篇关于Java JComponent paint - 几乎可以工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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