2010-08-06 165 views
7

我正在使用NET Beans IDE在LINUX中开发我的应用程序。我已经使用synthetica软件包来产生新的外观和感觉。一切都很好,直到现在。Java Swing按钮颜色

现在我的下一个阶段是在某些数据库状态更改时向按钮添加颜色。

例如:

在餐厅,我有2个表,当8人进来吃饭,我会在我的软件中创建2台,因为人都是无人值守我想要的按钮来那些2张表是绿色。处理任何这些表的订单时,处理表的按钮颜色应更改为橙色。当它正在处理时,它应该是闪烁的颜色。如何在java中做到这一点?我会照顾数据库更新,我只是想知道如何更改按钮的颜色和添加闪烁技术。

回答

14

这是一个 question and several answers与闪烁组件有关。

附件:您可以在文章How to Use Buttons中了解更多。特别是,您可以使用setForeground()更改按钮文本的颜色,但在某些平台上相应的setBackground()不能很好地阅读。使用Border是一种选择;下面显示的彩色面板是另一个面板。

enter image description here

package overflow; 

import java.awt.Color; 
import java.awt.EventQueue; 
import java.awt.GridLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.util.ArrayList; 
import java.util.List; 
import java.util.Random; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.Timer; 

public class ButtonTest extends JPanel implements ActionListener { 

    private static final int N = 4; 
    private static final Random rnd = new Random(); 
    private final Timer timer = new Timer(1000, this); 
    private final List<ButtonPanel> panels = new ArrayList<ButtonPanel>(); 

    public ButtonTest() { 
     this.setLayout(new GridLayout(N, N, N, N)); 
     for (int i = 0; i < N * N; i++) { 
      ButtonPanel bp = new ButtonPanel(i); 
      panels.add(bp); 
      this.add(bp); 
     } 
    } 

    @Override 
    public void actionPerformed(ActionEvent e) { 
     for (JPanel p : panels) { 
      p.setBackground(new Color(rnd.nextInt())); 
     } 
    } 

    private static class ButtonPanel extends JPanel { 

     public ButtonPanel(int i) { 
      this.setBackground(new Color(rnd.nextInt())); 
      this.add(new JButton("Button " + String.valueOf(i))); 
     } 
    } 

    public static void main(String[] args) { 
     EventQueue.invokeLater(new Runnable() { 

      @Override 
      public void run() { 
       JFrame f = new JFrame("ButtonTest"); 
       f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       ButtonTest bt = new ButtonTest(); 
       f.add(bt); 
       f.pack(); 
       f.setLocationRelativeTo(null); 
       f.setVisible(true); 
       bt.timer.start(); 
      } 
     }); 
    } 
} 
+1

使用'setOpaque(真)'上的按钮也是有效的,如图[这里](http://stackoverflow.com/a/9852024/230513)。 – trashgod 2012-03-24 14:37:37

+0

我从来没有意识到Swing可以那么漂亮 – 2013-10-30 22:26:29

+0

@TimothyLeung:归功于Java 2D和Aqua/Quartz;另见'Color.getHSBColor()',见[这里](http://stackoverflow.com/a/9875534/230513)。 – trashgod 2013-10-30 23:04:50