How to stop a JButton going gray when disabled? - java

I have to write a card game. When a card is clicked a random card image is generated but because you can only click on the card once, the button is set to be disabled after clicked. How can I stop the card image from going gray once it's clicked so that the new generated card image is clearly visible?
//Actions performed when an event occurs
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == card1)
{
randomInteger();
card1.setIcon(cardImages[randomInt]);
card1.setEnabled(false);
}
else if (e.getSource() == card2)
{
randomInteger();
card2.setIcon(cardImages[randomInt]);
card2.setEnabled(false);
}
else if (e.getSource() == card3)
{
randomInteger();
card3.setIcon(cardImages[randomInt]);
card3.setEnabled(false);
}
else if (e.getSource() == card4)
{
randomInteger();
card4.setIcon(cardImages[randomInt]);
card4.setEnabled(false);
}
else
{
randomInteger();
card5.setIcon(cardImages[randomInt]);
card5.setEnabled(false);
}
}
}

You simply need to set the disabled icon of the button to the same value as the icon of the button. See this example:
On the left a button where I have set both icon and disabledIcon. On the right I have only set the icon:
import java.awt.BorderLayout;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class TestDisabledButtons {
public static final String CARD_URL = "http://assets0.wordansassets.com/wvc-1345850020/wordansfiles/images/2012/8/24/156256/156256_340.jpg";
protected void createAndShowGUI() throws MalformedURLException {
JFrame frame = new JFrame("Test button");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageIcon imageIcon = new ImageIcon(new URL(CARD_URL));
JButton button = new JButton(imageIcon);
JButton button2 = new JButton(imageIcon);
button.setDisabledIcon(imageIcon);
button.setEnabled(false);
button2.setEnabled(false);
frame.add(button, BorderLayout.WEST);
frame.add(button2, BorderLayout.EAST);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
new TestDisabledButtons().createAndShowGUI();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}

Related

How do I implement the codes which works as a timer app using awt,swing,Thread while satisfying some conditions?

I have to make the timer codes of Java using awt,swing,Thread.
The overview of the eventual app has below 4 features.
The app has just one button.
Firstly the button display the "START"on the button itself.
Dynamic time is displayed on the button as the button is pressed.
As the button pressed while counting the time,the button stop the counting and display "START".
I've written the code such as below.
boolean isCounting = false;
int cnt = 0;
void counter() {
while (isCounting == true) {
btn.setText(Integer.toString(++cnt));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void actionPerformed(ActionEvent e) {
if (isCounting == true) {
isCounting = false;
} else {
isCounting = true;
counter();
}
}
Of course this code doesn't satisfy the conditions because once the button is pressed then
the button is no more able to be pressed again and the counter never works.
In this code,once the button is pressed then the function "counter" is called but the value on the button never changes until the button is unpressed.
I have to make the codes satisfying the above conditions.
How do I implement it?
If I understood your question correctly, then this snippet I quickly put together should work for you.
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class Testing {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Testing t = new Testing();
}
});
}
private Timer timer;
private JFrame frame;
private JButton btn;
private int timePassed;
public Testing() {
frame = new JFrame();
timer = new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
timePassed++;
updateTimeOnButton();
}
});
btn = new JButton("START");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (timer.isRunning()) {
timer.stop();
btn.setText("START");
} else {
timePassed = 0;
timer.start();
updateTimeOnButton();
}
}
});
frame.getContentPane().add(btn);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setSize(new Dimension(300, 300));
}
private void updateTimeOnButton() {
btn.setText(timePassed + " seconds");
}
}

Custom maximize, minimize buttons

I created custom buttons for maximize, minimize and exit. And everything is working, with one exception, program does not remember in which state window was, before minimization. So my question is, is there a way, program to remember window state before minimization, and restore that state, and not to return only on NORMAL state?
My solution for:
maximize:
JButton btnO = new JButton("O");
btnO.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (frame.getExtendedState() == JFrame.MAXIMIZED_BOTH) {
frame.setExtendedState(JFrame.NORMAL);
} else {
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
}
});
and Minimize:
JButton btnMinimize = new JButton("-");
btnMinimize.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.setExtendedState(JFrame.ICONIFIED);
}
});
You can take the ComponentListener approach and restore its state when the component (in your case, the frame), is resized. Some extra comments inside the code.
Take a look at this example:
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class FrameState extends JFrame {
private static final long serialVersionUID = 1965751967944243251L;
private int state = -1; // Variable to keep the last state.
public FrameState() {
super("Nothing :)");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton b = new JButton("-");
b.addActionListener(e -> {
state = getExtendedState(); //Store the state before "-" is pressed
setExtendedState(JFrame.ICONIFIED);
});
JButton o = new JButton("O");
o.addActionListener(e -> {
if (getExtendedState() == JFrame.MAXIMIZED_BOTH) {
setExtendedState(JFrame.NORMAL);
} else {
setExtendedState(JFrame.MAXIMIZED_BOTH);
}
});
getContentPane().setLayout(new FlowLayout());
getContentPane().add(o);
getContentPane().add(b);
setSize(new Dimension(300, 300));
setLocationRelativeTo(null);
addComponentListener(new ComponentListener() {
#Override
public void componentShown(ComponentEvent arg0) {
}
#Override
public void componentResized(ComponentEvent arg0) {
if (state != -1) {
setExtendedState(state); //Restore the state.
state = -1; //If it is not back to -1, window won't be resized properly by OS.
}
}
#Override
public void componentMoved(ComponentEvent arg0) {
}
#Override
public void componentHidden(ComponentEvent arg0) {
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
FrameState f = new FrameState();
f.setVisible(true);
});
}
}
You can use this code in JButton to maximize and restore JFrame.
In order to perform this function, you have import JFrame even though the JFrame has been extended in your java class.
if(getExtendedState()==NORMAL)
{
setExtendedState(MAXIMIZED_BOTH);
}
else
{
setExtendedState(NORMAL);
}

FileViewer and Enlarge Method with extend Frame and actionListener

Trying get a fileViewer method that will allow user to choose photo from file and when Button is used will pull up the dialog box. My close button obviously works as code is simple. With the enlarge picture button I did wonder if I could declare a constant and use it to scale photo by the constant. Wasn't sure if that was even a thing.
Below is my code:
package masdfas.fd;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class BetterWork extends Frame implements ActionListener {
Button browseButton = new Button("Browse");
Button enlargeButton = new Button("Enlarge");
Button closeButton = new Button("Quit");
Label onlyLabel = new Label ("Welcome to my Program");
public static void main(String[] args) {
BetterWork BW = new BetterWork();
BW.setVisible(true);
BW.setSize(600, 500);
}
public BetterWork() {
super ("program");
setLayout(null);
onlyLabel.setBounds(250, 50, 150, 50);
add(onlyLabel);
browseButton.setBounds(30, 50, 50, 50);
add( browseButton);
enlargeButton.setBounds(30, 150, 50, 50);
add(enlargeButton);
closeButton.setBounds(30, 250, 50, 50);
add(closeButton);
browseButton.addActionListener(this);
enlargeButton.addActionListener(this);
closeButton.addActionListener(this);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent AE) {
if (AE.getSource() == browseButton) {
browse();
} else if (AE.getSource() == enlargeButton) {
enlarge();
} else if (AE.getSource() == closeButton) {
close();
}
}
private void close() {
System.exit(0);
}
private void enlarge() {
// TODO Auto-generated method stub
}
private void browse() {
// TODO Auto-generated method stub
}
}

Need to display ImageIcon when Jbutton is pressed

I am having trouble getting my Image to display when I click my Jbutton, the test sysoutprint works but the Image does not. Any Ideas on what to do I am very lost! The Image is an easter egg for a school project, feel free to make comments. Should I use something besides a ImageIcon or what not?
Also if there are any other errors please let me know!
package GUI;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class mainView{
private static JFrame main; //main frame we add everything too
private static JPanel newGame; //panel for new game
private static JPanel dropDownPanel; //panel for the combobox
private static CardLayout clayout; //cardlayout for new game
private static JComboBox dropDown; //dropdown combobox
ImageIcon eastImg;
public void codeNameView(){
main = new JFrame("CodeNames");
main.setSize(600, 900);
main.setVisible(true);
//dropdown menu for quit and new game
String[] choice = {" " , "NewGame" , "Quit"};
dropDown = new JComboBox(choice);
//below is the panel where we add new game and quit options too
dropDownPanel = new JPanel();
dropDownPanel.setSize(100, 100);
dropDownPanel.add(dropDown);
main.getContentPane().add(dropDownPanel,BorderLayout.NORTH);
//easter egg
JButton easterButt = new JButton("Pass CSE 116");
JLabel eastLbl = new JLabel();
//added button to JLabel
eastLbl.add(easterButt);
try{
String path = "/Users/nabeelkhalid/git/s18semesterproject-b4-zigzag1/src/GUI/MatthewPhoto.jpg";
eastImg = new ImageIcon(path);
}catch(Exception ex){
System.out.print(ex);
}
//added label to Panel
dropDownPanel.add(eastLbl);
eastLbl.addMouseListener(new MouseListener(){
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
eastLbl.setIcon(eastImg);
System.out.print("test");
}
//Ignore
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
});
//action listener for dropdown combobox
dropDown.addActionListener(new ActionListener(){
/**
* Allows for the user to select New Game or Quit and have the game perform said action
*/
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
JComboBox cb = (JComboBox) e.getSource();
Object selectedOption = dropDown.getSelectedItem();
if (selectedOption.equals("Quit")) {
main.dispose();
}else if(selectedOption.equals("NewGame")){
codeNameView();
System.out.print("yolo");
}
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
mainView x = new mainView();
// create a instance on mainview to run instead of using static methods
}
});
}
}
The primary issue seems to be right here
try{
String path = "/Users/nabeelkhalid/git/s18semesterproject-b4-zigzag1/src/GUI/MatthewPhoto.jpg";
eastImg = new ImageIcon(path);
}catch(Exception ex){
System.out.print(ex);
}
The path is referencing a resource within the context of your src path. You should never reference src in your code, it won't exist once the program is exported (to a Jar or run on a different computer)
Instead, you should consider using Class#getResource to obtain a reference to the image and I'd personally use ImageIO.read over ImageIcon as a personal preference.
try{
String path = "/GUI/MatthewPhoto.jpg";
eastImg = new ImageIcon(ImageIO.read(this.getClass().getResource(path)));
}catch(Exception ex){
System.out.print(ex);
}
And, your next problem is, you're trying to add a JLabel to a JButton, expect, a JButton has not layout manager AND JButton already has support for display an image, so instead, you should be doing something more like...
JButton easterButt = new JButton("Pass CSE 116");
//JLabel eastLbl = new JLabel();
//added button to JLabel
//eastLbl.add(easterButt);
try {
String path = "/GUI/MatthewPhoto.jpg";
eastImg = new ImageIcon(ImageIO.read(this.getClass().getResource(path)));
} catch (Exception ex) {
System.out.print(ex);
}
//added label to Panel
dropDownPanel.add(easterButt);
easterButt.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
easterButt.setIcon(eastImg);
}
});
You really should take a closer look at How to Use Buttons, Check Boxes, and Radio Buttons
Test Code
This is the code I used to test the solutions suggested above
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class mainView {
private static JFrame main; //main frame we add everything too
private static JPanel newGame; //panel for new game
private static JPanel dropDownPanel; //panel for the combobox
private static CardLayout clayout; //cardlayout for new game
private static JComboBox dropDown; //dropdown combobox
ImageIcon eastImg;
public void codeNameView() {
main = new JFrame("CodeNames");
main.setSize(600, 900);
//dropdown menu for quit and new game
String[] choice = {" ", "NewGame", "Quit"};
dropDown = new JComboBox(choice);
//below is the panel where we add new game and quit options too
dropDownPanel = new JPanel();
dropDownPanel.setSize(100, 100);
dropDownPanel.add(dropDown);
main.getContentPane().add(dropDownPanel, BorderLayout.NORTH);
//easter egg
JButton easterButt = new JButton("Pass CSE 116");
// JLabel eastLbl = new JLabel();
// //added button to JLabel
// eastLbl.add(easterButt);
try {
String path = "/GUI/MatthewPhoto.jpg";
eastImg = new ImageIcon(ImageIO.read(this.getClass().getResource(path)));
} catch (Exception ex) {
System.out.print(ex);
}
//added label to Panel
dropDownPanel.add(easterButt);
easterButt.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
easterButt.setIcon(eastImg);
}
});
//action listener for dropdown combobox
dropDown.addActionListener(new ActionListener() {
/**
* Allows for the user to select New Game or Quit and have the game
* perform said action
*/
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
JComboBox cb = (JComboBox) e.getSource();
Object selectedOption = dropDown.getSelectedItem();
if (selectedOption.equals("Quit")) {
main.dispose();
} else if (selectedOption.equals("NewGame")) {
codeNameView();
System.out.print("yolo");
}
}
});
main.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
System.out.println("Hello");
mainView x = new mainView();
x.codeNameView();
// create a instance on mainview to run instead of using static methods
}
});
}
}
Try using something like this:
String path = "C:\\Users\\nabeelkhalid\\git\\s18semesterproject-b4-zigzag1\\src\\GUI\\MatthewPhoto.jpg";

How to open a new window or switch using a button?

I'm trying to figure out this for ages, starting to wonder if it is possible!
I have a starting window for my app - I need it so that when I click on a button I have created, the window either closes and opens a new window or the window resizes and leaves just the canvas (ready to put new widgets, sprites etc... ).
I know I need a handler event for this but I just can't get the code to work.
Im not quite sure whats your question but i coded a example with a JFrame and 3 Buttons.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class OpenWindowAndResizeWindow
{
private JFrame frame;
private JButton btnOpenNewWindow;
private JButton btnResizeWindow;
private JButton btnRemoveAllButtons;
/**
* Launch the application.
*/
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
OpenWindowAndResizeWindow window = new OpenWindowAndResizeWindow();
window.frame.setVisible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public OpenWindowAndResizeWindow()
{
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize()
{
frame = new JFrame();
frame.setBounds(100, 100, 300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(getBtnOpenNewWindow(), BorderLayout.NORTH);
frame.getContentPane().add(getBtnResizeWindow(), BorderLayout.SOUTH);
frame.getContentPane().add(getBtnRemoveAllButtons(), BorderLayout.CENTER);
frame.setVisible(true);
}
private void openNewWindow()
{
OpenWindowAndResizeWindow newWindow = new OpenWindowAndResizeWindow();
frame.dispose();
}
private void removeButtons()
{
getBtnOpenNewWindow().setVisible(false);
getBtnRemoveAllButtons().setVisible(false);
getBtnResizeWindow().setVisible(false);
}
private void resizeWindow()
{
Rectangle rectangle = frame.getBounds();
rectangle.width = (int)rectangle.getWidth() + 100;
rectangle.height = (int)rectangle.getHeight() + 100;
frame.setBounds(rectangle);
}
private JButton getBtnOpenNewWindow() {
if (btnOpenNewWindow == null) {
btnOpenNewWindow = new JButton("Open new Window");
btnOpenNewWindow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openNewWindow();
}
});
}
return btnOpenNewWindow;
}
private JButton getBtnResizeWindow() {
if (btnResizeWindow == null) {
btnResizeWindow = new JButton("Resize Window");
btnResizeWindow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
resizeWindow();
}
});
}
return btnResizeWindow;
}
private JButton getBtnRemoveAllButtons() {
if (btnRemoveAllButtons == null) {
btnRemoveAllButtons = new JButton("Remove All Buttons");
btnRemoveAllButtons.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
removeButtons();
}
});
}
return btnRemoveAllButtons;
}
}
This code is ready to compile with javac or just paste it in your IDE.
Maybe this helps a bit. The Java SE API Documentation is useful too.

Categories