2016-11-18 94 views
0

用三个按钮编写一个显示窗口的程序。每个按钮都有一个名称,如“红色”,“绿色”和“蓝色”。在这个窗口中,还有一个标签。该标签包含一个图标。此图标必须是CompositeIcon,其中开头为空。每按一次按钮,您都会看到一个带有按钮颜色的方块,例如“按蓝色按钮 - >窗口上出现蓝色方块”。 到目前为止,我有这个。我有他们的颜色名称的三个按钮。我每次按下其中一个按钮都不起作用。我需要做什么?我怎样才能让按钮变成方形的颜色?

代码:

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 

public class ActionTester{ 

    public static void main(String[] args){ 
      JFrame frame = new JFrame(); 
      final JTextField textField = new JTextField(); 

      JButton RedButton = new JButton("Red"); 

      RedButton.addActionListener(new ActionListener() { 
        @Override 
        public void actionPerformed(ActionEvent e) { 
          SquareIcon red = new SquareIcon(20,Color.RED); 
          CompositeIcon ci = new CompositeIcon(); 
          ci.addIcon(red); 
        } 
      }); 

      JButton GreenButton = new JButton("Green"); 

      GreenButton.addActionListener(new ActionListener() { 
        @Override 
        public void actionPerformed(ActionEvent e) { 
          SquareIcon green = new SquareIcon(20,Color.GREEN); 
          CompositeIcon ci = new CompositeIcon(); 
          ci.addIcon(green); 
        } 
      }); 

      JButton BlueButton = new JButton("Blue"); 

      BlueButton.addActionListener(new ActionListener() { 
        @Override 
        public void actionPerformed(ActionEvent e) { 
          SquareIcon blue = new SquareIcon(20,Color.BLUE); 
          CompositeIcon ci = new CompositeIcon(); 
          ci.addIcon(blue); 
        } 
      }); 

      frame.setLayout(new FlowLayout()); 
      frame.add(RedButton); 
      frame.add(GreenButton); 
      frame.add(BlueButton); 
      frame.add(textField); 
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
      frame.pack(); 
      frame.setVisible(true); 
    } 
} 
+0

嘿,我不知道如果同样的运动,但对这个一看,最常见的进口打扰:HTTP:/ /stackoverflow.com/questions/19881700/buttons-and-icons-within-a-label-squareicon。这听起来与你的任务非常相似。 – endkugelfang

回答

2

所有你需要做的是创建您在更改ActionListener像一个方形物体:

final JPanel sqr = new JPanel(); 

JButton RedButton = new JButton("Red"); 

RedButton.addActionListener(new ActionListener() 
{ 
    @Override 
    public void actionPerformed(ActionEvent e) 
    { 
    sqr.setBackground(Color.RED); 
    } 
}); 

不要忘记添加sqr到帧

在另一方面请避免使用进口喜欢

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 

在我的项目它来到了

import java.awt.Color; 
import java.awt.FlowLayout; 
import java.awt.Frame; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.JTextField; 

有些IDE可以整理你进口全自动所以你不需要再

+0

谢谢你回答我的问题。如果我想每次按红色按钮的时候想要做一个以上的红色正方形,那么更多的红色正方形会出现在另一个旁边。我怎么做? – MrDavidNhan10

+0

没关系我觉得我明白了。不管怎样,谢谢你。 – MrDavidNhan10

+2

某些外观不符合按钮的背景颜色。要获得更可靠的方法,请使用[This answer](http://stackoverflow.com/a/13943044/418556)中所见的'ColoredIcon'。这将适用于PLAF和系统。 (请注意,答案会将图标添加到标签,但按钮也会接受图标。) –

1

按钮本身的工作,但你永远不添加compositeicon到你的框架。因此没有任何显示

+0

谢谢你指出。 – MrDavidNhan10