简体   繁体   English

如何将宽度,高度设置为Jframe?

[英]How do I set width, height to a Jframe?

Hello im trying to make it so my getwidth and getheight can be automatically asigned from my Jframe 您好我正在尝试这样做,以便我的getwidth和getheight可以从我的Jframe自动分配

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import javax.swing.JComponent;
import java.awt.GradientPaint;
import java.awt.Polygon;
import java.awt.*;

/*
   component that draws the concert background
*/
public class Concertbackground
{  
    public void draw(Graphics g)
    {   
        // Recover Graphics2D 
        Graphics2D g2 = (Graphics2D) g;    
        //Background Top
        g2.setColor(Color.BLUE);
        Rectangle backgroundTop = new Rectangle (0, 0, getWidth(), getHeight() / 2); 
        g2.fill(backgroundTop);    
        // Background bottom
        g2.setColor(Color.GREEN);
        Rectangle backgroundBottom = new Rectangle (0, getHeight() / 2, getWidth(), getHeight() / 2); 
        g2.fill(backgroundBottom);
    }    
}

JFrame part JFrame部分

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

public class Concert
{
   public static void main(String[] args)
   {
      JFrame frame = new JFrame();
      frame.setSize(1000, 800);
      frame.setTitle("Concert!");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    
      ConcertComponent component = new ConcertComponent();
      frame.add(component);    
      frame.setVisible(true);
   }       
}

Part that actually draws the classes I create 实际绘制我创建的类的部分

import java.awt.Graphics;
import javax.swing.JComponent;


public class ConcertComponent
{
    public void paintComponent(Graphics g)
    {
        ConcertSpeaker speaker1 = new ConcertSpeaker(400, 300);
        speaker1.draw(g);    
        ConcertSpeaker speaker2 = new ConcertSpeaker(0, 0);
        speaker2.draw(g);          
      Concertbackground background1 = new Concertbackground();
      background1.draw(g);           
    }    
}

If I am unclear basically i want to make my getheight and getwidth equal to the Jframe size regaurdless of what its set or changed to 如果我基本上不清楚,我想使我的getheight和getwidth等于Jframe大小,而不管其设置或更改为什么

frame.add(component);

is wrong. 是错的。 Please refer to Oracle's online doc about add and Component . 请参考Oracle的在线文档有关addComponent的信息

java.lang.Object java.lang.Object继承

  java.awt.Component java.awt.Container javax.swing.JComponent 

As a conveniance add and its variants, remove and setLayout have been overridden to forward to the contentPane as necessary. 为方便起见,add和setLayout被覆盖,可以根据需要转发到contentPane。 This means you can write: 这意味着您可以编写:

  frame.add(child); 

And the child will be added to the contentPane. 并将子级添加到contentPane中。

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

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