gpt4 book ai didi

java - 代码完全按计划工作,但我仍然遇到异常?

转载 作者:行者123 更新时间:2023-11-30 08:53:47 24 4
gpt4 key购买 nike

今天这件事让我很头疼,但我认为这很容易解决。该程序创建了一个包含三个按钮的框架,这些按钮根据按下的按钮更改该框架的背景颜色。

程序运行,出现一个框架,我点击“红色”。将剩余的 2 种颜色变为红色,反之亦然,但是当我运行该程序时,出现此错误:

Exception in thread "main" java.lang.IllegalArgumentException: adding a window to a container
at java.awt.Container.checkNotAWindow(Unknown Source)
at java.awt.Container.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at javax.swing.JFrame.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at ThreeColorsViewer.main(ThreeColorsViewer.java:11)

代码:

 import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
This frame contains a panel that display one of three colors
specified by the user.
*/
public class ThreeColorsFrame extends JFrame {
private JPanel colorPanel;
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 300;

public ThreeColorsFrame()
{
setSize(FRAME_WIDTH, FRAME_HEIGHT);
colorPanel = new JPanel();
add(colorPanel, BorderLayout.CENTER);

createControlPanel();
}

/**
Creates the control panel with buttons at the bottom of the frame.
*/
private void createControlPanel()
{
JPanel southPanel = new JPanel();
southPanel.add(makeButton("Red", Color.RED));
southPanel.add(makeButton("Green", Color.GREEN));
southPanel.add(makeButton("Blue", Color.BLUE));

add(southPanel, BorderLayout.SOUTH);
}

/**
Makes a button to change the color of the panel.
@param label the button label
@param color the color to set
@return the button to change the color of the panel
*/
public JButton makeButton(String label, final Color color)
{
JButton button = new JButton(label);

class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
colorPanel.setBackground(color);
}
}

ButtonListener listener = new ButtonListener();
button.addActionListener(listener);
return button;
}
}

然后我有一个“查看器类”

import javax.swing.JFrame;

public class ThreeColorsViewer {
public static void main(String[] args){

JFrame viewer = new JFrame();
ThreeColorsFrame viewerFrame = new ThreeColorsFrame();

viewerFrame.setVisible(true);
viewer.add(viewerFrame);
}
}

最佳答案

您不需要将 ThreeColorsFrame 添加到另一个 JFrame。它本身已经是一个 JFrame。这应该有效。

public class ThreeColorsViewer {
public static void main(String[] args){
ThreeColorsFrame viewerFrame = new ThreeColorsFrame();
viewerFrame.setVisible(true);
}
}

关于java - 代码完全按计划工作,但我仍然遇到异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29674483/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com