Adding an int per click (java) - java

I am making a "fake virus" in java. when you run it a window called "Your computer has a virus" pops up and the window has a button that says "Your computer has (1) viruses. Click here to uninstall them" but when you click it one more window pops up. but i want it to be like each time you click it the number of "viruses" is added 1 to. (For example the second window that pops up after clicking button says "Your computer has (2) viruses"). I have tried to add it but it didn't work. (sorry for my terrible grammar). Here is my code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class FirstWindow extends JFrame {
int virusAmount = 1;
private static final long serialVersionUID = 1L;
public FirstWindow(){
super("Your computer has a virus");
setSize(400, 75);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel p = new JPanel();
JButton b = new JButton("Your computer has (" + virusAmount++ + ") virus(es). Click here to uninstall them.");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
FirstWindow f2 = new FirstWindow();
f2.setVisible(true);
}
});
p.add(b);
add(p);
}
}

Just define it in the constructor:
public FirstWindow(int i){}
Full example:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class FirstWindow extends JFrame {
int virusAmount;
private static final long serialVersionUID = 1L;
public FirstWindow(int i) {
virusAmount = i;
setSize(400, 75);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel p = new JPanel();
JButton b;
if(virusAmount == 1){
b = new JButton("Your computer has a virus");
}
else{
b = new JButton("Your computer has (" + virusAmount + ") virus(es). Click here to uninstall them.");
}
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
FirstWindow f2 = new FirstWindow(virusAmount+1);
f2.setVisible(true);
}
});
p.add(b);
add(p);
}
}
public class Main {
public static void main(String[] args) {
FirstWindow fw = new FirstWindow(1);
fw.setVisible(true);
}
}

Related

Swing window not opening

I am creating a NotePad app in Java Swing but when I am trying to open a popup to set a title, it is not showing up.
The class that calls the popup:
import java.io.*;
import java.util.*;
import java.awt.event.*;
import javax.swing.*;
public class NewFile implements ActionListener{
public static String title;
public void actionPerformed(ActionEvent e){
PopupFileName popup = new PopupFileName();
/*try{
Thread.sleep(30000);
}catch (InterruptedException o){
o.printStackTrace();
}*/
JTextArea titl = popup.title;
title = titl.getText();
try{
File writer = new File(title+".txt");
if(writer.createNewFile()){
System.out.println("file created");
}else{
System.out.println("file exists");
}
}catch (IOException i) {
System.out.println("An error occurred.");
i.printStackTrace();
}
}
}
The popup class that is supposed to open:
import javax.swing.*;
public class PopupFileName{
static JFrame popup = new JFrame("File Title");
static JLabel titlel = new JLabel("Title:");
static public JTextArea title = new JTextArea();
public static void main(String[] args){
popup.setSize(200,300);
popup.setVisible(true);
popup.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
popup.add(titlel);
popup.add(title);
}
}
Is there any way I can make it visible and make it able to get the text before it is created?
Start by taking a look at:
Creating a GUI With Swing
How to Write an Action Listener
How to Use Scroll Panes
How to Use Buttons, Check Boxes, and Radio Buttons
How to Make Dialogs
You're running in an event driven environment, this means, something happens and then you respond to it.
The problem with your ActionListener is, it's trying to present a window and then, immediately, trying to get some result from it. The problem is, the window probably isn't even present on the screen yet.
What you need is some way to "stop" the code execution until after the user responds. This is where a modal dialog comes in.
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
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.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
JButton btn = new JButton("Test");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String title = PopupFileName.getTitle(TestPane.this);
System.out.println(title);
}
});
add(btn);
}
}
public static class PopupFileName extends JPanel {
private JLabel titlel = new JLabel("Title:");
private JTextArea title = new JTextArea(20, 40);
public PopupFileName() {
setLayout(new BorderLayout());
add(titlel, BorderLayout.NORTH);
add(new JScrollPane(title));
}
public String getTitle() {
return title.getText();
}
public static String getTitle(Component parent) {
PopupFileName popupFileName = new PopupFileName();
int response = JOptionPane.showConfirmDialog(parent, popupFileName, "Title", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
switch (response) {
case JOptionPane.OK_OPTION:
return popupFileName.getTitle();
default: return null;
}
}
}
}

Having a user search and input a file in Java

I am working a side project that involves the user entering a file. I know there is the option for them to enter a string representing the text files name and then have the computer search for it but that would mean the file has to be in a certain location on the computer or the user has to enter the whole pathway to the file.
Is there anything similar to file input tag in HTML5 that prompts a window that allows the user to search through their laptop for the file? I've attached a picture of what I mean would be prompted on a mac.
Use file chooser by swing
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class FileChooserTest extends JFrame {
private JTextField filename = new JTextField(), dir = new JTextField();
private JButton open = new JButton("Open"), save = new JButton("Save");
public FileChooserTest() {
JPanel p = new JPanel();
open.addActionListener(new OpenL());
p.add(open);
save.addActionListener(new SaveL());
p.add(save);
Container cp = getContentPane();
cp.add(p, BorderLayout.SOUTH);
dir.setEditable(false);
filename.setEditable(false);
p = new JPanel();
p.setLayout(new GridLayout(2, 1));
p.add(filename);
p.add(dir);
cp.add(p, BorderLayout.NORTH);
}
class OpenL implements ActionListener {
public void actionPerformed(ActionEvent e) {
JFileChooser c = new JFileChooser();
// Demonstrate "Open" dialog:
int rVal = c.showOpenDialog(FileChooserTest.this);
if (rVal == JFileChooser.APPROVE_OPTION) {
filename.setText(c.getSelectedFile().getName());
dir.setText(c.getCurrentDirectory().toString());
}
if (rVal == JFileChooser.CANCEL_OPTION) {
filename.setText("You pressed cancel");
dir.setText("");
}
}
}
class SaveL implements ActionListener {
public void actionPerformed(ActionEvent e) {
JFileChooser c = new JFileChooser();
// Demonstrate "Save" dialog:
int rVal = c.showSaveDialog(FileChooserTest.this);
if (rVal == JFileChooser.APPROVE_OPTION) {
filename.setText(c.getSelectedFile().getName());
dir.setText(c.getCurrentDirectory().toString());
}
if (rVal == JFileChooser.CANCEL_OPTION) {
filename.setText("You pressed cancel");
dir.setText("");
}
}
}
public static void main(String[] args) {
run(new FileChooserTest(), 250, 110);
}
public static void run(JFrame frame, int width, int height) {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(width, height);
frame.setVisible(true);
}
} ///:~
File dialog

JButton & Action & KeyBinding

I have created a JButton class that recieving Action, the JButton class includes keystrokes & mouse listener so i can use the same class in multiple frames as needed.
My problems is that:
JButton not getting the focus when pressing the key, but it doing the action.
i need to make a new background or something that tell the user that the button did the action.
Any ideas??
Here is my code:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.KeyStroke;
import javax.swing.SwingConstants;
import javax.swing.border.LineBorder;
import swtdesigner.SwingResourceManager;
public class IButtonSave extends JButton{
private static final long serialVersionUID = 1L;
private Action action = null;
public IButtonSave() {
super();
setFocusPainted(true);
setFocusable(true);
try {
jbInit();
} catch (Throwable e) {
e.printStackTrace();
}
}
private void jbInit() throws Exception {
setMargin(new Insets(0, 0, 0, 0));
setBorder(new LineBorder(Color.black, 1, true));
setIconTextGap(0);
setHorizontalTextPosition(SwingConstants.CENTER);
setVerticalTextPosition(SwingConstants.TOP);
setPreferredSize(new Dimension(50, 43));
setMinimumSize(new Dimension(50, 43));
setMaximumSize(new Dimension(50, 43));
addMouseListener(new ThisMouseListener());
setVerifyInputWhenFocusTarget(true);
}
public void setAction(Action a){
action = a;
KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_F1,0,true);
KeyStroke ks2 = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0);
getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(ks, "Save");
getInputMap(JComponent.WHEN_FOCUSED).put(ks2, "Save");
getActionMap().put("Save", a);
setText("Save [F1]");
setIcon(SwingResourceManager.getIcon(SwingResourceManager.class, "/images/small/save.png"));
setToolTipText("[F1]");
}
private class ThisMouseListener extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
this_mouseClicked(e);
}
}
protected void this_mouseClicked(MouseEvent e) {
if(e.getClickCount() >= 1){
action.actionPerformed(null);
}
}
}
Why extend JButton class when you can simply add KeyBindings to its instance?
Not to sure what you want but this works fine for me:
Basically a JButton which can be activated by mouse click, or pressing F1 (as long as focus is in window and if pressed will shift focus to JButton) or ENTER (only when in focus of JButton).
When the AbstractAction is called it will call requestFocusInWindow() on JButton (thus pressing F1 will make button gain focus which is what I think you wanted):
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
public class Test {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JButton btn = new JButton("Button");
AbstractAction aa = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
System.out.println("Here");
btn.requestFocusInWindow();//request that the button has focus
}
};
//so button can be pressed using F1 and ENTER
btn.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Enter");
btn.getActionMap().put("Enter", aa);
btn.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0), "F1");
btn.getActionMap().put("F1", aa);
btn.addActionListener(aa);//so button can be clicked
JTextField tf = new JTextField("added to show ENTER wont work unless button in focus");
frame.add(tf);
frame.add(btn, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
});
}
}
UPADTE:
alternatively as #GuillaumePolet suggested (+1 to him) override processKeyBinding of JButton and check for appropriate key and than call the method:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
public class Test {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JButton btn = new JButton("Button") {
#Override
protected boolean processKeyBinding(KeyStroke ks, KeyEvent ke, int i, boolean bln) {
boolean b = super.processKeyBinding(ks, ke, i, bln);
if (b && ks.getKeyCode() == KeyEvent.VK_F1) {
requestFocusInWindow();
}
return b;
}
};
AbstractAction aa = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
System.out.println("Here");
}
};
//so button can be pressed using F1 and ENTER
btn.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Enter");
btn.getActionMap().put("Enter", aa);
btn.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0), "F1");
btn.getActionMap().put("F1", aa);
btn.addActionListener(aa);//so button can be clicked
JTextField tf = new JTextField("added to show ENTER wont work unless button in focus");
frame.add(tf);
frame.add(btn, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
});
}
}
Not sure this is the best way to do it, but it works decently enough and if it is not the best way, you get a free SSCCE out of this answer.
I override processKeyBindings() and if it returns true then I grab the focus to indicate that the action has been performed. If you want to do something else you just need to modify the code there.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
public class IButtonSave extends JButton {
private static final long serialVersionUID = 1L;
public IButtonSave() {
super();
setFocusPainted(true);
setFocusable(true);
}
#Override
protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) {
boolean processKeyBinding = super.processKeyBinding(ks, e, condition, pressed);
if (processKeyBinding) {
requestFocusInWindow();
}
return processKeyBinding;
}
#Override
public void setAction(Action a) {
super.setAction(a);
KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0, true);
KeyStroke ks2 = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(ks, "Save");
getInputMap(JComponent.WHEN_FOCUSED).put(ks2, "Save");
getActionMap().put("Save", a);
setText("Save [F1]");
setToolTipText("[F1]");
}
protected void initUI() {
JFrame frame = new JFrame(IButtonSave.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextArea textarea = new JTextArea(5, 30);
JPanel buttonPanel = new JPanel();
AbstractAction someAction = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
System.err.println("Action performed");
}
};
IButtonSave button = new IButtonSave();
button.setAction(someAction);
buttonPanel.add(button);
frame.add(new JScrollPane(textarea));
frame.add(buttonPanel, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new IButtonSave().initUI();
}
});
}
}

Java program exits when I click OK button in JOptionPane.showMessageDialog

when I click the OK button in second.java program, the program exit the program. I want it not to exit (since there is a thread running). I tried removing setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE).
CODE
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.JOptionPane;
import javax.swing.JTextField;
public class second extends JFrame implements ActionListener {
JLabel enterName;
JTextField name;
JButton click;
String storeName;
public second(){
setLayout(null);
setSize(300,250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
enterName = new JLabel("Enter Your Name: ");
click = new JButton("Click");
name = new JTextField();
enterName.setBounds(60,30,120,30);
name.setBounds(80,60,130,30);
click.setBounds(100,190,60,30);
click.addActionListener(this);
add(click);
add(name);
add(enterName);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == click) {
storeName = name.getText();
JOptionPane.showMessageDialog(null, "Hello" + storeName);
System.exit(0);
}
}
public static void main(String args[]){
second s = new second();
s.setVisible(true);
}
}
Many Thanks
You'll need to remove the System.exit(0); line. That's all.

Should open new window while clicking a button?

I know that it is very simple question, but I can't find a solution.
I have a main swing dialog and other swing dialog. Main dialog has a button.
How can I make that after clicking a button the other dialog opens?
EDIT:
When I try this:
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
NewJDialog okno = new NewJDialog();
okno.setVisible(true);
}
I get an error:
Cannot find symbol NewJDialog
The second window is named NewJDialog...
You'll surely want to look at How to Make Dialogs and review the JDialog API. Here's a short example to get started. You might compare it with what you're doing now.
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class DialogTest extends JDialog implements ActionListener {
private static final String TITLE = "Season Test";
private enum Season {
WINTER("Winter"), SPRING("Spring"), SUMMER("Summer"), FALL("Fall");
private JRadioButton button;
private Season(String title) {
this.button = new JRadioButton(title);
}
}
private DialogTest(JFrame frame, String title) {
super(frame, title);
JPanel radioPanel = new JPanel();
radioPanel.setLayout(new GridLayout(0, 1, 8, 8));
ButtonGroup group = new ButtonGroup();
for (Season s : Season.values()) {
group.add(s.button);
radioPanel.add(s.button);
s.button.addActionListener(this);
}
Season.SPRING.button.setSelected(true);
this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
this.add(radioPanel);
this.pack();
this.setLocationRelativeTo(frame);
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
JRadioButton b = (JRadioButton) e.getSource();
JOptionPane.showMessageDialog(null, "You chose: " + b.getText());
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new DialogTest(null, TITLE);
}
});
}
}

Categories