Java Swing button colors [duplicate] - java

This question already has answers here:
How to set background color of a button in Java GUI?
(7 answers)
Closed 8 years ago.
I am using NET Beans IDE for developing my application in LINUX. I have used synthetica package to generate new look and feel. All is well till now.
Now my next stage is to add colors to buttons when some database status changes.
For example:
In a restaurant i have 2 tables and when 8 people came in to dine and i will create 2 table in my software since the people are unattended i want the buttons to those 2 tables to be green. When the order is processed for any of those tables the button color of the processed table should be changed to orange. When it is under processing it should be flashing color. How to do this in java ? I will take care of database update i just want to know how to change the colors of the buttons and adding flashing technique.

Here is a question and several answers related to flashing a component.
Addendum: You can learn more in the article How to Use Buttons. In particular, you can use setForeground() to change the color of a button's text, but the corresponding setBackground() doesn't read well on some platforms. Using a Border is one alternative; a colored panel, shown below, is another.
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();
}
});
}
}

Related

I can't move my JLabel with Key Binding?

I am trying to make a game in Java where pressing spacebar moves the box in the window. I am using Key Binding to accomplish this task. The problem is that I can't figure out how to use an ActionListener on the box itself, which is a JLabel. Here is the code below:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
public class Game {
private static JFrame frame = new JFrame();
private static JPanel gamePanel = new JPanel();
private static Action playerAction = new PlayerListener();
private static JLabel box = new JLabel();
private static int x = 250;
private static int y = 250;
public static void main(String[] args) {
frame.add(boxPanel());
frame.setTitle("Block Game");
frame.setSize(500,500);
frame.setLocationRelativeTo(null);
frame.setFocusable(true);
box.addActionListener(playerAction);
frame.setVisible(true);
}
static JPanel boxPanel() {
ImageIcon boxIcon = new ImageIcon("box.png");
box.setIcon(boxIcon);
box.setSize(30,30);
box.setLocation(x,y);
box.getInputMap().put(KeyStroke.getKeyStroke("SPACE"), "doPlayerAction");
box.getActionMap().put("doPlayerAction", playerAction);
gamePanel.setLayout(null);
gamePanel.add(box);
frame.add(gamePanel);
return gamePanel;
}
static class PlayerListener extends AbstractAction {
public void actionPerformed(ActionEvent e) {
System.out.println("SPACEBAR");
}
}
}
I tried changing the box to a JButton and working with that instead, but I have found that "SPACEBAR" only prints out when I click on the box itself. Any help is greatly appreciated. Thanks!
Your "core" problem revolves around box.getInputMap(), change it to something more like box.getInputMap(WHEN_IN_FOCUSED_WINDOW) which will mean that the API will respond to key events whenever the window has focus, regardless what other components might have focus.
I'd also suggestsomething more like box.getInputMap(WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), "doPlayerAction"), as the mechanism which KeyStroke uses to parse String to a KeyStroke is more complicated then it might seem, normally requiring additional information like pressed, released or typed, it's just easier to use the virtual keys
I would also bind the keys to the gamePanel as a general preference, as it should be the container making decisions about what to do, but that's just me.
Have a look at How to Use Key Bindings for more details

JAVA JButton in a different class refuses to activate when pressed

I'm failing to understand why my yankee and whiskey JButtons aren't working. Right now I only want them to close the program when romeo is greater than 1 and sierra is greater than 1.
import java.awt.*;
import java.lang.*;
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.*;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
import java.util.Scanner;
public class AlphaMenu extends JFrame /*implements actionPerformed*/
{
private GraphicsDevice gamma;
public JButton charlie, zulu, yankee, xray;
public JFrame beta;
public JPanel delta, echo, foxtrot, golf, hotel;
public JTextArea whiskey, victor;
public BorderLayout uniform;
public ImageIcon bg;
public JLabel tango;
public int sierra, romeo;
public Integer quebec, papa;
public ActionEvent oscar;
public ActionEvent november;
public AlphaMenu()
{
//Initialization of Objects
charlie = new JButton("EXIT");
zulu = new JButton("Enter Time");
yankee = new JButton("Enter Amount of Money");
xray = new JButton("Calculate");
sierra = 0;
romeo = 0;
quebec = new Integer(0);
papa = new Integer(0);
whiskey = new JTextArea(2, 15);
victor = new JTextArea(2, 15);
bg = new ImageIcon("background.gif");
beta = new JFrame();
delta = new JPanel();
echo = new JPanel();
foxtrot = new JPanel();
golf = new JPanel();
hotel = new JPanel();
uniform = new BorderLayout();
ImageIcon bg = new ImageIcon("background.gif");
tango = new JLabel("");
tango.setIcon(bg);
//Modification of panels
beta.add(delta, uniform.PAGE_END);
beta.add(golf, uniform.PAGE_START);
beta.add(echo, uniform.LINE_START);
beta.add(foxtrot, uniform.LINE_END);
beta.add(hotel, uniform.CENTER);
golf.add(tango);
//Modification of JButton charlie & adding of JButtons
charlie.setPreferredSize(new Dimension(100, 50));
delta.add(charlie);
charlie.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
echo.add(whiskey);
echo.add(yankee);
foxtrot.add(victor);
foxtrot.add(zulu);
//Modification of JFrame beta
beta.setUndecorated(true);
beta.setExtendedState(JFrame.MAXIMIZED_BOTH);
beta.setResizable(false);
beta.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
beta.setVisible(true);
}
public void buttonSetup() throws NumberFormatException
{
//Modification of JButton yankee & JTextArea whiskey & int sierra
romeo = quebec.parseInt(whiskey.getText());
yankee.setPreferredSize(new Dimension(300, 50));
yankee.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent oscar)
{
System.exit(0);
}
});
//Modification of JButton zulu & JTextArea victor & int romeo
sierra = papa.parseInt(victor.getText());
zulu.setPreferredSize(new Dimension(300, 50));
zulu.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent november)
{
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e)
{
}
public static void main(String[] args)
{
new AlphaMenu();
}
}
So, you have two JTextArea (JTextField would probably be better) and a button. you want some buttons to execute exit when the text of both textareas is an integer greater than 1.
seems that your buttonSetup() function isn't called anywhere.
Anyway, I'd create an ActionListener that reads the texts, converts to integer, tests your condition and executes exit(). This ActionListener should be added to all the buttons you want to perform the action
final ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent event) {
try {
final int intRomeo = Integer.parseInt(romeo.getText());
final int intSierra = Integer.parseInt(sierra .getText());
if (intRomeo > 1 && intSierra > 1) {
// whatever you want to do
System.exit(0);
}
} catch (/*NumberFormat*/ Exception e) {
// ...not integers
}
};
}
whiskey.addActionListener(al);
yankee.addActionListener(al);
I have to add: the variable names you are using are really bad. Consider choosing something more significative.
For starters, readability...it would probably help the "sloppiness" if you used more appropriate names for your variables, indented different sections of code, and used comments to help describe sections in layman's terms. Maybe "btnExit" and "btnCalculate" would help make things a little easier to navigate.
Moving forward, you also don't have two different classes here, you have one class with several methods. Which is fine but wanted to inform you of that. I think maybe you need to add the buttons to their panels after your action listeners and formatting for each button. I'm just getting into some swing stuff myself and I've noticed moving the .add() functions around in the code has helped when I run into issues like this. Try the following bellow. I indented and used new naming conventions for the comments, but the code uses your convention.
//add the pnlEcho to frmBeta
beta.add(echo, uniform.LINE_START);
//format btnYankee
yankee.setPreferredSize(new Dimension(300, 50));
//btnYankee action listener
yankee.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) { //default action event
System.exit(0); //you could use this
beta.dispose(); //or you could dispose the frame and
//do more work after it is gone
}
});
//add btnYankee to pnlEcho
echo.add(yankee);
I'm failing to understand why my yankee and whiskey JButtons aren't
working
The variable wiskey is not JButton type but JTextArea type.

JRadioButton selection doesn't show on GUI until visible in Windows LaF

I'm currently working on a project that requires the state of a JRadioButton to change when the record being viewed is updated.
We've had a few clients complain to us that when the record changes, if the JRadioButton is off-screen, it won't be updated until the screen is shown. This behavior seems to be a result of using the Windows Look and Feel, as it doesn't seem to happen when it is not set.
The code example below demonstrates this.
The default selected JRadioButton is 'Cat', so by selecting the 'Dog' JButton and then changing tab to 'Question', you can see the JRadioButton transition occur.
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
/**
* Example of JRadioButton not updating until it's parent panel becomes visible.
*/
public class RadioButtonExample extends JPanel implements ActionListener {
public static final String CAT = "Cat";
public static final String DOG = "Dog";
private final JRadioButton radCat;
private final JRadioButton radDog;
private final ButtonGroup grpAnimal;
public RadioButtonExample() {
super(new BorderLayout());
JLabel lblQuestion = new JLabel("Are you a cat or dog person?");
radCat = new JRadioButton(CAT);
radCat.setActionCommand(CAT);
radCat.setSelected(true);
radDog = new JRadioButton(DOG);
radDog.setActionCommand(DOG);
grpAnimal = new ButtonGroup();
grpAnimal.add(radCat);
grpAnimal.add(radDog);
JPanel pnlQuestion = new JPanel(new GridLayout(0, 1));
pnlQuestion.add(lblQuestion);
pnlQuestion.add(radCat);
pnlQuestion.add(radDog);
JButton btnSetCat = new JButton(CAT);
btnSetCat.setActionCommand(CAT);
btnSetCat.addActionListener(this);
JButton btnSetDog = new JButton(DOG);
btnSetDog.setActionCommand(DOG);
btnSetDog.addActionListener(this);
JPanel pnlButtons = new JPanel(new GridLayout(0, 1));
pnlButtons.add(new JLabel("Update your choice of animal"));
pnlButtons.add(btnSetCat);
pnlButtons.add(btnSetDog);
JTabbedPane tabPane = new JTabbedPane();
tabPane.addTab("Buttons", pnlButtons);
tabPane.addTab("Question", pnlQuestion);
add(tabPane, BorderLayout.LINE_START);
setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
}
public void actionPerformed(ActionEvent evt) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
grpAnimal.clearSelection();
if (CAT.equals(evt.getActionCommand())) {
grpAnimal.setSelected(radCat.getModel(), true);
}
else if (DOG.equals(evt.getActionCommand())) {
grpAnimal.setSelected(radDog.getModel(), true);
}
}
});
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("RadioButtonExample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
JComponent newContentPane = new RadioButtonExample();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
// Comment out the line below to run using standard L&F
setLookAndFeel();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void setLookAndFeel() {
try {
// Set Windows L&F
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
}
catch (Exception e) {
// handle exception
}
}
}
Is there a way to prevent this behavior or even speed it up to make it less noticeable for our users?
You might be able to disable the animation by specifying the swing.disablevistaanimation Java system property:
java -Dswing.disablevistaanimation="true" your-cool-application.jar
In the com.sun.java.swing.plaf.windows.AnimationController class, there is a VISTA_ANIMATION_DISABLED field that is initialized to the swing.disablevistaanimation property. This field determines whether the paintSkin method calls the skin.paintSkinRaw method if animations are disabled or else starts to get into the animations.
It works on my Windows 8.1 laptop with Java 8 (jdk1.8.0_65), so its effect does not seem to be limited to Windows Vista only.

Focus not being set by method to grab focus

Learning to code, building a GUI to figure out how everything interacts. Trying to write a method to set focus on (component) at the points I need in the larger program - ie to call FocusGrabber(JTextField1) and have it set the input focus on JTextField1. In an attempt to do my best SSCCE, I've made a simple main that makes just enough GUI to give 2 textfields that should set focus on the second.
package ODIN;
import java.awt.Component;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
/*
*/
class FocusGrabber implements Runnable {
private JComponent component;
public FocusGrabber(JComponent component) {
this.component = component;
}
#Override
public void run() {
component.grabFocus();
}
public static void main(String[] args){
//draw and show the GUI
JFrame GUI = new JFrame();
GUI.setTitle("New Provider Interface");
GUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTextField textID = new JTextField("providerID ", 20);
final JTextField textName = new JTextField("Provider Name ", 20);
GUI.add(textID);
GUI.add(textName);
GUI.pack();
GUI.setVisible(true);
FocusGrabber(textName);
}
}
Use requestFocusInWindow over grabFocus...
It would also be helpful if you called the run method at some point
Also, shouldn't it be more like
FocusGrabber fg = new FocusGrabber(textName);
fg.run();

Create banner/tool bar in java acting like Windows Taskbar

I want to create desktop application, a banner / tool bar, in java (I'm using swing in netbeans) and I want it to act same as windows Task bar, means desktop icons will rearrange according to banner position.
How to do so?
Thanks for any responses.
one of way is use JWindow or Modal and un_decorated JDialog, for example
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JWindow;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class SlideText_1 {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
final JWindow window = new JWindow();
final JPanel windowContents = new JPanel();
JLabel label = new JLabel("A window that is pushed into view..........");
windowContents.add(label);
window.add(windowContents);
window.pack();
window.setLocationRelativeTo(null);
final int desiredWidth = window.getWidth();
window.getContentPane().setLayout(null);
window.setSize(0, window.getHeight());
window.setVisible(true);
Timer timer = new Timer(15, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int newWidth = Math.min(window.getWidth() + 1, desiredWidth);
window.setSize(newWidth, window.getHeight());
windowContents.setLocation(newWidth - desiredWidth, 0);
if (newWidth >= desiredWidth) {
((Timer) e.getSource()).stop();
window.getContentPane().setLayout(new BorderLayout()); //restore original layout
window.validate();
window.setVisible(false);
}
}
});
timer.start();
}
private SlideText_1() {
}
}
Shahar asked this question on my behalf. I thought that it could be done using pure Java, but sadly as far as I know, in this case, Java is a dead end.
You need to use windows API and for that you will need to use Java Native Interface (JNI).
Best way is to create a DLL using C or C++ (use the header windows) and import it into the Java code.

Categories

Resources