我为你做了一个示例程序,让我知道,如果你想要的东西以外的东西。我已经完成了这两种方式,你可以通过按下JButton在JPanel上设置一个没有任何项目的新颜色,或者你可以先将Item添加到JPanel,然后更改背景颜色,这工作正常。似乎你的问题有点不清楚,究竟是什么,以及实际发生了什么。如果你想要别的东西,请告诉我,除此之外。
而且,你将项目添加到已显示的JPanel,总是重新验证()和后重绘()您的JPanel,更改生效。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class AddItemOrColor extends JFrame
{
private JPanel contentPane;
private JButton modifyItemButton;
private JButton modifyColorButton;
private ActionListener action;
private int count = 0;
private Color[] color = {
Color.RED, Color.BLUE, Color.GRAY,
Color.WHITE, Color.CYAN, Color.PINK,
Color.DARK_GRAY, Color.ORANGE, Color.MAGENTA
};
public AddItemOrColor()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
contentPane = new JPanel(new FlowLayout(FlowLayout.LEFT, 3, 3));
//contentPane.setMargin(new Insets(10, 10, 10, 10));
contentPane.setBackground(Color.BLUE);
modifyItemButton = new JButton("MODIFY CONTENT");
modifyColorButton = new JButton("MODIFY COLOR");
action = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
JButton button = (JButton) ae.getSource();
if (count == 9)
count = 0;
if (button == modifyItemButton)
{
contentPane.add(new JLabel("LABEL " + count));
}
else if (button == modifyColorButton)
{
contentPane.setBackground(color[count]);
}
contentPane.revalidate();
contentPane.repaint();
count++;
}
};
modifyItemButton.addActionListener(action);
modifyColorButton.addActionListener(action);
add(modifyColorButton, BorderLayout.PAGE_START);
add(contentPane, BorderLayout.CENTER);
add(modifyItemButton, BorderLayout.PAGE_END);
setSize(400, 400);
setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new AddItemOrColor();
}
});
}
}
好的代码为OP + 1 – mKorbel 2012-03-06 08:56:40
@mKorbel:Thankyou :-) – 2012-03-06 08:58:00