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());
Related
I am working on a simple counter swing app. I'm trying to make it so when you click the check box, it will stay on the top and display a message dialog being "On Top" or "Not On Top".
However, when I click the checkbox after compiling and running, both of the messages display, and after clicking OK on both messages, the checkbox isn't even enabled. If I were to remove the showMessageDialog, it would still function properly, but I want to learn how to appropriately implement this.
Thank you in advance. Here is all of the code for the program:
public Class Counter {
JFrame frame;
JPanel panel;
JButton button, clear;
JTextField textC;
JLabel label;
JCheckBox cbox;
boolean topC = false;
int icount = 0;
String scount;
String topStatus = "";
public Counter() {
gui();
setActions();
}
public void gui() {
frame = new JFrame("Counter Program");
panel = new JPanel();
label = new JLabel("Counter");
textC = new JTextField();
textC.setPreferredSize(new Dimension(72,28));
textC.setEditable(false);
button = new JButton("Click");
clear = new JButton("Clear");
cbox = new JCheckBox("Top");
frame.setSize(350,80);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.add(panel);
panel.add(label);
panel.add(textC);
panel.add(button);
panel.add(clear);
panel.add(cbox);
frame.setVisible(true);
}
public void setActions() {
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
icount++;
scount = Integer.toString(icount);
textC.setText(scount);
}
});
clear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
icount = 0;
textC.setText("");
}
});
cbox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
topC = !topC;
if (topC) {
topStatus = "Top";
}
else topStatus = "Not Top";
frame.setAlwaysOnTop(topC);
JOptionPane.showMessageDialog(frame, topStatus, "Top Setting", 1);
}
});
}
public static void main(String[]args) {
new Counter();
}
}
An ItemListener generates two events, one for the selection and one for the unselection (and vice versa). Read the section from the Swing tutorial on How to Write an ItemListener for more information and working exmaples if you really want to use an ItemListener.
Otherwise, use an ActionListener instead, it will only generate a single event.
So I am trying to create a virtual keyboard that can insert values in a Jtextfield of another Jframe. The problem is that the data is overlapping when editing other text fields. So, I tried renewing the object but it replaced the first Jtextfield value as well. what should i do with this, should i start from scratch or is there any other way? . Since, English is not my first language I am struggling to find the correct terminology to research the problem please enlighten me with your knowledge
import java.awt.*;
import javax.swing.*;
public class OnScreenKeyboard implements ActionListener {
JFrame keyboard;
static String keyboardKeys = "0123456789qwertyuiopasdfghjklzxcvbnm.< ";
JButton[] keys = new JButton[39];
GridLayout gl;
FlowLayout fl;
Dimension buttondimension;
JPanel panel1, panel2;
JToggleButton capslock;
private String message = "";
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public OnScreenKeyboard() {
buttondimension = new Dimension(45, 40);
fl = new FlowLayout();
capslock = new JToggleButton("capslock");
panel1 = new JPanel(fl);
panel2 = new JPanel(fl);
char[] key = keyboardKeys.toCharArray();
for (int i = 0; i < 39; i++) {
keys[i] = new JButton(String.valueOf(key[i]));
keys[i].setFont(new Font("Arial", Font.PLAIN, 13));
if (i == 38) {
keys[i].setPreferredSize(new Dimension(100, 30));
} else {
keys[i].setPreferredSize(buttondimension);
}
keys[i].addActionListener(this);
}
keyboard = new JFrame("Keyboard");
keyboard.setSize(720, 220);
keyboard.setLocationRelativeTo(null);
keyboard.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
keyboard.setResizable(false);
Container content = keyboard.getContentPane();
content.setLayout(null);
panel1.setBounds(1, 1, 500, 210);
panel2.setBounds(510, 1, 200, 210);
for (int i = 0; i < 10; i++) {
panel2.add(keys[i]);
}
for (int i = 10; i < 39; i++) {
panel1.add(keys[i]);
}
panel1.add(capslock);
content.add(panel1);
content.add(panel2);
capslock.addActionListener(this);
keyboard.setVisible(true);
}
public static void main(String[] args) {
new OnScreenKeyboard();
}
public void reset(){
message = "";
}
#Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < 36; i++) {
if (e.getSource() == keys[i]) {
setMessage(getMessage() + keys[i].getText());
break;
}
}
if (e.getSource() == capslock) {
if (capslock.isSelected()) {
for (int i = 10; i < 36; i++) {
keys[i].setFont(new Font("Arial", Font.PLAIN, 12));
keys[i].setText(keys[i].getText().toUpperCase());
}
} else if (!capslock.isSelected()) {
for (int i = 10; i < 36; i++) {
keys[i].setFont(new Font("Arial", Font.PLAIN, 13));
keys[i].setText(keys[i].getText().toLowerCase());
}
}
}
setMessage(getMessage());
//JOptionPane.showMessageDialog(null, getMessage());
}
}
this is the frame I am trying to put my values from the keyboard in
public class LoginScreen implements ActionListener, FocusListener {
JFrame frame;
Container content;
FlowLayout fl;
JTextField txtusername, txtpassword;
JLabel lblusername, lblpassword;
JPanel panel1, panel2;
JButton keyboard, signup, signin;
OnScreenKeyboard kyb;
Dimension text;
private void init() {
text =new Dimension(100, 30);
fl = new FlowLayout(FlowLayout.CENTER);
lblusername = new JLabel("enter username");
lblpassword = new JLabel("enter password");
txtusername = new JTextField();
txtpassword = new JPasswordField();
keyboard = new JButton("keyboard");
signup = new JButton("signup");
signin = new JButton("sign in");
panel1 = new JPanel(fl);
panel2 = new JPanel(fl);
keyboard = new JButton("keyboard");
txtusername.setPreferredSize(text);
txtpassword.setPreferredSize(text);
kyb = new OnScreenKeyboard();
}
public LoginScreen() {
init();
frame = new JFrame("BorderLayoutDemo");
frame.setTitle("Registration Form");
frame.setSize(300, 300);
frame.setDefaultCloseOperation(3);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
content = frame.getContentPane();
content.setLayout(new GridLayout(2, 1));
panel1.add(lblusername);
panel1.add(txtusername);
panel1.add(lblpassword);
panel1.add(txtpassword);
panel2.add(signup);
panel2.add(signin);
panel2.add(keyboard);
content.add(panel1);
content.add(panel2);
keyboard.addActionListener(this);
txtusername.addFocusListener(this);
txtpassword.addFocusListener(this);
}
public static void main(String[] args) {
new LoginScreen();
}
#Override
public void actionPerformed(ActionEvent e) {
if (!kyb.keyboard.isVisible()) {
if (e.getSource() == keyboard) {
kyb = new OnScreenKeyboard();
}
}
}
#Override
public void focusGained(FocusEvent e) {
if(txtusername == e.getSource()){
txtusername.setText(kyb.getMessage());
}else if(txtpassword == e.getSource()){
kyb.reset();
txtpassword.setText(kyb.getMessage());
}
}
#Override
public void focusLost(FocusEvent e) {
}
The problem is that it's weird how/when the text is taken from the keyboard.
You use the LoginScreen both as actionListener on the keyboard and as focusListener on the 2 textfields.
The way you implemented it now is that you "type" something in on the keyboard and after that put the focus on 1 of the 2 fields. Only at the moment you click the text from the keyboard is fetched (kyb.getMessage()).
It's especially a problem on the password. If you click on the txtpassword field you first reset the kyb and then fetch the message (which you just reset so is empty).
What felt weird for me is that you don't have a way in the keyboard to notion that you are done typing. So the flow of only getting the message when the focus changes to one of the text fields is wrong.
What I would do is create a new kind of KeyboardListener. This listener is put on the txtusername OR txtpassword depending on who last took focus (so in the focusGained() you should change who is listening to the keyboard).
Then each time a key is "typed" you should notify the listener of the letter and then the txtusername/txtpassword (whichever is listening at that time) should add that letter to its text.
This means that the keyboard itself doesn't need to remember any text. It just figures out which key was pressed and then sends the corresponding letter to the listener.
You should be using a TextAction as your ActionListener. The TextAction has a method getFocusedComponent() which will return the last text component to have focus.
Then in the can add the character to the text field. So the basic code in the actionPerformed(...) method of the TextAction might be something like:
JTextComponent component = getFocusedComponent();
component.replaceSelection( the character to add );
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
i have an program which is an JFrame, but when i use my "starting" action it isn't able to be switched of, instead it just sticks running and I need to force-close it :( could you say me why, because I'm new to coding an i dont find my mistake here is my code:
public class ClickBotSetUp extends JFrame {
static ClickBotSetUp frame;
static Robot robot;
public static void ClickBot() throws AWTException{
final Robot robot = new Robot();
robot.delay(2000);
while(true)
{
{
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
robot.delay(least);
}
}
}
public static void main(String[] args) throws IOException, AWTException {
frame = new ClickBotSetUp("setup speed");
frame.setVisible(true);
frame.setBackground(Color.WHITE);
robot = new Robot();
}
//settings
static int least = 100;
JTextField count;
JButton start;
static int bot = 0;
public ClickBotSetUp(String title) throws HeadlessException
{
super(title);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setSize(180, 145);
Container cont = getContentPane();
cont.setLayout(new BorderLayout());
((JComponent) cont).setBorder(BorderFactory.createEmptyBorder(15, 15,
15, 15));
//desing
JLabel instructions = new JLabel("low nubers can crash");
cont.add(instructions, BorderLayout.SOUTH);
//buttons
start = new JButton("start");
start.setAction(starting);
cont.add(start, BorderLayout.WEST);
//score
JPanel scores = new JPanel();
scores.setLayout(new BorderLayout());
cont.add(scores, BorderLayout.CENTER);
JPanel times = new JPanel();
times.setLayout(new BorderLayout());
scores.add(times, BorderLayout.WEST);
//times
count = new JTextField("100");
count.setEditable(false);
times.add(count, BorderLayout.CENTER);
JButton add10 = new JButton("+10");
add10.setAction(add_10);
times.add(add10, BorderLayout.NORTH);
JButton remove10 = new JButton("-10");
remove10.setAction(remove_10);
times.add(remove10, BorderLayout.SOUTH);
}
private AbstractAction starting = new AbstractAction("start") {
#Override
public void actionPerformed(ActionEvent arg0) {
frame.setVisible(false);
try {
ClickBot();
} catch (AWTException e) {
e.printStackTrace();
}
}
};
private AbstractAction add_10 = new AbstractAction("+10") {
#Override
public void actionPerformed(ActionEvent arg0) {
least = least + 10;
count.setText("" +least+ "");
}
};
private AbstractAction remove_10 = new AbstractAction("-10") {
#Override
public void actionPerformed(ActionEvent arg0) {
if(least < 20){
}else{
least = least - 10;
count.setText("" +least+ "");
}
}
};
}
while(true) is an infinite loop. It will never exit this.
Have some condition in the while(someCondition Here) which will break the while loop.
Also as #ArnaudDenoyelle pointed out
You need the line
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
That is because the default behavior for the JFrame for the X button is the equivalent to
frame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
So most of the times you will need to add the line manually when creating your JFrame
while(true) will create a never ending loop. you should be using a flag and when a condition is met that flag should be changed so that the loop may be exited.
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
}
}
});