您好,我正在尝试这样做,以便可以从我的 Jframe 自动分配我的 getwidth 和 getheight
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部分
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);
}
}
实际绘制我创建的类的部分
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);
}
}
如果我不清楚基本上我想让我的 getheight 和 getwidth 等于 Jframe 大小而不管它的设置或更改为什么