I been coding on a autoclicker, I just finished but I can't click anything, I can be in the window open but I can't click any button or slider etc.
I am using jnativehook as api for checking mouse press outside.
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import javax.swing.JSlider;
import javax.swing.JTextField;
import java.awt.AWTException;
import java.awt.Color;
public class AutoClicker extends JFrame implements Runnable {
public static AutoClicker get = new AutoClicker();
private static final long serialVersionUID = 1L;
private JPanel contentPane;
public static boolean enabled = false;
// private MouseHandler mouse;
private JTextField textField;
private JTextField textField_1;
public boolean activated;
public boolean skipNext;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AutoClicker frame = new AutoClicker();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public AutoClicker() {
setTitle("Swezeds AutoClicker");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 403, 253);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
JButton btnStart = new JButton("Start");
btnStart.setBounds(88, 36, 89, 23);
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
enabled = true;
}
});
contentPane.setLayout(null);
contentPane.add(btnStart);
JButton btnStop = new JButton("Stop");
btnStop.setBounds(187, 36, 89, 23);
btnStop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
enabled = false;
}
});
contentPane.add(btnStop);
JLabel lblSwezedsAutoclicker = new JLabel("Swezeds AutoClicker");
lblSwezedsAutoclicker.setBounds(102, 11, 167, 14);
lblSwezedsAutoclicker.setFont(new Font("Impact", Font.PLAIN, 20));
contentPane.add(lblSwezedsAutoclicker);
JCheckBox chckbxClickingSound = new JCheckBox("Clicking Sound");
chckbxClickingSound.setBounds(6, 184, 118, 23);
contentPane.add(chckbxClickingSound);
JSlider slider = new JSlider();
slider.setValue(5);
slider.setMaximum(20);
slider.setBounds(88, 70, 188, 14);
contentPane.add(slider);
JSlider slider_1 = new JSlider();
slider_1.setMaximum(20);
slider_1.setValue(12);
slider_1.setBounds(88, 112, 188, 14);
contentPane.add(slider_1);
JLabel lblNewLabel = new JLabel("Max CPS");
lblNewLabel.setBounds(32, 112, 76, 14);
contentPane.add(lblNewLabel);
JLabel lblMinCps = new JLabel("Min CPS");
lblMinCps.setBounds(32, 70, 76, 14);
contentPane.add(lblMinCps);
textField = new JTextField(slider.getValue() + "");
textField.setEditable(false);
textField.setBackground(Color.LIGHT_GRAY);
textField.setBounds(276, 64, 31, 20);
contentPane.add(textField);
textField.setColumns(10);
textField_1 = new JTextField(slider_1.getValue() + "");
textField_1.setEditable(false);
textField_1.setBackground(Color.LIGHT_GRAY);
textField_1.setColumns(10);
textField_1.setBounds(276, 109, 31, 20);
contentPane.add(textField_1);
}
public static int randInt(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public boolean isSkipNext() {
return skipNext;
}
public void setSkipNext(boolean skipNext) {
this.skipNext = skipNext;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
AutoClicker.enabled = enabled;
}
public boolean isActivated() {
return activated;
}
public void setActivated(boolean activated) {
this.activated = activated;
}
#Override
public void run() {
try {
for (;;) {
Thread.sleep(1L);
if ((isActivated()) && (isEnabled())) {
try {
Thread.sleep(1L);
Robot robot = new Robot();
while (true) {
try {
setSkipNext(true);
Thread.sleep(AutoClicker.randInt(100, 150));
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
} catch (InterruptedException ecksdee) {
}
}
} catch (AWTException ecksdee) {
}
}
}
} catch (Exception localException) {
}
try {
GlobalScreen.registerNativeHook();
this.mouse = new MouseHandler();
GlobalScreen.addNativeMouseListener(this.mouse);
} catch (NativeHookException exception) {
exception.printStackTrace();
}
}
}
You've overridden essentially functionality of the JFrame
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
AutoClicker.enabled = enabled;
}
This is changing the user interaction state, basically disabling the frame.
Suggestion, use a model to manage the state, separate the logic from the user interface and share the model between them.
I recommend against using JFrame as your primary component, you're not adding any new functionality to the class and it ties you into a single use case. Better to start with a JPanel, then you can add it to whatever container you like.
This:
public static AutoClicker get = new AutoClicker();
is not how a singleton should be done, besides, you create a whole other instance in the main method anyway, so now you run the risk of contaminating the state. Separating the model/view/controller will help solve part of the problem at least
Related
So, I have this task where the user guess the correct number just by clicking on the JLabel I have presented for them. What I was trying to is to generate a random number then use if (e.getSource() == random) { } but it seems object and int isn't a compatible operand and I was hoping if someone has any solution to this.
Anyways, here is the source code of what I am doing nothing good since I don't have any solution on my first problem yet.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import java.awt.Font;
import java.util.Random;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Test123 {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test123 window = new Test123();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Test123() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
Random generator = new Random();
int num;
num = generator.nextInt(9) + 1;
int count = 0;
frame = new JFrame();
frame.setBounds(100, 100, 405, 195);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel NO1 = new JLabel("1");
NO1.setBounds(20, -26, 43, 183);
NO1.setFont(new Font("Arial", Font.BOLD, 75));
frame.getContentPane().add(NO1);
JLabel NO2 = new JLabel("2");
NO2.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
}
});
NO2.setFont(new Font("Arial", Font.BOLD, 75));
NO2.setBounds(60, -26, 43, 183);
frame.getContentPane().add(NO2);
JLabel NO3 = new JLabel("3");
NO3.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
}
});
NO3.setFont(new Font("Arial", Font.BOLD, 75));
NO3.setBounds(102, -26, 43, 183);
frame.getContentPane().add(NO3);
JLabel NO4 = new JLabel("4");
NO4.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
}
});
NO4.setFont(new Font("Arial", Font.BOLD, 75));
NO4.setBounds(143, -26, 43, 183);
frame.getContentPane().add(NO4);
JLabel NO5 = new JLabel("5");
NO5.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
}
});
NO5.setFont(new Font("Arial", Font.BOLD, 75));
NO5.setBounds(184, -26, 43, 183);
frame.getContentPane().add(NO5);
JLabel NO6 = new JLabel("6");
NO6.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
}
});
NO6.setFont(new Font("Arial", Font.BOLD, 75));
NO6.setBounds(223, -26, 43, 183);
frame.getContentPane().add(NO6);
JLabel NO7 = new JLabel("7");
NO7.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
}
});
NO7.setFont(new Font("Arial", Font.BOLD, 75));
NO7.setBounds(264, -26, 43, 183);
frame.getContentPane().add(NO7);
JLabel NO8 = new JLabel("8");
NO8.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
}
});
NO8.setFont(new Font("Arial", Font.BOLD, 75));
NO8.setBounds(304, -26, 43, 183);
frame.getContentPane().add(NO8);
JLabel NO9 = new JLabel("9");
NO9.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
}
});
NO9.setFont(new Font("Arial", Font.BOLD, 75));
NO9.setBounds(345, -26, 43, 183);
frame.getContentPane().add(NO9);
JLabel CorrectAns = new JLabel("Correct!");
CorrectAns.setEnabled(false);
CorrectAns.setBounds(181, 132, 46, 14);
frame.getContentPane().add(CorrectAns);
NO1.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (e.getSource() == num) {
count++;
CorrectAns.setText("Correct!" + count + " attempts");
}
}
});
}
}
MouseEvent#getSource will return the object which trigged the event, in your case, the JLabel.
A "generally" better solution might be to use JButton instead, then take advantage of the ActionListener. I'd attach a single ActionListener to the "correct" button to handle the correct workflow and a ActionListener to the others to handle the incorrect state
See How to Use Buttons, Check Boxes, and Radio Buttons and How to Write an Action Listener for more details
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Twst {
public static void main(String[] args) {
new Twst();
}
public Twst() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
randomButtons();
}
protected void randomButtons() {
removeAll();
List<JButton> buttons = new ArrayList<>(4);
Random rnd = new Random();
Set<Integer> numbers = new HashSet<>();
while (numbers.size() < 4) {
int number = rnd.nextInt(99) + 1;
numbers.add(number);
}
for (Integer number : numbers) {
JButton btn = new JButton(Integer.toString(number));
add(btn);
buttons.add(btn);
}
Collections.shuffle(buttons);
JButton correct = buttons.remove(0);
correct.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
JOptionPane.showMessageDialog(TestPane.this, "Correct");
randomButtons();
}
});
ActionListener wrong = new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
if (evt.getSource() instanceof JButton) {
JButton btn = (JButton) evt.getSource();
btn.setEnabled(false);
}
JOptionPane.showMessageDialog(TestPane.this, "Wrong");
// You could keep a counter or do what ever else you
// want with a wrong guess
}
};
for (JButton btn : buttons) {
btn.addActionListener(wrong);
}
revalidate();
repaint();
}
}
}
I have this part of code here, but whenever I launch the program I only get left brain. even though I check one or the other box.
chckbxMusic = new JCheckBox("Music");
chckbxMusic.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
chckbxMath.setSelected(false);
}
});
chckbxMusic.setBounds(46, 107, 85, 23);
Question_1.add(chckbxMusic);
chckbxMath = new JCheckBox("Math");
chckbxMath.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
chckbxMusic.setSelected(false);
}
});
chckbxMath.setBounds(243, 107, 128, 23);
Question_1.add(chckbxMath);
if(chckbxMusic.isSelected()) brain_right++;
else brain_left++;
Ok maybe the full code can help a bit more..
I rewrite it a little bit, but the result is always 0 for both variables??
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.CardLayout;
import javax.swing.JPanel;
import javax.swing.JCheckBox;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
public class PrgVeloce {
private JFrame frame;
private JPanel Question;
private JPanel Result;
public int brain_left;
public int brain_right;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PrgVeloce window = new PrgVeloce();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public PrgVeloce() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new CardLayout(0, 0));
Question = new JPanel();
frame.getContentPane().add(Question, "name_971195205673");
Question.setLayout(null);
final JCheckBox chckbxMath = new JCheckBox("Math");
chckbxMath.setBounds(39, 115, 128, 23);
Question.add(chckbxMath);
final JCheckBox chckbxMusic = new JCheckBox("Music");
chckbxMusic.setBounds(237, 115, 128, 23);
Question.add(chckbxMusic);
JButton btnNext = new JButton("Next");
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(chckbxMusic.isSelected())
{
brain_left = 10;
}
if(chckbxMath.isSelected())
{
brain_right = 10;
}
Question.setVisible(false);
Result.setVisible(true);
}
});
btnNext.setBounds(158, 210, 117, 29);
Question.add(btnNext);
Result = new JPanel();
frame.getContentPane().add(Result, "name_978670915264");
Result.setLayout(null);
JLabel lblEmisferoDx = new JLabel("Right brain:");
lblEmisferoDx.setBounds(90, 118, 110, 16);
Result.add(lblEmisferoDx);
JLabel lblNewLabel = new JLabel("Left Brain:");
lblNewLabel.setBounds(90, 157, 84, 16);
Result.add(lblNewLabel);
JLabel lblNewLabel_1 = new JLabel(brain_right + "%");
lblNewLabel_1.setBounds(218, 118, 61, 16);
Result.add(lblNewLabel_1);
JLabel lblNewLabel_2 = new JLabel(brain_left + "%");
lblNewLabel_2.setBounds(218, 157, 61, 16);
Result.add(lblNewLabel_2);
}
}
I have a JFrame with three tabs: Home, Statistics, and About.
On the Home tab, I have a counter that tracks how many times you click your left or right arrow, and it updates a counter (I use the KeyListener method):
On the Statistics tab, I want to somehow import these Left and Right values that I generate from the counter.
But, I don't know how to. Can someone help me out here?
Edit:
Here is the code for the Home tab (Left/Right counter)
import java.awt.*;
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class HomePanel extends JPanel implements KeyListener {
// Variables
private int counter = 0;
private int counter2 = 0;
private JLabel counterLabel;
private JLabel counterLabel2;
private JButton countUpButton;
private JButton countDownButton;
// Panel Elements
public HomePanel() {
countUpButton = new JButton ("Left");
countUpButton.setBounds(195, 121, 75, 29);
countUpButton.addKeyListener(this);
countDownButton = new JButton ("Right");
countDownButton.setBounds(195, 162, 77, 29);
countDownButton.addKeyListener(this);
counterLabel = new JLabel("" + counter);
counterLabel.setBounds(282, 126, 34, 16);
counterLabel2 = new JLabel("" + counter2);
counterLabel2.setBounds(282, 167, 34, 16);
setLayout(null);
add (countUpButton);
add (counterLabel);
add (countDownButton);
add (counterLabel2);
}
// Key Listener
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
// Ensures counter updates once per stroke
#Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
counter++;
counterLabel.setText("" + counter);
} else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
counter2++;
counterLabel2.setText("" + counter2);
}
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}
And here is the code for the Statistics tab:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class StatsPanel extends JPanel {
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
private JTextField textField_4;
private JTextField textField_5;
private JTextField textField_6;
public StatsPanel() {
setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(41, 43, 371, 234);
add(panel);
panel.setLayout(null);
JLabel lblNewLabel = new JLabel("LEFT:");
lblNewLabel.setBounds(115, 39, 33, 16);
panel.add(lblNewLabel);
JLabel lblRight = new JLabel("RIGHT:");
lblRight.setBounds(105, 67, 43, 16);
panel.add(lblRight);
JLabel lblNewLabel_2 = new JLabel("TOTAL:");
lblNewLabel_2.setBounds(102, 95, 46, 16);
panel.add(lblNewLabel_2);
JLabel lblNewLabel_3 = new JLabel("% LEFT:");
lblNewLabel_3.setBounds(102, 123, 46, 16);
panel.add(lblNewLabel_3);
JLabel lblNewLabel_4 = new JLabel("% RIGHT: ");
lblNewLabel_4.setBounds(91, 151, 60, 16);
panel.add(lblNewLabel_4);
textField_2 = new JTextField();
textField_2.setBounds(160, 33, 134, 28);
panel.add(textField_2);
textField_2.setColumns(10);
textField_3 = new JTextField();
textField_3.setBounds(160, 61, 134, 28);
panel.add(textField_3);
textField_3.setColumns(10);
textField_4 = new JTextField();
textField_4.setBounds(160, 89, 134, 28);
panel.add(textField_4);
textField_4.setColumns(10);
textField_5 = new JTextField();
textField_5.setBounds(160, 117, 134, 28);
panel.add(textField_5);
textField_5.setColumns(10);
textField_6 = new JTextField();
textField_6.setBounds(160, 145, 134, 28);
panel.add(textField_6);
textField_6.setColumns(10);
JButton btnCalculate = new JButton("Calculate");
btnCalculate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// Variables
double num1, num2, ans, percEq1, percEq2, percLeft, percRight;
try {
num1 = Double.parseDouble(textField_2.getText());
num2 = Double.parseDouble(textField_3.getText());
ans = num1 + num2;
textField_4.setText(Double.toString(ans));
percEq1 = (num1/(num1+num2))*100;
percLeft = Math.round(percEq1);
textField_5.setText(Double.toString(percLeft));
percEq2 = (num2/(num1+num2))*100;
percRight = Math.round(percEq2);
textField_6.setText(Double.toString(percRight));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Please enter a valid number!");
}
}
});
btnCalculate.setBounds(79, 185, 117, 29);
panel.add(btnCalculate);
JButton btnRest = new JButton("Reset");
btnRest.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
textField_2.setText("");
textField_3.setText("");
textField_4.setText("");
textField_5.setText("");
textField_6.setText("");
}
});
btnRest.setBounds(197, 185, 117, 29);
panel.add(btnRest);
}
}
I suggest using variables in the parent container so every tab can access them or, from the statistics tab, ask the values to the parent frame and the parent asks to the home tab.
It's not a short code and you haven't attached yours, so I hope your get the idea.
In the main container you have something like this:
KeyPressStats statistics = new KeyPressStats();
HomePanel home = new HomePanel(statistics);
StatsPanel stats = new StatsPanel(statistics);
JTabbedPane tabbed = new JTabbedPane();
tabbed.addTab("Home", home);
tabbed.addTab("Stats", stats);
tabbed.setVisible(true);
KeyPressStats is as follows:
public class KeyPressStats {
private int leftCount = 0;
private int rightCount = 0;
public int getLeftCount() {
return leftCount;
}
public void setLeftCount(int leftCount) {
this.leftCount = leftCount;
}
public int getRightCount() {
return rightCount;
}
public void setRightCount(int rightCount) {
this.rightCount = rightCount;
}
public void incrementRight() {
rightCount++;
}
public void incrementLeft() {
leftCount++;
}
}
And the code in the Home and stats tabs will have these changes:
public class HomePanel extends JPanel implements KeyListener {
...
private KeyPressStats stats;
public HomePanel(KeyPressStats stats) {
this.stats = stats;
countUpButton = new JButton("Left");
countUpButton.setBounds(195, 121, 75, 29);
...
}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
stats.incrementLeft();
counterLabel.setText("" + stats.getLeftCount());
} else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
stats.incrementRight();
counterLabel2.setText("" + stats.getRightCount());
}
}
public class StatsPanel extends JPanel {
...
public StatsPanel(KeyPressStats stats) {
...
textField_2 = new JTextField(""+stats.getLeftCount());
textField_2.setBounds(160, 33, 134, 28);
...
textField_3 = new JTextField(""+stats.getRightCount());
textField_3.setBounds(160, 61, 134, 28);
...
}
}
So what I've got is that I would love to try and make an little login applet. I'm using Java Windowsbuilder for it, to make it easyer for me. I hope the code isn't to messy, because I'm just a starter.
The problem I've got is that My JButton "login" only registers a keyevent when it's selected trought tab, or when you first click it. What I want is that I can use the button always just by pressing the "ENTER" key.
Hope you guys solve my problem :)
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import org.eclipse.wb.swing.FocusTraversalOnArray;
import java.awt.Component;
import java.awt.event.KeyAdapter;
public class nummer1 extends JFrame{
private JPanel contentPane;
public static nummer1 theFrame;
private JTextField textFieldUsername;
private JTextField textFieldPass;
private nummer1 me;
private JLabel lblCheck;
private String password = "test", username = "test";
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
nummer1 frame = new nummer1();
nummer1.theFrame = frame;
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void Check(){
String Pass = textFieldPass.getText();
String Username = textFieldUsername.getText();
System.out.println(Pass);
if (Pass.equals(password) && Username.equals(username)){
lblCheck.setText("Correct Login");
}else{
lblCheck.setText("Invalid username or password");
}
}
/**
* Create the frame.
*/
public nummer1() {
me = this;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 356, 129);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblUsername = new JLabel("Username:");
lblUsername.setBounds(10, 11, 61, 14);
contentPane.add(lblUsername);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setBounds(10, 36, 61, 14);
contentPane.add(lblPassword);
textFieldUsername = new JTextField();
textFieldUsername.setBounds(81, 8, 107, 20);
contentPane.add(textFieldUsername);
textFieldUsername.setColumns(10);
me.textFieldUsername = textFieldUsername;
textFieldPass = new JTextField();
textFieldPass.setBounds(81, 33, 107, 20);
contentPane.add(textFieldPass);
textFieldPass.setColumns(10);
me.textFieldPass = textFieldPass;
JButton btnLogin = new JButton("Login");
contentPane.requestFocusInWindow();
btnLogin.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER){
me.Check();
System.out.println("hi");
}
}
});
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
me.Check();
}
});
btnLogin.setBounds(198, 7, 89, 23);
contentPane.add(btnLogin);
JLabel lblCheck = new JLabel("");
lblCheck.setHorizontalAlignment(SwingConstants.TRAILING);
lblCheck.setBounds(10, 65, 264, 14);
contentPane.add(lblCheck);
me.lblCheck = lblCheck;
contentPane.setFocusTraversalPolicy(new FocusTraversalOnArray(new
Component[]{lblUsername, lblPassword, textFieldUsername, textFieldPass, btnLogin, lblCheck}));
}
}
Thanks Emil!
What I want is that I can use the button always just by pressing the "ENTER" key
Sounds like you want to make the "login" button the default button for the dialog.
See Enter Key and Button for the problem and solution.
When using panels KeyListeners won't work unless the panel is focusable. What you can do is make a KeyBinding to the ENTER key using the InputMap and ActionMap for your panel.
public class Sample extends JPanel{
//Code
Sample() {
//More code
this.getInputMap().put(KeyStroke.getKeyStroke((char)KeyEvent.VK_ENTER), "Enter" );
this.getActionMap().put("Enter", new EnterAction());
}
private class EnterAction extends AbstractAction(){
#Override
public void ActionPerformed(ActionEvent e){
//Acion
}
}
}
So for class I'm suppose to make a Celsius to Fahrenheit converter GUI. With that said, it's a pretty simple and easy program to create. I want to do more with it though. What I want to do is have one window that changes depending on which radio button is selected in a buttongroup. I want the selected radiobutton for "To Fahrenheit" or "To Celsius" to update the labels for the input and output. I have tried using an actionlistener for when one is selected, but it doesn't change the labels. Am I using the wrong listener? What's the correct way to do this?
Here's my code:
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
public class Converter extends JFrame {
private JPanel contentPane;
private JTextField tfNumber;
private JLabel lblCelsius;
private JLabel lblFahrenheit;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Converter frame = new Converter();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Converter() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
setTitle("Celsius Converter");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 308, 145);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
tfNumber = new JTextField();
tfNumber.setText("0");
tfNumber.setBounds(10, 11, 123, 20);
contentPane.add(tfNumber);
tfNumber.setColumns(10);
lblCelsius = new JLabel("Celsius");
lblCelsius.setFont(new Font("Tahoma", Font.BOLD, 15));
lblCelsius.setBounds(143, 12, 127, 14);
contentPane.add(lblCelsius);
lblFahrenheit = new JLabel("Fahrenheit");
lblFahrenheit.setBounds(187, 46, 95, 14);
contentPane.add(lblFahrenheit);
final JLabel lblNum = new JLabel("32.0");
lblNum.setBounds(143, 46, 43, 14);
contentPane.add(lblNum);
final JRadioButton rdbtnF = new JRadioButton("to Fahrenheit");
rdbtnF.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(rdbtnF.isSelected()) {
lblCelsius.setText("Celsius");
lblFahrenheit.setText("Fahrenheit");
}
}
});
rdbtnF.setSelected(true);
rdbtnF.setBounds(10, 72, 109, 23);
contentPane.add(rdbtnF);
final JRadioButton rdbtnC = new JRadioButton("to Celsius");
rdbtnC.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(rdbtnF.isSelected()) {
lblCelsius.setText("Fahrenheit");
lblFahrenheit.setText("Celsius");
}
}
});
rdbtnC.setBounds(121, 72, 109, 23);
contentPane.add(rdbtnC);
ButtonGroup bg = new ButtonGroup();
bg.add(rdbtnF);
bg.add(rdbtnC);
JButton btnConvert = new JButton("Convert");
btnConvert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(rdbtnF.isSelected()) {
String num = String.valueOf(convertToF(tfNumber.getText()));
lblNum.setText(num);
}
if(rdbtnC.isSelected()) {
String num = String.valueOf(convertToC(tfNumber.getText()));
lblNum.setText(num);
}
}
});
btnConvert.setBounds(10, 42, 123, 23);
contentPane.add(btnConvert);
}
private double convertToF(String celsius) {
double c = Double.parseDouble(celsius);
double fahren = c * (9/5) + 32;
return fahren;
}
private double convertToC(String fahren) {
double f = Double.parseDouble(fahren);
double celsius = (f - 32) * 5 / 9;
return celsius;
}
}