简体   繁体   English

Java Swing-如何绘制扩展JComponent的此类

[英]Java Swing - how do i paint this class which extends JComponent

I tried to create a class which extends JComponents, but when i add it to a Box, i can see only an empty window. 我试图创建一个扩展JComponents的类,但是当我将其添加到Box中时,我只能看到一个空窗口。 Can you help me? 你能帮助我吗? What i Expect to get, is a window with 3 horizontal boxes containing a label and a button next to it. 我期望得到的是一个带有3个水平框的窗口,其中包含一个标签和一个按钮。

public class MyWindowComp{
    public MyWindowComp(){

    JFrame frame = new JFrame("myFrame");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel wp = new JPanel(new BorderLayout());

    Box vBox = new Box(BoxLayout.Y_AXIS);

    MyComponent one = new MyComponent();
    MyComponent two = new MyComponent();
    MyComponent three = new MyComponent();

    vBox.add(one);
    vBox.add(two);
    vBox.add(three);

    wp.add(vBox);


    frame.add(wp);
    frame.setVisible(true);
    }}

public class MyComponent extends JComponent {

private Box box;
private JButton b;
private JLabel l;

public MyComponent(){
    this.box = new Box(BoxLayout.X_AXIS);

    this.l = new JLabel ("label");
    this.l.setVisible(true);
    this.b =  new JButton("button");
    this.b.setVisible(true);

    box.add(l);
    box.add(b);

}}

Obtained: 获得: 在此处输入图片说明

Expected: 预期: 在此处输入图片说明

You create instances of MyComponent component, but you never add any components to your component so there is nothing to paint. 您创建了MyComponent组件的实例,但从未将任何组件添加到您的组件中,因此无需绘制任何内容。

In the constructor of your MyComponent classe you create a Box and then you add two components to the Box, but you don't add the Box to your component. 在MyComponent类的构造函数中,创建一个Box,然后将两个组件添加到Box中,但是没有将Box添加到组件中。

The solution is to get rid of the Box and add the button and label directly to your component: 解决方案是摆脱Box并将按钮和标签直接添加到您的组件中:

public MyComponent()
{
    setLayout( new BoxLayout(this, BoxLayout.X_AXIS) );

    l = new JLabel ("label");
    b =  new JButton("button");

    add(l);
    add(b);
}

Also: 也:

  1. there is no need to use setVisible(true) on each components since components are visible by default (except for top level containers like JFrame). 无需在每个组件上使用setVisible(true),因为默认情况下组件是可见的(顶级容器(如JFrame)除外)。
  2. Usually you would extend JPanel , since the purpose of a panel is to contain other components. 通常,您将扩展JPanel ,因为面板的目的是包含其他组件。

Seem like a homework, I will try answer as a teacher 好像是作业,我会尝试作为老师回答

  1. you forgot the method to load your MyWindowComp() method 您忘记了加载MyWindowComp()方法的方法

  2. if it loaded, and it show only menu bar, then you forget to set it size with frame.setSize(x,y); 如果已加载,并且仅显示菜单栏,则您忘记使用frame.setSize(x,y);来设置它的大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM