我已经明白了这个问题:当你点击下一个按钮时,分配是制作四个不同的广告,当你到达第4个时,绕到第一个。我不知道为什么它是没有回来?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class advertisementPanel extends JPanel {
public advertisementPanel() throws IOException{
setPreferredSize(new Dimension(500, 200));
URL url = new URL("http://www.geneca.com/wp-content/uploads/2013/03/mcdonalds-small-logo1.png");
URL url2 = new URL("http://www.eatthis.com/uploads/wendys.jpg");
URL url3 = new URL("http://www.scaredmonkeys.com/fun-images/KFC_20old_small.jpg");
URL url4 = new URL("http://www.canaltagroup.com/images/aw_logo.gif");
Image image = ImageIO.read(url);
ImageIcon myIcon = new ImageIcon(image);
JLabel adPicture1 = new JLabel(myIcon);
Image image2 = ImageIO.read(url2);
ImageIcon myIcon2 = new ImageIcon(image2);
JLabel adPicture2 = new JLabel(myIcon2);
Image image3 = ImageIO.read(url3);
ImageIcon myIcon3 = new ImageIcon(image3);
JLabel adPicture3 = new JLabel(myIcon3);
Image image4 = ImageIO.read(url4);
ImageIcon myIcon4 = new ImageIcon(image4);
JLabel adPicture4 = new JLabel(myIcon4);
JLabel myLabel1 = new JLabel("McDonald's");
JLabel myLabel2 = new JLabel("20% off!");
JLabel myLabel3 = new JLabel("Wendy's");
JLabel myLabel4 = new JLabel("50% off!");
JLabel myLabel5 = new JLabel("KFC's");
JLabel myLabel6 = new JLabel("90% off!");
JLabel myLabel7 = new JLabel("A&W's");
JLabel myLabel8 = new JLabel("10% off!");
JButton button = new JButton("next");
setBackground(Color.white);
add(adPicture1);
add(myLabel1);
add(myLabel2);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent myEvent) {
if (getBackground() == Color.white) {
setBackground(Color.green);
myLabel1.setVisible(false);
myLabel2.setVisible(false);
adPicture1.setVisible(false);
add(myLabel3);
add(myLabel4);
add(adPicture2);
} else if (getBackground() == Color.green) {
setBackground(Color.red);
myLabel3.setVisible(false);
myLabel4.setVisible(false);
adPicture2.setVisible(false);
add(myLabel5);
add(myLabel6);
add(adPicture3);
} else if (getBackground() == Color.red) {
setBackground(Color.pink);
myLabel5.setVisible(false);
myLabel6.setVisible(false);
adPicture3.setVisible(false);
add(myLabel7);
add(myLabel8);
add(adPicture4);
} else if (getBackground() == Color.pink) {
myLabel7.setVisible(false);
myLabel8.setVisible(false);
adPicture4.setVisible(false);
add(myLabel1);
add(myLabel2);
add(adPicture1);
setBackground(Color.white);
}
}
});
add(button);
}
}
答案 0 :(得分:0)
每次点击按钮时,您可能不希望add()
标签和图片。也就是说,他们可能会被添加,但旧的不会被删除。因此,它们被添加到可见区域之外的面板中。
单击按钮时可以更改标签的文本和图标,而不是添加新标签。