program instantly terminates instead of staying in a constant loop - java

i am trying to make a program that, when a button is pressed it will start to create many invisible frames to the point it should crash a pc. however when i try and run it the console instantly terminates
this is the code for the program:
public class JavaTester extends JFrame {
static JFrame frame;
static ImageIcon img;
private static boolean a = false;
public JavaTester() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(670, 700);
frame.setLocationRelativeTo(null);
frame.getContentPane().setBackground(new Color(0,255,0,0));
frame.getContentPane().setLayout(null);
frame.setUndecorated(true);
frame.setResizable(false);
frame.setVisible(true);
addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
a = true;
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
});
}
public static void main(String[] args) {
do {
if (a) {
while (true)
new JavaTester();
}
} while (a = false);
}
}
is this a problem with the way my loops are ordered or is there something else that makes it instantly stop running?

Problem is here:
while (a = false);
By doing that, a is set to false.
Instead you need to use conditional operator equal to (a == false)

Related

How to check if a JFrame is open by checking it's one of the components are visible

I have this code sample in a separate jDialog (jDialog is in the same package as that of JFrame) which used to check (using a Thread) if the jCheckBox1 in the jFrame is whether visible or not. JDialog is set to visible by clicking a JLabel (Change Password) in JFrame. I have not set the visibility of the JFrame even to false even after I click on the Change Password JLabel.
The problem I encountered is that even if the JFrame is not visible i.e when I run the JDialog separately (without clicking on the Change Password JLabel) it prints the "Visible" and I'm more than sure that the jFrame is not visible and not running.
This is the code snippet (Thread) I have used to check the visibility of the JFrame's jCheckBox1:
LockOptions lock = new LockOptions();
private void setLocation2() {
new Thread() {
public void run() {
boolean running = true;
while (running) {
try {
Thread.sleep(1000);
if (lock.jCheckBox1.isVisible()) {
System.out.println("Visible");
} else {
System.out.println("Not Visible");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
And this is the Code I have written in JFrame's Change Password JLabel:
private void jLabel9MouseClicked(java.awt.event.MouseEvent evt) {
Container c = new ChangePassword(this, rootPaneCheckingEnabled);
if (!c.isShowing()) {
c.setVisible(true);
hideMeToSystemTray();
this.requestFocusInWindow();
}
}
But when I run the JDialog separately (without clicking on the Change Password JLabel) it prints the "Visible"
I have attached a Screenshots of both JFrame and JDialog
JFrame containing jCheckBox1
JDialog:
OK, let's have the simplest possible example.
The following code creates a main frame having a button to create a new frame of class LockOptionsWindow, which extends JFrame.
The class FrameDemo implements Runnable. So can it be accessed on the event dispatching thread using SwingUtilities.invokeLater as mentioned in Swing's Threading Policy. So it is possible creating a new thread checklockoptionswindow which then can check whether the new window created by the button is visible or not visible.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FrameDemo extends WindowAdapter implements ActionListener, Runnable {
private LockOptionsWindow lockoptionswindow;
private Thread checklockoptionswindow = new Thread();
private void showLockOptionsWindow() {
if (lockoptionswindow != null && lockoptionswindow.isDisplayable()) {
lockoptionswindow.setVisible(true);
lockoptionswindow.setExtendedState(Frame.NORMAL);
} else {
lockoptionswindow = new LockOptionsWindow();
lockoptionswindow.setSize(new Dimension(300, 100));
lockoptionswindow.setVisible(true);
lockoptionswindow.setExtendedState(Frame.NORMAL);
}
}
private void startCheckLockOptionsWindow() {
if (!checklockoptionswindow.isAlive()) {
checklockoptionswindow = new Thread() {
public void run() {
boolean running = true;
while (running) {
try {
Thread.sleep(1000);
if (lockoptionswindow.isVisible()) {
if (lockoptionswindow.getExtendedState() == Frame.ICONIFIED) {
System.out.println("Visible iconified");
} else {
System.out.print("Visible on screen ");
int x = lockoptionswindow.getLocation().x;
int y = lockoptionswindow.getLocation().y;
System.out.println("at position " + x + ", " + y);
}
} else {
System.out.println("Not Visible");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
checklockoptionswindow.start();
}
}
public void actionPerformed(ActionEvent e) {
showLockOptionsWindow();
startCheckLockOptionsWindow();
}
public void run() {
JFrame frame = new JFrame("FrameDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Show LockOptions frame");
button.addActionListener(this);
Container contentPane = frame.getContentPane();
contentPane.add(button);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new FrameDemo());
}
class LockOptionsWindow extends JFrame {
public LockOptionsWindow() {
super("LockOptions frame");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
}
}
Edited to determine whether the LockOptionsWindow is visible iconified only or is really showed as window on the screen.

Listening for the CAPS key [duplicate]

This question already has answers here:
KeyListener after Button Is Pressed
(2 answers)
Closed 6 years ago.
I have been trying to build a small utility that listens for when the user presses the "Caps Lock" key. The program should start and first display wheter the key is ON or OFF. The program should also listen for any changes, and update the frame accordingly.
Unfortunately, the only part I can get right is in the beginning, when the frame displays if the Caps key is on or off. After that, it gets stuck. Even if I press the key it changes nothing on screen.
The program is also supposed to produce a .beep() sound when the caps key is on, but it only works if I start it with the key on.
Code:
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(400, 400);
JLabel label = new JLabel("CAPS LOCK IS ON!");
JLabel label1 = new JLabel("CAPS LOCK IS OFF!");
boolean check = Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK);
if (check == true) {
frame.repaint();
frame.add(label);
Toolkit.getDefaultToolkit().beep();
} else {
frame.repaint();
frame.add(label1);
}
keyPressed(KeyCode.CAPS);
frame.show();
}
public static void keyPressed(KeyCode e) {
boolean check = Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK);
if (check == true) {
Toolkit.getDefaultToolkit().beep();
}
}
EDIT: If you only want to know if the Caps key is toggled(on):
if (Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK)) {
label.setText("CAPS LOCK IS ON!");
Toolkit.getDefaultToolkit().beep();
} else {
label.setText("CAPS LOCK IS OFF");
}
This way it only beeps when the caps key is toggled and doesnt beep when is not toggled.
If you want to track "Caps Lock" only within your application, you can do something like:
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher()
{
#Override
public boolean dispatchKeyEvent(KeyEvent e)
{
if (KeyEvent.VK_CAPS_LOCK == e.getKeyCode())
{
boolean check = Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK);
// do something here
}
return false;
}
});
You also might need to track focus and update state when your app is re-focused.
However if you want your application to track Caps Lock system-wide as I suspect you do, than unfortunately you are out of luck. There is no way in pure Java to do it as this is a very OS-specific feature. Still for Windows there is a wrapper around C-code https://github.com/kristian/system-hook
As mentioned in other answers, your code isn't registering a KeyListener, so it's simply reading the locking state of the key once.
To capture the state change on CapsLock, You need to watch for the keyPressed (cap lock on) and keyReleased (cap lock off) separately.
Take a look at this example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class CapChecker {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel();
frame.add(label);
frame.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_CAPS_LOCK && Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK)) {
label.setText("CAPS LOCK IS ON!");
Toolkit.getDefaultToolkit().beep();
} else {
label.setText("" + e.getKeyChar());
}
}
#Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_CAPS_LOCK) {
label.setText("CAPS LOCK IS OFF!");
}
}
});
frame.setVisible(true);
}
});
}
}
After the Frame is shown, your program does nothing. You have to register a KeyListener to the frame:
frame.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
})
In these methods you can react to key presses or releases.

java detect when any window is created or closed

Is it possible to be notified whenever any window in the application was created or closed?
At the moment I'm polling Window.getWindows() but I would prefer to get notified instead.
What I have:
List<Window> previousWindows = new ArrayList<>();
while (true) {
List<Window> currentWindows = Arrays.asList(Window.getWindows());
for (Window window : currentWindows) {
if (!previousWindows.contains(window)) {
//window was created
}
}
for (Window window : previousWindows) {
if (!currentWindows.contains(window)) {
//window was closed
}
}
previousWindows = currentWindows;
Thread.sleep(1000);
}
What I'd like:
jvm.addWindowListener(this);
#Override
public void windowWasDisplayed(Window w) {
//window was created
}
#Override
public void windowWasClosed(Window w) {
//window was closed
}
You can register listeners that receive any subset of types of AWT events via the windowing Toolkit. From those you can select and handle the WindowEvents for windows being opened and closed, something like this:
class WindowMonitor implements AWTEventListener {
public void eventDispatched(AWTEvent event) {
switch (event.getID()){
case WindowEvent.WINDOW_OPENED:
doSomething();
break;
case WindowEvent.WINDOW_CLOSED:
doSomethingElse();
break;
}
}
// ...
}
class MyClass {
// alternative 1
public void registerListener() {
Toolkit.getDefaultToolkit().addAWTEventListener(new WindowMonitor(),
AWTEvent.WINDOW_EVENT_MASK);
}
// alternative 2
public void registerListener(Component component) {
component.getToolkit().addAWTEventListener(new WindowMonitor(),
AWTEvent.WINDOW_EVENT_MASK);
}
}
I would recommend alternative 2, where the Component from which you obtain the Toolkit is the main frame of your application (there should be only one), but alternative 1 should work out for you if you have to do this without reference to any particular component (for instance, before any have been created).
Do note, however, that registering an AWTEventListener is subject to a security check.
If you create the additional windows (I assume JFrames) yourself, you can use the addWindowListener method. The WindowAdapter abstract class allows you to override methods for the events you are interested in:
import java.awt.event.*;
import javax.swing.*;
public class MultipleWindows {
public static void main(String[] arguments) {
SwingUtilities.invokeLater(() -> new MultipleWindows().createAndShowGui());
}
private void createAndShowGui() {
JFrame frame = new JFrame("Stack Overflow");
frame.setBounds(100, 100, 800, 600);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.add(new JLabel("Testing multiple windows..."));
frame.getContentPane().add(panel);
WindowAdapter windowAdapter = new WindowAdapter() {
#Override
public void windowOpened(WindowEvent windowEvent) {
System.out.println("Window opened: "
+ windowEvent.getWindow().getName());
}
#Override
public void windowClosed(WindowEvent windowEvent) {
System.out.println("Window closed: "
+ windowEvent.getWindow().getName());
}
};
for (int windowIndex = 2; windowIndex < 6; windowIndex++) {
String title = "Window " + windowIndex;
JFrame extraFrame = new JFrame(title);
extraFrame.setName(title);
extraFrame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
extraFrame.addWindowListener(windowAdapter);
extraFrame.setVisible(true);
}
frame.setVisible(true);
}
}

JAVA Automatic Frame creator

I am trying to create a spam of frames and i want to stop it when i press HOME key ,but it doesn't focus on the first frame( which i can use the keylistener on ). I tried without the first frame , just the ones in the loop with focus set on true but still doesn't work.
public class Script extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
public static boolean isTrue = true;
public Script(){
addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_HOME)
System.exit(1);
}
});
}
public static void main(String[] args) {
JFrame frames = new Script();
frames.setSize(300, 300);
frames.setVisible(true);
frames.setFocusable(true);
frames.setLocation(800, 1000);
frames.setDefaultCloseOperation(EXIT_ON_CLOSE);
while(isTrue == true){
int x = (int)(1+Math.random() * (1500-1));
int y = (int)(1+Math.random() * (900-1));
JFrame frame = new Script();
frame.setVisible(true);
frame.setFocusable(false);
frame.setSize(300, 300);
frame.setLocation(x, y);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
}
Never use an infinite while loop like that without Thread.sleep

Unable to set background color of checkbox at runtime

There is a class AgentHome which extends JFrame.
AgentHome has a JPanel rem_panel. Checkboxes are added dynamically into rem_panel…number of checkboxes depending on the number of entries in the database table from where the text to be displayed by the textboxes are read.
AgentHome has an integer variable x and a checkbox arraylist rem_cbarr.
rem_cbarr stores the checkboxes as they are created and added to rem_panel.
I am trying to set the background color of these checkboxes to red when the variable x is set to 1 as the program executes.
I have implemented the TickerBehaviour of JADE framework to check if the variable x is set to 1.
I am unable to set the background color of the checkboxes to red. This is the code I have implemented. Please help. Thanks.
public void setup()
{
Behaviour loop = new TickerBehaviour( this, 2000 )
{
protected void onTick() {
timer();
}
};
addBehaviour( loop );
}
public void timer()
{
AgentHome hm=new AgentHome();
if(hm.x==1)
{
for (int i = hm.rem_cbarr.size()-1; i>=0; i--)
{
JCheckBox cb=hm.rem_cbarr.get(i);
cb.setBackground(Color.red);
hm.rem_panel.revalidate();
hm.rem_panel.repaint();
}
}
}
GUI operations need to be done on the EDT (Event Dispatcher Thread). In java this happens by calling SwingUtilities.invokeLater(Runnable run).
A number of things...
UI components should only ever be updated within the context of the Event Dispatching Thread
You should never perform any action which might block the Event Dispatching Thread (like using loops or Thread#Sleep to try and update the screen)
The Event Dispatching Thread is responsible for dispatching paint updates...
JCheckBox is transparent by default.
public class FlashCheckBox {
public static void main(String[] args) {
new FlashCheckBox();
}
public FlashCheckBox() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.add(new FlashyCheckBox());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class FlashyCheckBox extends JCheckBox {
private final Color defaultBackground;
private int flash;
private Timer flashTimer;
public FlashyCheckBox() {
defaultBackground = getBackground();
flashTimer = new Timer(500, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
flash++;
if (flash % 5 == 0) {
setOpaque(false);
setBackground(defaultBackground);
flashTimer.stop();
} else if (flash % 2 == 0) {
setBackground(Color.YELLOW);
setOpaque(true);
} else {
setBackground(defaultBackground);
setOpaque(false);
}
repaint();
}
});
flashTimer.setRepeats(true);
flashTimer.setCoalesce(true);
flashTimer.setInitialDelay(0);
addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
flashTimer.restart();
}
});
}
}
}

Categories