Create object on Jbutton click - java

I am trying to create an object when the user presses the button.So far, I've come up with the implementation bellow, but it does not seem to work.I haven't been dealing with Swing and Java UI at all so I am guessing it might be an amateur mistake.
The object I am trying to create is from another type called DebitCard.
private JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GenerateCard window = new GenerateCard();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public GenerateCard() {
}
{
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewButton = new JButton("Generate card");
btnNewButton.setBounds(112, 213, 216, 41);
frame.getContentPane().add(btnNewButton);
}
private class buttonEvent implements ActionListener {
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("Generate card")) {
DebitCard a = new DebitCard();
}
}
}

Based on your available code, you seem to have forgotten to register buttonEvent with btnNewButton
btnNewButton.addActionListener(new buttonEvent());
You might want to take a closer look at:
How to Use Buttons, Check Boxes, and Radio Buttons
How to Write an Action Listener
Laying Out Components Within a Container
Code Conventions for the Java TM Programming Language (this will make your code easier to read and it easier for you to read others)

Related

Currency Exchange API Java GUI

I am fairly new to programming of this level and I was wondering if someone could help me with this.
So I am trying to create a currency exchange app using Java, and I have a problem updating the values on the GUI to reflect the new value on the API. Essentially ever so often the values change and it shows on the console, however, the GUI value never updates and stays the same.
I thought ActionListener would help solve this problem but either I have not implemented it properly or I haven't googled and come up with a solution properly.
Thank you in advance for any help :)
Here is my code:
GUI.java
public class GUI extends JFrame {
static Arb arb = new Arb();
private JPanel contentPane;
public static void main(String[] args) throws IOException, InterruptedException {
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
try {
arb.runUpdate_fx("anAPI");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
Timer timer = new Timer(100 ,taskPerformer);
timer.setRepeats(true);
timer.start();
Thread.sleep(5000);
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUI frame = new GUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public GUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 1121, 765);
contentPane = new JPanel();
contentPane.setBackground(Color.BLACK);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JTextPane FXRate = new JTextPane();
FXRate.setForeground(new Color(255, 255, 255));
FXRate.setBackground(new Color(0, 0, 0));
FXRate.setEditable(false);
FXRate.setFont(new Font("Tahoma", Font.BOLD, 11));
panel_1.setLayout(new FlowLayout(FlowLayout.LEADING, 5, 5));
FXRate.setText("FX Rates\r\n\r\nEUR-AUD FX Rate: " + arb.fxEURAUD + "\r\nEUR-USD FX Rate: " + arb.fxEURUSD);
panel_1.add(FXRate);
}
}
Result:
EUR-AUD: 1.646659
after sometime
EUR-AUD: 1.646659
Expected Result:
EUR-AUD: 1.646659
after sometime
EUR-AUD: 1.80102
References are passed by value in Java.
JTextField textField = new JTextField();
String text = "Initial text";
textField.setText(text); // no displays "Initial text";
text = "Updated text"; // doesn't change what the panel displays
// the panel still holds a reference to the old text
textField.setText(text); // updates the reference the panel holds to your new text
In your event listener, you need to call setText with the updated string to actually make the textfield display that.
Your timer and event handler look good, but the update method only fetches new values into the Arb object; nothing takes those values and puts them into the GUI. You can do that explicitly in your event handler.after the update method returns. To enable that, you may want to make FXRate a member variable, so you can access it from the action listener.

Moving a JLabel for a game

I am coding a Backgammon game that plays by itself. While the backend code is mostly done, me and my colleague have pretty much no experience in GUI coding. We used the Designer given by a plugin for Eclipse and most of the code was generated.
So here's the thing. Right now there is a JFrame which has a JPanel in which are 2 JLabels, one for the background and one for 1 playing piece (when I figure this out, the rest of them will be added). These are all in an initialize() method which is run through EventQueue.invokeLater(new Runnable()). After the board and the piece are drawn, the startGame() method is called, which finally comes to a method called movePiece(), with the sole purpose of moving that JLabel piece I talked about before.
I have tried mostly everything I can think of, I have scoured the forums and only found people talking about layouts (which I may or may not be using, as I said, generated code) and the darn JLabel won't move when I call setLocation() inside the movePiece() method. It always throws a NullPointerException at that line which is bizarre because the image is already drawn. I will include part of the code below.
I know this will probably look like some of the worse codes ever, but please bear with my lack of skill and help me make this better. Any insights?
public class Main{
public JLabel image1;
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main window = new Main();
window.frame.setVisible(true);
new Main(1);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Main() {
initialize();
}
public Main(int i){
startGame();
}
public void startGame() {
//game code
movePiece(Move.getPos(), Move.getDest());
//rest of code
}
public void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 1023, 617);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setPreferredSize(new Dimension(800, 700));
JPanel panel_1 = new JPanel();
panel_1.setPreferredSize(new Dimension(200, 700));
frame.getContentPane().add(panel_1, BorderLayout.EAST);
JButton btnNewButton = new JButton("Start Game");
/* ACTION LISTENER FOR THE BUTTON */
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnNewButton.setFocusable(false);
btnNewButton.setForeground(SystemColor.windowBorder);
btnNewButton.setBackground(SystemColor.menu);
btnNewButton.setVerifyInputWhenFocusTarget(false);
btnNewButton.setRequestFocusEnabled(false);
btnNewButton.setRolloverEnabled(false);
btnNewButton.setFont(new Font("Verdana", Font.PLAIN, 11));
btnNewButton.setDebugGraphicsOptions(DebugGraphics.NONE_OPTION);
/* ADDING THE BTN TO PANEL 1 TO THE RIGHT */
panel_1.add(btnNewButton);
JPanel parentPanel = new JPanel();
parentPanel.setFocusable(false);
parentPanel.setEnabled(false);
parentPanel.setDoubleBuffered(false);
parentPanel.setDebugGraphicsOptions(DebugGraphics.NONE_OPTION);
parentPanel.setIgnoreRepaint(true);
parentPanel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
parentPanel.setBorder(null);
parentPanel.setPreferredSize(new Dimension(800, 700));
parentPanel.setBackground(SystemColor.menu);
frame.getContentPane().add(parentPanel, BorderLayout.WEST);
/* BACKGAMMON BOARD LABEL-->PANEL */
ImageIcon imageIcon = new ImageIcon(
new ImageIcon("images/bg.png").getImage()
.getScaledInstance(800, 551, Image.SCALE_SMOOTH));
parentPanel.setLayout(null);
ImageIcon imageIcon1 = new ImageIcon(
new ImageIcon("images/pl.png").getImage()
.getScaledInstance(50, 50, Image.SCALE_SMOOTH));
image1 = new JLabel("");
image1.setBounds(37, 36, 50, 50);
parentPanel.add(image1);
image1.setIcon(imageIcon1);
JLabel bg = new JLabel("");
bg.setBounds(10, 11, 800, 551);
bg.setIcon(imageIcon);
parentPanel.add(bg);
}
void movePiece(int pos, int dest) {
//null exception happens here, ignore the arguments
image1.setLocation(37 + 50,36);
}
You create an instance of Main and make it visible...
Main window = new Main();
window.frame.setVisible(true);
You then create a new instance of Main, which, through it's constructor, calls your moviePiece method...
new Main(1);
But the new instance of Main has nothing to do with the previous instance or any of the components which they created.
Instead, trying doing...
window.movePiece(Move.getPos(), Move.getDest());
instead of new Main(1);

Pass a String to another class

I'm writing an application where I need to get two String objects from the GUI to the nullObject class.
I'm relatively new to programming, and am trying my best to learn. If you have any tips on how to make this better, I'd be really thankful!
My GUI class:
package com.giuly.jsoncreate;
public class GUI {
private JFrame startFrame;
private JFrame chkFrame;
private JFrame osFrame;
private JFrame appVFrame;
private JPanel controlPanel;
private JButton nextPage;
private JButton cancel;
private JButton save;
public GUI() {
generateGUI();
}
public static void main(String[]args) {
GUI gui = new GUI();
}
public void generateGUI() {
//Creation of the First Frame
startFrame = new JFrame("JSCON Creator");
startFrame.setSize(1000, 700);
startFrame.setLayout(new FlowLayout());
startFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
//Panel Creation
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
//Button Creation
cancel = new JButton("Cancel");
cancel.setSize(100, 100);
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
nextPage = new JButton("Next");
nextPage.setSize(100, 100);
nextPage.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
startFrame.setVisible(false);
showText();
}
});
startFrame.add(controlPanel);
startFrame.add(cancel);
startFrame.add(nextPage);
startFrame.setVisible(true);
startFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public void showText() {
JFrame textFrame = new JFrame();
textFrame.setSize(1000, 700);
textFrame.setTitle("Text");
textFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
JPanel textPanel = new JPanel();
JLabel titleLabel = new JLabel("Title");
textPanel.add(titleLabel);
JLabel descrLabel = new JLabel("Description");
JTextField tfTitle = new JTextField("",15);
tfTitle.setForeground(Color.BLACK);
tfTitle.setBackground(Color.WHITE);
JTextField tfDescr = new JTextField("",30);
tfDescr.setForeground(Color.BLACK);
tfDescr.setBackground(Color.WHITE);
textPanel.add(tfTitle);
textPanel.add(descrLabel);
textPanel.add(tfDescr);
JButton buttonOK = new JButton("OK");
textPanel.add(buttonOK);
buttonOK.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String jsonTitle = tfTitle.getText();
String jsonDescr = tfDescr.getText();
System.exit(0);
}
});
textFrame.add(textPanel);
textFrame.setVisible(true);
}
I want to get the Strings jsonTitle and jsonDescr into another class, so I can store them. In the end I will have some Strings and I need to save them in a JSON file. I need a way to get those two Strings, what advice do you guys have?
Erick is correct with his answer. Just thought I should add additional info. If you declare jstonTitle and jsonDescr like your other fields using private you still will not be able to access these fields from another class. Coding up a getter for the fields along with declaring them at the top of GUI should solve your problem. Then just create an instance of GUI in your other class and call the method.
public String getJsonTitle(){
return this.jsonTitle;
}
You're declaring jstonTitle and jsonDescr inside the actionPerformed() method. That means that as soon as actionPerformed() exits you'll lose those variables. You need to declare them in an enclosing context. For example, you could make them fields on the GUI class. Still assign them in actionPerformed(), but declare them up at the top of GUI where you're declaring startFrame, chkFrame, etc.
That will give you the ability to access those values from anywhere within GUI.
Oh, BTW, get rid of System.exit(0);. (Have you actually tried to run your program?)

JLabel that changes text from one thing to another

I'm working on this program and I ran into another issue. I have a Jframe with a JLabel that I wish for it to change text from one thing to another. However, when I try to do that it doesnt show me the text changing, rather the last text I set it to.
How do I get my JLabel to cycle through text SLOWLY?
I'm trying a wait method to make the program go slowly so I can see if I can make it cycle through, but that doesnt seem to be working.
it would be helpful if someone could edit my code or make their own example of how to do this, THANKS!
public class CreditGraphics {
public String cardNum;
public JFrame frame;
public JPanel panel;
public JLabel label;
public JTextField text;
public CreditGraphics() {
synchronized(this){
try {
frame = new JFrame("HI");
panel = new JPanel();
label = new JLabel();
text = new JTextField(16);
panel.add(label);
panel.add(text);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.setPreferredSize(new Dimension(500, 500));
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
wait(4000);
label.setText("Hi");
wait(4000);
frame.revalidate();
frame.repaint();
label.setText("Hello");
frame.revalidate();
frame.repaint();
text.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cardNum = text.getText();
}
});
}
catch(InterruptedException e) {
e.printStackTrace();
}}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new CreditGraphics();
}
});
}
public void checkCard(){
}
}
As suggested by #trashgod use Swing Timer that is more suitable for swing application to perform a task once, after a delay or to perform a task repeatedly.
sample code:
private Timer timer;
...
label.setText("Hi");
// delay of 4 seconds
timer=new Timer(4000,new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
label.setText("Hello");
// timer.stop(); // stop the timer if repeated mode is on
}
});
timer.setRepeats(false); // you can turn-on it if needed
timer.start();
Note:
There is no need to call frame.repaint() and frame.revalidate() in this case.
Override getPreferredSize() to set the preferred size of the JPanel in case of custom painting.
sample code:
JPanel panel = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(..., ...);
}
};
read more...
Do not use Thread.sleep() or wait() as it will freeze your Swing application.
Instead you should use a javax.swing.Timer
See the Java tutorial How to Use Swing Timers and Lesson: Concurrency in Swing for more information and examples.

How to tell if a JFrame window has already been opened?

I have a JFrame with a Button that opens a different JFrame. But I want the button to only open the second frame once. Problem is, every time I click it I get a new instance of the frame. This must be a very common problem, since I'm following a book on how to create this GUI. I find it odd that the author didn't mention this "feature".
So how do I keep my button from opening multiple copies of the new frame?
Instead of letting the button create a new JFrame every time, make the second JFrame a member of the first JFrame, and only let the button call jframe2.setVisible(true);:
class JFrame1 {
JFrame2 jframe2=...;
JButton button=...;
JFrame1() {
...
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jframe2.setVisible(true);
}
});
...
}
}
UPDATED!
try this:
JFrame frame2 = new JFrame(); // instance variable
...
//when button is clicked
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(!frame2.isVisible())
frame2.setVisible(true);
}
});
make sure you are handling the closing of all of the JFrames manually like this:
frame2.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
// handle closing the window
frame2.setVisible(false);
frame2.dispose();
}
});
instead of using the JFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
hope this helps.
You should keep a reference to the sub frame you open for first time. At second time you first check if you have a reference or not and then decide to create a new frame or to put the focus onto the existing open frame.
Example as answer to comment of OP (similar to other answer of #AlexanderTorstling, but not immediately creating the sub frame):
class MainFrame extends JFrame {
private JFrame subFrame = null;
MainFrame() {
...
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (subFrame == null) {
subFrame = new JFrame();
...
}
subFrame.setVisible(true);
}
});
}
}
This example has also the advantage to give you the possibility to close the subframe via a registered WindowAdapter if the main frame is closed.
please try this one
JFrame frame2 = new JFrame(); // instance variable
boolean secondWindowIsOpne = false;
...
//when button is clicked
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(secondWindowIsOpne == false){
frame2.setVisible(true);
secondWindowIsOpne = true;
}
else{
System.out.println("This Window is already running");
}
});
make sure you are handling the closing of all of the JFrames manually like this:
frame2.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
// handle closing the window
secondWindowIsOpne = false;
frame2.setVisible(false);
frame2.dispose();
}
});

Categories