BorderLayout仅显示一个对象 [英] BorderLayout only showing one object

查看:171
本文介绍了BorderLayout仅显示一个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我决定编写一个小的Java程序来尝试BorderLayout,因为我正在开发Java游戏,并且我需要同时在一个JFrame中放置2个对象,所以我问的每个人都说我需要BorderLayout为此.

I decided to write a small Java program to experiment around with BorderLayout, because I'm developing a Java game and I need to have 2 objects placed in a single JFrame at the same time, and everyone I asked said I need BorderLayout to do that.

因此,我编写的Java程序应该在JFrame上放置一个JButton,并且还要放置一个图形组件(在这种情况下为矩形).问题是,只有按钮显示,如下面的图像链接所示:

So the Java program I wrote is supposed to place a JButton on the JFrame and ALSO place a graphic component (a rectangle in this case). The problem is, only the button shows up, as can be seen in the image link below:

http://prntscr.com/3m5ek6

由于信誉统计欠佳,我无法发布实际图像.

I can't post actual images due to my low reputation statistic.

这是代码:

main.java ->主方法类+ JFrame/JPanel/JButton构造函数

main.java --> The main method class + JFrame/JPanel/JButton constructor

import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;


public class main {

public static void main(String[] args) {

    Infout m = new Infout();
    JFrame f = new JFrame();
    JPanel start = new JPanel();
    JPanel start2 = new JPanel();

    start.add(m);
    start2.add(new JButton("Hi"));

    f.add(start,BorderLayout.LINE_START);
    f.add(start2, BorderLayout.LINE_END);
    f.setVisible(true);
    f.setSize(300, 400);

}

}

Infout.java ->矩形构造函数类

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import javax.swing.JPanel;


public class Infout extends JPanel{

public void paintComponent(Graphics g){
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    g2.fill(new Rectangle2D.Double(140, 270, 5, 300));
}

}

有人可以告诉我怎么了吗?另外,使用BorderLayout是向JFrame添加多个静态和/或动态对象的最佳选择吗?

Can someone tell me what's wrong? Also, is using BorderLayout the best option for adding multiple static and/or dynamic objects to a JFrame?

谢谢!

Ab

推荐答案

您需要覆盖getPreferredSize()方法,以便布局管理器可以确定组件的正确大小.

You need to override the getPreferredSize() method so the layout manager can determine the proper size for the component.

How do I do that?

自定义绘画上,从Swing教程中阅读本节.有关自定义绘画的更多信息,包括一个工作示例,该示例演示如何重写getPreferredSize()方法.

Read the section from the Swing tutorial on Custom Painting for more information on custom painting, including a working example that shows how to override the getPreferredSize() method.

这篇关于BorderLayout仅显示一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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