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";
Related
I want to display a "loading message" when a process is started and I want to change the message when the process is finished. I tried to update the text from a JLabel before and after the thread with the process is started but the problem is that on the frame appears only the last update.
Here is my code:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class MyClass extends JFrame {
private JLabel loading;
private JButton jButton;
private JPanel jPanel;
public static void main(String[] args) {
new MyClass();
}
MyClass() {
jPanel = new JPanel();
setLayout(new GridLayout(0, 1));
loading = new JLabel("");
loading.setVisible(true);
jButton = new JButton("Click me!");
addActionToJButon();
setSize(300, 300);
jPanel.add(jButton);
jPanel.add(loading);
add(jPanel);
setVisible(true);
}
private void addActionToJButon() {
jButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
loading.setText("Loading....");
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i <= 1000000; i++) {
System.out.println(i);
}
}
}).start();
loading.setText("Done!");
}
});
}
}
I was expecting to appear the label "Loading..." once what the process is started and the message "Done" when the process is finished but I can't find out why on the frame appears the label with the message "Done!".
Thanks to JB Nizet advices I used SwingWorker and the code is working now.
Here is the correct code:
package view;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.ExecutionException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingWorker;
public class MyClass extends JFrame {
private JLabel loading;
private JButton jButton;
private JPanel jPanel;
public static void main(String[] args) {
new MyClass();
}
MyClass() {
jPanel = new JPanel();
setLayout(new GridLayout(0, 1));
loading = new JLabel("");
loading.setVisible(true);
jButton = new JButton("Click me!");
addActionToJButon();
setSize(300, 300);
jPanel.add(jButton);
jPanel.add(loading);
add(jPanel);
setVisible(true);
}
private void addActionToJButon() {
jButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
loading.setText("Loading....");
swingWorker();
}
});
}
private void swingWorker() {
SwingWorker worker = new SwingWorker<String, String>() {
#Override
protected String doInBackground() throws Exception {
// TODO Auto-generated method stub
for (int i = 0; i <= 1000000; i++) {
System.out.println(i);
}
return "Done";
}
protected void done() {
try {
String finished = get();
loading.setText(finished);
} catch (InterruptedException | ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
worker.execute();
}
}
Because you are doing your "loading" within a thread, and you are setting your loading text outside the thread, you immediately set loading to "Done!" when you begin loading. What you want to do is set loading within your run() function like this:
private void addActionToJButon() {
jButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
new Thread(new Runnable() {
#Override
public void run() {
loading.setText("Loading....");
// TODO Auto-generated method stub
for (int i = 0; i <= 1000000; i++) {
System.out.println(i);
}
loading.setText("Done!");
}
}).start();
}
});
}
I've tried many things to get this button bb or continue to output "Hey Buddy", yet it still does not work. It is displayed yet when i press it nothing happens. The code uses both java swing a awt.
package Game;
import java.awt.*;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.TextEvent;
import java.awt.event.TextListener;
import java.util.concurrent.TimeUnit;
import javax.swing.JButton;
public class base extends java.applet.Applet implements ActionListener, TextListener {
//Graphics
//Graphics
#SuppressWarnings("deprecation")
public static JButton bb = new JButton("Continue");
public TextArea ta = new TextArea(30, 140);
TextArea tb = new TextArea(3, 130);
public int counter = 0;
//main class
public static void main(String[] args) {
Frame f = new Frame("---Quest---");
base ex = new base();
ex.init();
f.add("Center", ex);
f.pack();
f.show(true);
bb.addActionListener(ex);
}
public void actionPerformed1(ActionEvent Continue) {
bb.addActionListener(this);
counter++;
if (Continue.getSource() == bb && counter == 1) {
tb.append("Hey Buddy");
}
}
//graphics
public void init() {
bb.addActionListener(this);
Panel p;
setLayout(new BorderLayout());
p = new Panel();
ta.append("Hey");
bb.addActionListener(this);
p.add(bb);
p.add(ta);
p.add(tb);
p.setBackground(Color.blue);
ta.setBackground(Color.cyan);
ta.setEditable(false);
add("Center", p);
p.setVisible(true);
}
//time class
public static int nap(int time) {
try {
TimeUnit.SECONDS.sleep(time);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
//end of code
#Override
public void textValueChanged(TextEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
The whole code is buggy.Read the Comments inline.
1.Idk why you are adding actionListener to the button 4 times(Keep one)
2.You have to have to change the actionPerformed1 to actionPerfromed as you are implementing the ActionListener and assigning this to button's ActionListener
public TextArea ta = new TextArea(30, 140);
TextArea tb = new TextArea(3, 130);
public int counter = 0;
//main class
public static void main(String[] args) {
f.show(true);//show is deprecated use setVisible(true) instead;
bb.addActionListener(ex);//1
}
public void actionPerformed1(ActionEvent Continue) {//have to change the actionPerformed1 to actionPerfromed
bb.addActionListener(this);//2 What is this assigning inside actionPerformed Need to be removed
counter++;
if (Continue.getSource() == bb && counter == 1) {
tb.append("Hey Buddy");
}
}
//graphics
public void init() {
bb.addActionListener(this);//3
Panel p;
setLayout(new BorderLayout());
p = new Panel();
ta.append("Hey");
bb.addActionListener(this);//4
p.add(bb);
p.setVisible(true);//already called a show for JFrame why you want to set Visible of Panel
}
I need to write a program that I will create a runnable jar and distribute. The functions should be like below:
when double click the jar, it will open a window.
it will ask the path where to save the image files.
it will then ask whether to add any prefix / suffix / both on every image along with timestamp for unique name.
it will also ask what image format to use.
the app can be minimized and closed
it will take a full screenshot whenever PrintScreen is pressed and save.
Please provide a programme that is complete. I have gathered pieces but could not put them in one. Here is my code :-
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.*;
import java.awt.image.RenderedImage;
import java.io.File;
import java.util.Date;
import javax.imageio.ImageIO;
import javax.swing.*;
public class MainClass
{
static String location = "";
static String prefix = "";
static String format = "";
static Date timestamp = new Date();
public static void main(String args[])
{
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
JFrame f = new JFrame("Text Field Examples");
f.getContentPane().setLayout(new FlowLayout());
final JTextField textField1 = new JTextField("Enter Location To Save Image Files");
textField1.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e){
textField1.setText("");
}
});
textField1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
location = textField1.getText();
System.out.println(location);
}
});
f.getContentPane().add(textField1);
final JTextField textField2 = new JTextField("Enter Prefix or Leave Empty");
textField2.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e){
textField2.setText("");
}
});
textField2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
prefix = textField2.getText();
System.out.println(prefix);
}
});
f.getContentPane().add(textField2);
String jlistData[] =
{
"GIF",
"PNG",
"JPG"
};
final JComboBox jlist = new JComboBox<String>( jlistData );
jlist.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
format = jlist.getSelectedItem().toString();
System.out.println(format);
}
});
f.getContentPane().add(jlist);
f.pack();
f.setVisible(true);
}
catch (Exception evt)
{
evt.printStackTrace();
}
try
{
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_PRINTSCREEN);
robot.keyRelease(KeyEvent.VK_PRINTSCREEN);
Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
RenderedImage image = (RenderedImage) t.getTransferData(DataFlavor.imageFlavor);
ImageIO.write(image, format, new File(new String(location+prefix+image+timestamp)));
}
catch(Exception e)
{
}
}
}
The first try catch block can open a window, take image format, prefix and storage location. The second try catch block alone can take screen shot when run not when printscreen key is pressed but with the first try catch it does not print anything. So, what to do to take the screenshot when printscreen key is pressed ?
I have approached the solution in a little bit another way.
As people always works with mouse while on online meeting, I removed the clause of PrintScreen button from keyboard and instead the attendees can click on swing window button to capture screen.
My solution as follows:
MainClass.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MainClass{
static String location = "";
static String prefix = "";
static String format = "";
public static void main(String args[])
{
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
final JFrame f = new JFrame("ENTER ALL DETAILS BELOW");
f.setAlwaysOnTop(true);
f.getContentPane().setLayout(new FlowLayout());
final JTextField textField1 = new JTextField("Enter Location To Save Image Files");
textField1.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e){
textField1.setText("");
}
});
f.getContentPane().add(textField1);
final JTextField textField2 = new JTextField("Enter MeetingID");
textField2.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e){
textField2.setText("");
}
});
f.getContentPane().add(textField2);
String jlistData[] =
{
"GIF",
"PNG",
"JPG"
};
final JComboBox jlist = new JComboBox<String>( jlistData );
f.getContentPane().add(jlist);
final JButton jButton = new JButton("OKAY");
jButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
location = textField1.getText();
prefix = textField2.getText();
format = jlist.getSelectedItem().toString();
System.out.println(location);
System.out.println(prefix);
System.out.println(format);
f.setVisible(false);
PrintButton.printButton();
}
});
f.getContentPane().add(jButton);
f.pack();
f.setVisible(true);
}
catch (Exception evt)
{
evt.printStackTrace();
}
}
}
PrintButton.java
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.UIManager;
public class PrintButton
{
static void printButton()
{
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
//final JFrame f = new JFrame("Print Screen App");
Dlg f = new Dlg(new JFrame(), "PRINT");
f.setAlwaysOnTop(true);
f.getContentPane().setLayout(new FlowLayout());
final JButton jButton = new JButton("OKAY");
jButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
PrintScreen.printScreen();
}
});
f.getContentPane().add(jButton);
f.pack();
f.setVisible(true);
}
catch (Exception evt)
{
evt.printStackTrace();
}
}
}
class Dlg extends JDialog {
public Dlg(JFrame frame, String str) {
super(frame, str);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
System.exit(0);
}
});
}
}
PrintScreen.java
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.KeyEvent;
import java.awt.image.RenderedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class PrintScreen
{
static void printScreen()
{
try
{
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_PRINTSCREEN);
robot.keyRelease(KeyEvent.VK_PRINTSCREEN);
Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
RenderedImage image = (RenderedImage) t.getTransferData(DataFlavor.imageFlavor);
ImageIO.write(image, MainClass.format, new File(new String(MainClass.location+ "\\" +MainClass.prefix+"_"+System.currentTimeMillis()+"."+MainClass.format)));
}
catch(Exception e)
{
}
}
}
I hope this will be helpfull to some freinds. Is there any scope to improve this?
How to create a installable version for Windows and Linux/Ubuntu and Linux/RedHat ?
I am new to programming, and created a little program to practice code. It is an authentication program where you type in a username and password, and only my specified username and password will work to make it show a picture. I typed all the code, and there was no error; but when I ran it and typed in the username and password, it failed to show the picture. Here is my code.
package main.Swing.com;
//imports
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputMethodEvent;
import java.awt.event.InputMethodListener;
import java.awt.event.TextEvent;
import java.awt.event.TextListener;
import java.util.EventObject;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
//class that carries other classes and carries some variables
public class Main extends javax.swing.JFrame implements ActionListener, TextListener, InputMethodListener {
JButton Test = new JButton("TEST IF YOU HAVE ACCESS TO THIS");
JButton Cancel = new JButton("CANCEL");
JTextField username = new JTextField(15);
JTextField password = new JTextField(15);
String n = ("Nathan");
int nathannam;
int nathannamer;
JButton superman;
JButton supermanny;
//constructor class that has the jframe
public Main() {
super("Authenticator");
setSize(300, 220);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLookAndFeel();
//creating the pane and defining some labels
JPanel pane = new JPanel();
JLabel UsernameLabel = new JLabel("Username: ");
JLabel PasswordLabel = new JLabel("Password: ");
//adding all the components to the pane
pane.add(UsernameLabel);
pane.add(username);
pane.add(PasswordLabel);
pane.add(password);
pane.add(Test);
pane.add(Cancel);
//adding the pane
add(pane);
//adding a event listener to my JButton titled Test
Test.addActionListener(this);
//checking if the password variable and name variable are both
//correct by taking the values assigned to each of them later
//on in the code and adding them together and if they add together
//to the correct amount it should display a button, but it doesn't
//which is the problem I am having
if (nathannam + nathannamer == 24) {
ImageIcon superman = new ImageIcon("JButton.png");
JButton supermanny = new JButton(superman);
pane.add(supermanny);
}
//setting visibility to true
setVisible(true);
//end of constructor class
}
//start of class that checks if the username is correct
public void METHODPREFORMED(ActionListener evt) {
Object source = ((EventObject) evt).getSource();
//testing if username is equivalent to my name which is nathan
if (source == Test) {
String get = username.getText().toString();
String notation = "Nathan";
//if it is equivalent a variable will be assigned to nathanam
for (int i = 0; i < get.length(); i++) {
if (get.substring(i) == notation) {
int nathannam = 14;
//if it is not it will assign a wrong variable to nathannam
} else {
int nathannam = 15;
}
}
}
}
//testing if password variable is correct
public void ACTIONPREFORMED(ActionListener evt) {
Object source = ((EventObject) evt).getSource();
//testing if password is correct
if (source == Test) {
String got = password.getText().toString();
String notition = "iamnathan";
//if it is equivalent a variable will be assigned to nathanamer
for (int i = 0; i < got.length(); i++) {
if (got.substring(i) == notition) {
int nathannamer = 10;
//if it is not equivalent nathannamer will be assigned a wrong variable
} else {
int nathannamer = 15;
}
}
}
} //setting the nimbus setlookandfeel that was implemented in java 7
private static void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//adding the main method
public static void main(String[] args) {
setLookAndFeel();
Main main = new Main();
}
#Override
public void textValueChanged(TextEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void caretPositionChanged(InputMethodEvent event) {
// TODO Auto-generated method stub
}
#Override
public void inputMethodTextChanged(InputMethodEvent event) {
// TODO Auto-generated method stub
}
}//end of program
You never call your test method from your implementation of actionPerformed(). Here's a much simplified version of your program that checks username when you click on TestAccess.
Going forward, see How to Use Password Fields for a working example of using JPasswordField.
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
/**
* #see
*/
public class Test {
private final JTextField username = new JTextField(15);
private final JButton test = new JButton("Test access");
private void display() {
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new GridLayout(0, 1));
f.add(username);
test.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("nathan".equalsIgnoreCase(username.getText()));
}
});
f.add(test);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
new Test().display();
});
}
}
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();
}
}
});
}
}