Use If-Else statement in SubmitListener - java

Trying to develop a GUI, but I've hit a snag:
I am using a submit button, which will look at a txtEnter field. If the user types "yes" in the txtEnter field and clicks submit, it will execute a shell script. If the user types "no" there will be no action. I know the command to run shell script is Runtime.getRuntime().exec(myShellScript);
How I can use an if-else statement in the SubmitListner to check for the user's input?
import javax.swing.*; import javax.swing.event.DocumentListener;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;public class Executer private JLabel lblCommand;
private JTextField txtEnter;
private JButton btNext, btPrevious, btSubmit;
private JPanel panel;
public static void main(String[] args) {
new Executer();
}
public Executer() {
JFrame frame = new JFrame("Script Executer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,300);
frame.setVisible(true);
myPanel();
Text();
Fields();
Buttons();
frame.add(panel);
frame.setVisible(true);
}
public void myPanel() {
panel = new JPanel();
panel.setLayout(null);
}
public void Text(){
lblCommand = new JLabel("Enter Here");
lblCommand.setBounds(145, 100, 150, 20);
Font styleOne = new Font("Arial", Font.BOLD, 13);
lblCommand.setFont(styleOne);
panel.add(lblCommand);
}
public void Fields () {
txtEnter = new JTextField();
txtEnter.setBounds(230, 100, 120, 20);
panel.add(txtEnter);
}
public void Buttons() {
btNext = new JButton ("Next");
btNext.setBounds(300,215,100,20);
panel.add(btNext);
btPrevious = new JButton ("Previous");
btPrevious.setBounds(190,215,100,20);
panel.add(btPrevious);
btSubmit = new JButton("Submit");
btSubmit.setBounds(80,215,100,20);
panel.add(btSubmit);
}
class SubmitListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
}}}

You have to assign your Actionlistener to your button:
btSubmit = new JButton();
btSubmit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// here the click happend so you can check your Textfield
String userEntered = txtEnter.getText();
if(userEntered.equalsIgnoreCase("yes"))
{
//run your script
}
}
});

Related

Change button's text with an external combobox java

I've two class. Can i change a text of a button in a class "home" with an actionlistener of the combobox in a class "panelGestisciImpianti"? I don't unterstand becasue don't works.
The code is this:
//home
package s;
public class home extends JFrame {
private JPanel contentPane;
private panelImpostazioni panel5= new panelImpostazioni();
private JButton btnImpostazioni = new JButton("no"); //$NON-NLS-1$
public static void main(String[] args) {
home frame = new home();
frame.setVisible(true);
}
public home() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setExtendedState( JFrame.MAXIMIZED_BOTH) ;
setBounds(0, 0, 1963, 688);
contentPane = new JPanel();
setContentPane(contentPane);
contentPane.setLayout(null);
btnImpostazioni.setBounds(0, 560, 140, 140);
contentPane.add(btnImpostazioni);
btnImpostazioni.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
contentPane.add(panel5);
revalidate();
repaint();
}
});
}
public void changetext() {
btnImpostazioni.setText("yes");
}
}
//panelGestisciImpostazioni
package s;
public class panelImpostazioni extends JPanel {
private JComboBox comboboxLingua = new JComboBox();
static home h=new home();
public panelImpostazioni() {
setBounds(140, 0, 800, 560);
setLayout(null);
comboboxLingua.setBounds(100, 24, 150, 45);
comboboxLingua.setModel(new DefaultComboBoxModel(new String[] {"italiano", "inglese"}));
add(comboboxLingua);
comboboxLingua.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
h.changetext();
}
});
}
}
Thank you.
Its because when you create panel5 you have a new home created.
static home h = new home ().
So when you call changetext method you do it in a new invisible frame.
In order to make this work (it is really really bad) you have to pass your visible "home" as an argument to your panel5. Which means you have to initiate it in home's constructor and not as a field.
public panelImpostazioni(home h)
And in your combobox action listener
h.changetext ()

A basic logic issue whilst using setters and getters with Swing

Im writing a basic program to simulate a conversation between a user and the computer. I am trying to use a setter and getter to change the text in a textField in another class. The button is clicked and nothing appears in the textField. here is my code:
public class DialogueWindow extends JFrame {
SuperDialogue SD = new SuperDialogue();
JTextField textField = new JTextField();
JButton Answer1 = new JButton();
public DialogueWindow() {
initUI();
}
public void initUI() {
JPanel panel = new JPanel();
getContentPane().add(panel);
panel.setLayout(null);
JButton Answer1 = new JButton();
Answer1.setBounds(102, 149, 113, 30);
Answer1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
textField.setText(SD.getReply1());
}
});
panel.add(Answer1);
textField = new JTextField();
textField.setBounds(56, 74, 174, 45);
panel.add(textField);
setTitle("Dialogue");
setSize(800, 600);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
public class SuperDialogue {
private String answer;
public String getReply1(){
return this.answer;
}
public void setReply1(String a1){
this.answer = a1;
}
}
public class Conversation1 extends SuperDialogue {
public void Convo(){
String firstLine = "hello";
setReply1(firstLine);
DialogueWindow DW = new DialogueWindow();
DW.setVisible(true);
DW.setSize(300,300);
}
}
public class Main {
public static void main(String[] args) {
Conversation1 c1 = new Conversation1();
c1.Convo();
}
}
The SuperDialogue in your JFrame class is not the same as the one created in your main.
SuperDialogue SD = new SuperDialogue();
This line is creating a separate SuperDialog which does not has the same values. This one is never set, so getReply1() returns nothing.

Auto typer doesn't stop when "Stop Spam" button is pushed

I've created an auto typer because I've always wanted to know how they work. Only problem is when I click the stop button, it doesn't stop and it freezes my system.
I've tried changing the interval time, and it still doesn't stop when the stop button is pushed.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class AutoSpammer{
private static int interval;
private static Timer timerMain;
private static JTextField txtSpam;
private static JTextField txtInterval;
private static JButton btnStart;
private static JButton btnStop;
public static void main(String[]args){
ActionListener taskSpam = new ActionListener(){
public void actionPerformed(ActionEvent evt) {
sendkeys(txtSpam.getText());
}
};
ActionListener taskStartTimer = new ActionListener(){
public void actionPerformed(ActionEvent evt){
timerMain.setDelay(Integer.parseInt(txtInterval.getText()));
timerMain.start();
btnStart.setEnabled(false);
btnStop.setEnabled(true);
txtInterval.setEnabled(false);
}
};
ActionListener taskStopTimer = new ActionListener(){
public void actionPerformed(ActionEvent evt){
timerMain.stop();
btnStart.setEnabled(true);
btnStop.setEnabled(false);
txtInterval.setEnabled(true);
}
};
btnStart = new JButton("Start Spam");
btnStop = new JButton("Stop Spam");
JLabel lbl1 = new JLabel("Enter Text:");
JLabel lbl2 = new JLabel("Interval:");
timerMain = new Timer(1,taskSpam);
txtSpam = new JTextField("Enter text:", 13);
txtInterval = new JTextField("3000",3);
btnStart.addActionListener(taskStartTimer);
btnStop.addActionListener(taskStopTimer);
btnStop.setEnabled(false);
JPanel intervalpane = new JPanel();
intervalpane.add(lbl2,BorderLayout.EAST);
intervalpane.add(txtInterval,BorderLayout.WEST);
JPanel bottompane = new JPanel();
bottompane.add(btnStart,BorderLayout.EAST);
bottompane.add(btnStop,BorderLayout.CENTER);
bottompane.add(intervalpane,BorderLayout.WEST);
JPanel toppane = new JPanel();
toppane.add(lbl1,BorderLayout.EAST);
toppane.add(txtSpam,BorderLayout.NORTH);
JPanel pane = new JPanel(new BorderLayout());
pane.add(toppane,BorderLayout.NORTH);
pane.add(bottompane,BorderLayout.SOUTH);
JFrame frame = new JFrame("Spammer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(pane);
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
}
private static void sendkeys(String text) {
try {
Robot robot = new Robot();
text = text.toUpperCase();
for(int i = 0; i < text.length(); i++)
robot.keyPress(text.charAt(i));
robot.keyPress(KeyEvent.VK_ENTER);
}catch(java.awt.AWTException exc) {
System.out.println("error");
}
}
}
program works fine for me. Stop does stop the robot. I added a simple System.out what has been pressed and this stops

It does not add to an arrayList for some reasons

I've got this strange thing, I'm trying to add to the ArrayList but it does not add, it get the values and everything. Please check the code and brigthen me up.
The class where I am trying to add:
public class ManualProductGUI extends JDialog {
private final JPanel contentPanel = new JPanel();
private JTextField barcodeField;
private JTextField idField;
private JTextField nameField;
private JTextField priceField;
private JTextField quantityField;
private JTextField infoField;
BasketContainer bc = new BasketContainer();
private static final long serialVersionUID = 1L;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
ManualProductGUI dialog = new ManualProductGUI();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the dialog.
*/
public ManualProductGUI() {
setTitle("Product search");
setBounds(100, 100, 450, 300);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
barcodeField = new JTextField();
barcodeField.setText("Enter barcode");
barcodeField.setBounds(10, 11, 157, 20);
contentPanel.add(barcodeField);
barcodeField.setColumns(10);
barcodeField.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
barcodeField.setText("");
}
});
barcodeField.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
int barcode = Integer.parseInt(barcodeField.getText());
ProductCtr prodCtr = new ProductCtr();
Product prod = prodCtr.searchProductByBarcode(barcode);
buildFields(prod);
}
});
infoField = new JTextField();
infoField.setEditable(false);
infoField.setBounds(177, 133, 86, 20);
contentPanel.add(infoField);
infoField.setColumns(10);
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("Add");
okButton.setActionCommand("Add");
buttonPane.add(okButton);
okButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
addToBasket();
setVisible(false);
dispose();
}
});
getRootPane().setDefaultButton(okButton);
}
{
JButton cancelButton = new JButton("Cancel");
cancelButton.setActionCommand("Cancel");
cancelButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
setVisible(false);
dispose();
}
});
buttonPane.add(cancelButton);
}
}
}
private void addToBasket()
{
int barcode = Integer.parseInt(barcodeField.getText());
ProductCtr prodCtr = new ProductCtr();
Product prod = prodCtr.searchProductByBarcode(barcode);
bc.addProduct(prod);
}
}
And here is a part of the Container class:
private ArrayList<Product> listOfItems;
public BasketContainer()
{
listOfItems = new ArrayList<>();
}
public void addProduct(Product prod)
{
listOfItems.add(prod);
}
public ArrayList<Product> getProducts()
{
return listOfItems;
}
It prints out the info on the screen, but it does not add. Am I missing something?
Thank you.
You create a new instance of BasketContainer every time, so that new instances will have a new clear ArrayList.
To fix it you should create your BasketContainer instance somewhere (maybe in an init block?) and save the reference, then use it to add the elements.
You're creating a new BasketContainer within the scope of the method.
BasketContainer bc = new BasketContainer();
bc.addProduct(prod);
The addToBasket method should call addProduct on a field of the class it's in.

Java - Password Field character counter

I have an assignment question that requires me to create a JPasswordField. Two buttons are needed, one to show the actual password in another textfield, and the other just shows the character count in the textfield. Here's what I have to far, but I can't get it to compile because Method setText in class javax.swing.text.JTextComponent cannot be applied to given types.
The compiler stops under bt1 when I want it to read the password itself.
Can anyone help?
Thanks.
Code:
public class JavaPasswordCount {
public JavaPasswordCount() {
JFrame window = new JFrame("Password Character Count");
window.setSize(50, 50);
JButton bt1 = new JButton("Show Count");
JButton bt2 = new JButton("Show Password");
final JPasswordField pwd = new JPasswordField();
final JTextField tf = new JTextField();
final int counter;
JPanel panel = new JPanel();
bt1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tf.setText(pwd.getPassword());
}
});
bt2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
counter = pwd.length();
tf.setText(counter);
}
});
panel.setLayout(new FlowLayout()); // Add buttons and TextField to the panel
panel.add(tf);
panel.add(pwd);
panel.add(bt1);
panel.add(bt2);
window.getContentPane().add(panel, BorderLayout.CENTER);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.pack();
window.setVisible(true);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception e) {
}
JavaPasswordCount application = new JavaPasswordCount();
}
}
Change this lines:
counter = pwd.length();
tf.setText(counter);
to
int counter = pwd.getPassword().length;
tf.setText(String.valueOf((counter)));
and this
tf.setText(pwd.getPassword());
To
tf.setText(pwd.getPassword().toString());

Categories