我有以下代码。 KochSnowflakesMenu 类是一个带有三个按钮的网格 JPanel。 KochSnowflakesDraw 类当前使用 drawOval 绘制圆形:
import javax.swing.*;
import java.awt.*;
public class KochSnowflakes
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Koch Snowflakes");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(0,0, 600, 425);
frame.setBackground(Color.BLACK);
frame.setResizable(false);
frame.setLayout(null);
// Create the button interface
frame.add(new KochSnowflakesMenu());
frame.add(new KochSnowflakesDraw());
frame.repaint();
}
}
如果我注释掉frame.setResizable(false),这会起作用。当我不这样做时,按钮不会出现。这是为什么?正如你所看到的,我尝试过使用 repaint()。我以前遇到过这样的问题:除非我手动调整窗口大小,否则按钮不会显示...
另外,作为一个额外的问题,如果有人能告诉我如何获取 JPanel 的尺寸,那就太好了。我无法使用像 BorderLayout 这样可调整大小的布局管理器(这正是我想要使用的)的原因是我无法计算出占据中心的 JPanel 的尺寸(因此不知道如何放大我正在绘制的内容)。
编辑: 根据要求,这里是 KockSnowflakesMenu 类:
import javax.swing.*;
import java.awt.*;
public class KochSnowflakesMenu extends JPanel
{
public KochSnowflakesMenu()
{
setLayout(new GridLayout(3,1));
setBounds(0,0,200,400);
JButton button_red = new JButton("Red");
JButton button_yellow = new JButton("Yellow");
JButton button_blue = new JButton("Blue");
add(button_red);
add(button_yellow);
add(button_blue);
}
}
并且,为了确保我没有搞砸 KochSnowflakesDraw,这也是该类:
import javax.swing.*;
import java.awt.*;
public class KochSnowflakesDraw extends JPanel
{
public KochSnowflakesDraw()
{
setLayout(null);
setBounds(200, 0, 400, 400);
}
public void paintComponent(Graphics g)
{
g.setColor(Color.RED);
g.drawOval(0,0,400, 400);
}
}
最佳答案
一般来说,使用 JFrame 时,您应该使用 contentPane,而不是 JFrame 本身,因此要添加项目,请尝试
frame.getContentPane().add(.....);
对于您的第一个问题,请尝试在您的 JFrame 上使用 pack。 http://download.oracle.com/javase/1.4.2/docs/api/java/awt/Window.html#pack ()
对于你的额外问题,JComponent 有一个 getWidth 和 getHeight 方法。这将告诉您 JPanel 的当前大小。
http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/JComponent.html#getWidth ()
关于Java Swing 应用程序 - 如果调整大小设置为 false,则按钮不会出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4287160/