0
这里的顶部创建一个按钮是一段代码:无法在一个矩形
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class QuitButton extends JPanel implements ActionListener
{
static JButton button = new JButton("Panic");
Color[] colors = new Color[9];
boolean pressed = false;
public QuitButton()
{
button.addActionListener(this);
colors[0] = Color.RED;
colors[1] = Color.BLUE;
colors[2] = Color.GREEN;
colors[3] = Color.YELLOW;
colors[4] = Color.BLACK;
colors[5] = Color.PINK;
colors[6] = Color.MAGENTA;
colors[7] = Color.ORANGE;
colors[8] = Color.CYAN;
}
@Override
public void actionPerformed(ActionEvent e)
{
pressed = true;
}
public static void main(String args[])
{
JFrame frame = new JFrame("Do NOT Panic!!");
QuitButton qb = new QuitButton();
frame.add(qb);
frame.add(button);
frame.setLayout(new FlowLayout());
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
//frame.pack();
button.requestFocus();
qb.gameLoop();
}
public void gameLoop()
{
while (true)
{
repaint();
try
{
Thread.sleep(200);
} catch (Exception e)
{
}
}
}
public void paint(Graphics g)
{
Graphics2D g2d = (Graphics2D) g;
if (pressed == false)
{
super.paint(g2d);
g2d.setColor(Color.GRAY);
g2d.fillRect(0, 0, 400, 400);
} else
{
super.paint(g2d);
Random r = new Random();
int min = 0;
int max = 8;
int index = r.nextInt(max - min) + min;
g2d.setColor(colors[index]);
g2d.fillRect(0, 0, 400, 400);
}
}
这项计划的目的:矩形应该是灰色的前,但是当我点击恐慌按钮颜色应该开始改变。
请不要混淆QuitButton类的名称。
但我的矩形不占用整个窗口。相反,我得到这样一个小小的矩形:http://g.recordit.co/xJAMiQu6fM.gif 我认为这是因为我使用的布局,我没有指定任何地方的按钮将在上面。可能这就是他们并肩而坐的原因。我不熟悉GUI创建,并感谢您的帮助。
对不起,但请解释组件的首选大小是如何为0,0或接近它。我还想提一下,由于某些原因,我并不是在回顾这篇特定的教程。我遵循的教程看起来很生涩。他们从事情跳到事情没有解释太多,我发现自己只是在不做任何事情的情况下完成他们的描述 –
@IshanSrivastava:也许我错过了你的代码中的东西 - 我没有我的IDE在这里,但是*你在哪里设置组件的preferredSize或覆盖'getPreferredSize()'?再一次,我可能错过了这个,所以请耐心等待。 –
@IshanSrivastava:遵循教程的最佳方式是试验他们给你的代码。玩它,然后尝试将其纳入你自己,我相信你会得到它。 –