在Java中,我们可以在子类本身和子类方法之外创建一个子类的对象吗?

发布于 2025-01-23 03:47:09 字数 2237 浏览 0 评论 0原文

我需要在子类本身中创建一个子类的对象,但在子类的所有方法之外。

在下面的代码中,我想在指定的位置创建一个ODRAWPANEL的对象(在代码中注释部分),但是当我这样做时,我会得到一个stackoverflowerror。但是,我可以在display()方法中创建对象odrawpanel毫无问题,但是在这种情况下,我不能在其他方法中使用它。我需要在面板上进行一些绘画,并且面板必须在代码中的任何地方可用。

如何使面板对象在代码中的任何地方可用?

感谢您的帮助。

package odrawpanel;

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

public class ODrawPanel extends JPanel
{ 
    
        private Point p1 = new Point(100, 300);
        private Point p2 = new Point(380, 300);

        // Either
        // JPanel panel = new ODrawPanel();     I want to create the object of the subclass here.
        // or
        // ODrawPanel panel = new ODrawPanel();

        @Override
        protected void paintComponent(Graphics g) 
        {
            super.paintComponent(g);
            g.setColor(Color.BLUE);       
            g.drawLine(p1.x, p1.y, p2.x, p2.y);
                        
        }
         
        public void display() 
        {   
            JPanel panel = new ODrawPanel(); 
            JFrame f = new JFrame();
 
            panel.setBounds(40, 40, 400, 400);    
            panel.setBackground(Color.white); 
            
            f.add(panel);  
            f.setSize(800,600);    
            f.setLayout(null);    
            f.setLocationRelativeTo(null);
            f.setVisible(true); 
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            f.addComponentListener(new ComponentAdapter() 
            {           
                @Override
                public void componentResized(ComponentEvent e) 
                {
                  panel.setSize(f.getWidth()-100,f.getHeight()-100);                                 
                }
        
            });
         
        }
        
        public static void main(String args[])  
        {          
                EventQueue.invokeLater(new Runnable() 
                  {
                      @Override
                      public void run() 
                      {
                         new ODrawPanel().display();                        
                      }
                  });  
        }
        
}  



I need to create an object of a subclass in the subclass itself but outside of all the methods of the subclass.

In the code below, I want to create an object of ODrawPanel at the specified location (commented part in the code) but when I do this, I get a StackOverflowError. However, I can create the object ODrawPanel inside the display() method with no problem but in that case I cannot use it in the other methods. I need to do some drawing on the panel and the panel must be available anywhere in the code.

How can I make the panel object available anywhere in the code?

Thanks for helping.

package odrawpanel;

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

public class ODrawPanel extends JPanel
{ 
    
        private Point p1 = new Point(100, 300);
        private Point p2 = new Point(380, 300);

        // Either
        // JPanel panel = new ODrawPanel();     I want to create the object of the subclass here.
        // or
        // ODrawPanel panel = new ODrawPanel();

        @Override
        protected void paintComponent(Graphics g) 
        {
            super.paintComponent(g);
            g.setColor(Color.BLUE);       
            g.drawLine(p1.x, p1.y, p2.x, p2.y);
                        
        }
         
        public void display() 
        {   
            JPanel panel = new ODrawPanel(); 
            JFrame f = new JFrame();
 
            panel.setBounds(40, 40, 400, 400);    
            panel.setBackground(Color.white); 
            
            f.add(panel);  
            f.setSize(800,600);    
            f.setLayout(null);    
            f.setLocationRelativeTo(null);
            f.setVisible(true); 
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            f.addComponentListener(new ComponentAdapter() 
            {           
                @Override
                public void componentResized(ComponentEvent e) 
                {
                  panel.setSize(f.getWidth()-100,f.getHeight()-100);                                 
                }
        
            });
         
        }
        
        public static void main(String args[])  
        {          
                EventQueue.invokeLater(new Runnable() 
                  {
                      @Override
                      public void run() 
                      {
                         new ODrawPanel().display();                        
                      }
                  });  
        }
        
}  



如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

零度° 2025-01-30 03:47:09

您可以声明JPANEL lazy初始化为类的供应商:

private Point p1 = new Point(100, 300);
private Point p2 = new Point(380, 300);
private final Supplier<JPanel> panelSupplier = new Supplier<>() {

    private JPanel panel;

    @Override
    public JPanel get() {
        if (panel == null) {
            panel = new ODrawPanel();
        }
        return panel;
    }
};

...供应商(您第一次使用它,将创建odrawpanel,但不会导致溢出,因为您不会递归初始化它:

public void display() {
    JPanel panel = panelSupplier.get(); //the first time you call get() it will create the panel, the next times it will reuse it
    JFrame f = new JFrame();

    panel.setBounds(40, 40, 400, 400);
    //...rest of the code

You may declare a JPanel supplier with lazy initialization as a field of the class:

private Point p1 = new Point(100, 300);
private Point p2 = new Point(380, 300);
private final Supplier<JPanel> panelSupplier = new Supplier<>() {

    private JPanel panel;

    @Override
    public JPanel get() {
        if (panel == null) {
            panel = new ODrawPanel();
        }
        return panel;
    }
};

... and then use it all over the class by .get()ting the value from the supplier (the first time you use it, the ODrawPanel will be created but it won't cause an overflow since you're not recursively initializing it:

public void display() {
    JPanel panel = panelSupplier.get(); //the first time you call get() it will create the panel, the next times it will reuse it
    JFrame f = new JFrame();

    panel.setBounds(40, 40, 400, 400);
    //...rest of the code
听你说爱我 2025-01-30 03:47:09

我将为main(),jframe,jpanel创建不同的类。

主要:
new Jframe();

在Jframe中:
添加(new Jpanel());
...

在jpanel:
不要在这里创建jpanels。
...

I would create different classes for the main(), the JFrame, the JPanel.

In Main:
new JFrame();

In JFrame:
add(new JPanel());
...

In JPanel:
Do not create JPanels here.
...

昔日梦未散 2025-01-30 03:47:09

Matteo,谢谢您的代码。当我尝试使用时,我会收到以下编译器错误:

private final Supplier<JPanel> panelSupplier = new Supplier<>()
{
   // some code here.
};
"cannot infer type arguments for Supplier<T>
  reason: '<>' with anonymous inner classes is not supported in -source 8
    (use -source 9 or higher to enable '<>' with anonymous inner classes)
  where T is a type-variable:
    T extends Object declared in interface Supplier"

将代码更改为:

private final Supplier<JPanel> panelSupplier = new Supplier<JPanel>()
{
  // some code here.
}

我没有收到错误。例如,它在这样的方法中起作用:

public void Test()
{
  JPanel panel = panelSupplier.get();
  panel.setBackground(Color.RED);
}

但是它在方法中没有影响:

protected void paintComponent(Graphics g) 
{
   super.paintComponent(g);
   g.setColor(Color.BLUE);       
   g.drawLine(p1.x, p1.y, p2.x, p2.y);
            
   JPanel panel = panelSupplier.get();
   panel.setBackground(Color.CYAN); 
}

Matteo, thank you for the code. When I tried it, I got the following compiler error for the line:

private final Supplier<JPanel> panelSupplier = new Supplier<>()
{
   // some code here.
};
"cannot infer type arguments for Supplier<T>
  reason: '<>' with anonymous inner classes is not supported in -source 8
    (use -source 9 or higher to enable '<>' with anonymous inner classes)
  where T is a type-variable:
    T extends Object declared in interface Supplier"

After changing the code to:

private final Supplier<JPanel> panelSupplier = new Supplier<JPanel>()
{
  // some code here.
}

I did not receive an error. It works, for example, in a method like:

public void Test()
{
  JPanel panel = panelSupplier.get();
  panel.setBackground(Color.RED);
}

But it has no effect in the method:

protected void paintComponent(Graphics g) 
{
   super.paintComponent(g);
   g.setColor(Color.BLUE);       
   g.drawLine(p1.x, p1.y, p2.x, p2.y);
            
   JPanel panel = panelSupplier.get();
   panel.setBackground(Color.CYAN); 
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文