I have this code where I designed an editable JComboBox to listen to my keyPressed event and show a message that the key is pressed. But I have no idea why this not working. As a beginner I might have gone wrong logically/conceptually.
So, I would request for suggestions about how to construct the code, so that it works.
Code
import javax.swing.*;
import java.awt.*;
public class testEJCBX extends JFrame {
JComboBox jcbx = new JComboBox();
public testEJCBX() {
super("Editable JComboBox");
jcbx.setEditable(true);
getContentPane().setLayout(new FlowLayout());
getContentPane().add(jcbx);
jcbx.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt)
{
jcbxKeyPressed(evt);
}
});
setSize(300, 170);
setVisible(true);
}
private void jcbxKeyPressed(java.awt.event.KeyEvent evt) {
JOptionPane.showMessageDialog(null, "Key Pressed");
}
public static void main(String argv[]) {
new testEJCBX();
}
}
You shouldn't be using a KeyListener for this sort of thing. Rather if you want to detect changes to the combo box's editor component, extract it and add a DocumentListener to it:
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;
import java.awt.*;
public class TestEJCBX extends JFrame {
JComboBox<String> jcbx = new JComboBox<>();
public TestEJCBX() {
super("Editable JComboBox");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
jcbx.setEditable(true);
getContentPane().setLayout(new FlowLayout());
getContentPane().add(jcbx);
JTextField editorComponent = (JTextField) jcbx.getEditor()
.getEditorComponent();
Document doc = editorComponent.getDocument();
doc.addDocumentListener(new DocumentListener() {
#Override
public void removeUpdate(DocumentEvent e) {
System.out.println("text changed");
}
#Override
public void insertUpdate(DocumentEvent e) {
System.out.println("text changed");
}
#Override
public void changedUpdate(DocumentEvent e) {
System.out.println("text changed");
}
});
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String argv[]) {
new TestEJCBX();
}
}
Related
I have a java project in which I am trying to make an effect similar to the hover in CSS, changing the color(icon) every time the mouse passes over a jlabel, but I realized that I am using several methods that do the same thing.
My question is if there is a possibility to unify all of them in a single method or if there is a simpler way to do this kind of animations with a library or something like that.
private void lblPersonalizarMouseExited(java.awt.event.MouseEvent evt) {
lblPersonalizar.setIcon(icono_personalizari);
}
private void lblPersonalizarMouseEntered(java.awt.event.MouseEvent evt) {
lblPersonalizar.setIcon(icono_personalizara);
}
private void lblNuevaCompraMouseExited(java.awt.event.MouseEvent evt) {
lblNuevaCompra.setIcon(icono_comprai);
}
private void lblNuevaCompraMouseEntered(java.awt.event.MouseEvent evt) {
lblNuevaCompra.setIcon(icono_compraa);
}
private void lblUsuarioMouseEntered(java.awt.event.MouseEvent evt) {
lblUsuario.setIcon(icono_usuarioa);
}
private void lblUsuarioMouseExited(java.awt.event.MouseEvent evt) {
lblUsuario.setIcon(icono_usuarioi);
}
private void lblFacturasMouseEntered(java.awt.event.MouseEvent evt) {
lblFacturas.setIcon(icono_facturasa);
}
private void lblFacturasMouseExited(java.awt.event.MouseEvent evt) {
lblFacturas.setIcon(icono_facturasi);
}
private void lblMaterialesMouseEntered(java.awt.event.MouseEvent evt) {
lblMateriales.setIcon(icono_materialesa);
}
private void lblMaterialesMouseExited(java.awt.event.MouseEvent evt) {
lblMateriales.setIcon(icono_materialesi);
}
private void lblAyudaMouseEntered(java.awt.event.MouseEvent evt) {
lblAyuda.setIcon(icono_ayudaa);
}
private void lblAyudaMouseExited(java.awt.event.MouseEvent evt) {
lblAyuda.setIcon(icono_ayudai);
}
JButton supports image rollover, which would be a much simper solution
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
public class TestPane extends JPanel {
public TestPane() throws IOException {
setLayout(new GridBagLayout());
setBackground(Color.BLACK);
JButton bagButton = makeButton(new ImageIcon(ImageIO.read(getClass().getResource("/images/Bag.png"))), new ImageIcon(ImageIO.read(getClass().getResource("/images/Bag-Selected.png"))));
JButton editButton = makeButton(new ImageIcon(ImageIO.read(getClass().getResource("/images/Edit.png"))), new ImageIcon(ImageIO.read(getClass().getResource("/images/Edit-Selected.png"))));
JButton settingsButton = makeButton(new ImageIcon(ImageIO.read(getClass().getResource("/images/Settings.png"))), new ImageIcon(ImageIO.read(getClass().getResource("/images/Settings-Selected.png"))));
add(bagButton);
add(editButton);
add(settingsButton);
bagButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Bag was selected");
}
});
editButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Edit was selected");
}
});
settingsButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Settings was selected");
}
});
}
protected JButton makeButton(Icon icon, Icon rollOverIcon) {
JButton button = new JButton();
button.setIcon(icon);
button.setRolloverIcon(rollOverIcon);
button.setRolloverEnabled(true);
button.setBorderPainted(false);
button.setFocusPainted(false);
return button;
}
}
}
Make sure you take a look at How to Use Buttons, Check Boxes, and Radio Buttons
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class TheSize extends JFrame implements ActionListener, KeyListener {
static String inText="";
JPanel pane=new JPanel();
JLabel word0=new JLabel("I would like my grid to be 2^",JLabel.RIGHT);
JLabel word1=new JLabel("* 2^ "+inText,JLabel.RIGHT);
JButton finish=new JButton("I'm done");
JTextField size=new JTextField("",3);
public TheSize(){
super("size");
System.out.println("hi");
setLookAndFeel();
setSize(550,100);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
FlowLayout box=new FlowLayout();
setLayout(box);
pane.add(word0);
pane.add(size);
pane.add(word1);
pane.add(finish);
finish.addActionListener(this);
add(pane);
setVisible(true);
pack();
size. addKeyListener(this);
setFocusable(true);
}
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
);
} catch (Exception exc) {
// ignore error
}
}
public void actionPerformed(ActionEvent e) {
}
#Override
public void keyPressed(KeyEvent arg0) {
}
#Override
public void keyReleased(KeyEvent arg0) {
}
#Override
public void keyTyped(KeyEvent e) {
inText=size.getText();
pane.revalidate();
pane.repaint();
}
public static void main(String[] args){
new TheSize();
}
}
a couple of things
I made sure the KeyListener is working, and it is not working as in no output, it didn't give me any error.
What should happen:
It should pop a frame which says I would like my grid to be 2^__(user input Textfield)____* 2^(what is in the textfield). (Button for I'm done).
however, (what is in the textfield) remains empty after I type something into the text field. I checked whether the program heard my keystrokes using System.out.println();, and it is working, so the revalidate(); and repaint() commands must not be(I also tested it out by putting a System.out.println(); in my constructor. Thanks in advance
Never use a KeyListener on a JTextField. Get rid of the KeyListener and the JTextField should likely accept text just fine. Instead, if you want to register user input, use a DocumentListener if you just want the text but won't filter it, or a DocumentFilter if you need to filter the text before it is displayed. This sort of question has been asked many times on this site.
Also note that your JLabel will never change, even if you do use a DocumentListener since you call setText(...) on your word1 JLabel but never re-call this method. Just changing the String that the inText String variable refers to of course will not magically change the JLabel's displayed text.
Note, that I'm not sure what you mean by the replicate() command as I've not heard of this method. Do you mean revalidate() if so, please clarify.
For example:
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Window;
import java.awt.event.ActionEvent;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
// Avoid extending JFrames if at all possible.
// and only extend other components if needed.
#SuppressWarnings("serial")
public class TheSize2 extends JPanel {
private static final String FORMAT = "* 2^ %s";
private static final int PREF_W = 550;
private static final int PREF_H = 100;
private String inText = "";
private JLabel word0 = new JLabel("I would like my grid to be 2^", JLabel.RIGHT);
private JLabel word1 = new JLabel(String.format(FORMAT, inText), JLabel.RIGHT);
private JButton finish = new JButton("I'm done");
private JTextField size = new JTextField("", 3);
public TheSize2() {
finish.setAction(new FinishAction("I'm Done"));
size.getDocument().addDocumentListener(new SizeListener());
add(word0);
add(size);
add(word1);
add(finish);
}
#Override // make JPanel bigger
public Dimension getPreferredSize() {
Dimension superSz = super.getPreferredSize();
if (isPreferredSizeSet()) {
return superSz;
}
int prefW = Math.max(superSz.width, PREF_W);
int prefH = Math.max(superSz.height, PREF_H);
return new Dimension(prefW, prefH);
}
private class SizeListener implements DocumentListener {
private void textUpdated(DocumentEvent e) {
try {
inText = e.getDocument().getText(0, e.getDocument().getLength());
word1.setText(String.format(FORMAT, inText));
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
#Override
public void changedUpdate(DocumentEvent e) {
textUpdated(e);
}
#Override
public void insertUpdate(DocumentEvent e) {
textUpdated(e);
}
#Override
public void removeUpdate(DocumentEvent e) {
textUpdated(e);
}
}
private class FinishAction extends AbstractAction {
public FinishAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
Component comp = (Component) e.getSource();
if (comp == null) {
return;
}
Window win = SwingUtilities.getWindowAncestor(comp);
if (win == null) {
return;
}
win.dispose();
}
}
private static void createAndShowGui() {
TheSize2 theSize2 = new TheSize2();
JFrame frame = new JFrame("The Size");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(theSize2);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
I found the solution with the help of Hovercraft Full Of Eels, all I missed was to re setSize. It is not the best solution, but it is simple enough for me to understand.
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class TheSize extends JFrame implements ActionListener, KeyListener {
static String inText="";
JPanel pane=new JPanel();
JLabel word0=new JLabel("I would like my grid to be 2^",JLabel.RIGHT);
JLabel word1=new JLabel("* 2^ "+inText,JLabel.RIGHT);
JButton finish=new JButton("I'm done");
JTextField size=new JTextField("",3);
public TheSize(){
super("size");
setLookAndFeel();
setSize(550,100);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
FlowLayout box=new FlowLayout();
setLayout(box);
pane.add(word0);
pane.add(size);
pane.add(word1);
pane.add(finish);
finish.addActionListener(this);
add(pane);
setVisible(true);
pack();
size.addKeyListener(this);
setFocusable(true);
}
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
);
} catch (Exception exc) {
// ignore error
}
}
public void actionPerformed(ActionEvent e) {
}
public static void main(String[] args){
new TheSize();
}
#Override
public void keyPressed(KeyEvent arg0) {
}
#Override
public void keyReleased(KeyEvent arg0) {
inText=size.getText();
word1.setText("* 2^ "+inText);
pane.revalidate();
pane.repaint();
}
#Override
public void keyTyped(KeyEvent arg0) {
}
}
So I wanted to make a program that holds down the mouse button for me.
So far I've got this: http://pastebin.com/UTJwdHY7
What I'm wondering is how I can stop it. Also, what I realise is that stopping the button makes no sense as I wouldn't be able to click it anyway. Also some tips on how I've done so far would be nice.
Edit (Adding code):
package main;
import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.beans.PropertyChangeListener;
public class clickForever extends JFrame implements ActionListener {
public static boolean isClicking = false;
public void actionPerformed(ActionEvent e) {}
public void createFrame() { initComponents(); }
public void initComponents() {
JFrame frame = new JFrame("AutoClicker");
JPanel panel = new JPanel(true);
JButton button = new JButton("OKAY");
JLabel label = new JLabel();
frame.setVisible(true);
frame.setSize(350, 67);
frame.setResizable(false);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.getContentPane().add(panel, BorderLayout.CENTER);
frame.add(panel);
button.addActionListener(new Action() {
#Override
public Object getValue(String s) {
return null;
}
#Override
public void putValue(String s, Object o) {}
#Override
public void setEnabled(boolean b) {}
#Override
public boolean isEnabled() {
return false;
}
#Override
public void addPropertyChangeListener(PropertyChangeListener propertyChangeListener) {}
#Override
public void removePropertyChangeListener(PropertyChangeListener propertyChangeListener) {}
#Override
public void actionPerformed(ActionEvent actionEvent) {
if(isClicking){isClicking = false; return;}
if(!isClicking){isClicking = true; return;}
}
});
label.setFont(new Font("Times New Roman", 1, 16));
label.setText("Click 'OKAY' to start.");
label.setBorder(BorderFactory.createLineBorder(Color.black));
panel.add(label);
panel.setBorder(new LineBorder(Color.BLACK));
panel.add(button);
}
public static void main(String[] args) throws java.awt.AWTException, java.lang.InterruptedException {
clickForever clickForever = new clickForever();
Robot rbt = new Robot();
clickForever.createFrame();
while(true){
if(isClicking) rbt.mousePress(InputEvent.BUTTON1_MASK);
if(!isClicking) ;
}
}
}
Add a key listener to the frame, and when the key is pressed, stop the pressing. Note that this will not work if the frame goes out of focus, in which case you would have to listen for a global key press, which I believe would be much more difficult.
You Can Use This To End Your Program And Try Link It To The Press Of A button
Code:
public class Main {
public static void main(String[] args) {
System.out.println("Statement 1");
System.exit(0);
System.out.println("Statement 2");
}
}
I would like the user to enter a value into the JTextField and use a listener to listen to the textfield and print the value to the console straightaway without pressing a key.
textfield1.addChangeListener(new ChangeListener() {
public void actionPerformed(ActionEvent e) {
System.out.println(textfield1);
}
});
error:
<anonymous textfield$2> is not abstract and does not override abstract method stateChanged(ChangeEvent) in ChangeListener
Put this private class into your public class. Just like a method.
private class textChangedListener implements KeyListener
{
public void keyPressed(KeyEvent e){}
public void keyReleased(KeyEvent e){}
public void keyTyped(KeyEvent e)
{
System.out.print(textField1.getText());
}
}
And then call it to your JTextField in your main method like so:
private JTextField textField1; // just showing the name of the JTextField
textField1.addKeyListener(new textChangedListener());
Yes, just use the KeyListener class, see the example below:
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class Main extends JFrame {
public Main() throws HeadlessException {
setSize(200, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout(FlowLayout.LEFT));
JLabel label = new JLabel("Write something: ");
JTextField input = new JTextField();
input.setPreferredSize(new Dimension(100, 20));
final JTextField output = new JTextField();
output.setPreferredSize(new Dimension(100, 20));
add(label);
add(input);
add(output);
input.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
JTextField textField = (JTextField) e.getSource();
String text = textField.getText();
output.setText(text);
}
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
}
});
}
public static void main(String[] args) {
new Main().setVisible(true);
}
}
You can set a addlistener to textproperty of the text field.
textField.textProperty().addListener(new ChangeListener<String>() {
#Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
System.out.println("textfield changed to "+ newValue);
}
});
When I press tab key on the keyboard I want to select my text fields in above order.how to do that?
Try this example....
package com.Demo;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
#SuppressWarnings("serial")
public class TabTest extends JFrame {
public TabTest() {
initialize();
}
private void initialize() {
setSize(300, 300);
setTitle("JTextArea TAB DEMO");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JTextField textField = new JTextField();
JPasswordField passwordField = new JPasswordField();
final JTextArea textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
//
// Add key listener to change the TAB behaviour in
// JTextArea to transfer focus to other component forward
// or backward.
//
textArea.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_TAB) {
if (e.getModifiers() > 0) {
textArea.transferFocusBackward();
} else {
textArea.transferFocus();
}
e.consume();
}
}
});
getContentPane().add(textField, BorderLayout.NORTH);
getContentPane().add(scrollPane, BorderLayout.CENTER);
getContentPane().add(passwordField, BorderLayout.SOUTH);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TabTest().setVisible(true);
}
});
}
}
jTextField1.setNextFocusableComponent(jTextField2);
jTextField2.setNextFocusableComponent(jTextField3);
jTextField3.setNextFocusableComponent(jTextField4);
jTextField4.setNextFocusableComponent(jTextField5);
try this :)
Try this:
txtfld.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
txtfld.setText("aaa");
}
#Override
public void focusLost(FocusEvent e) {
...
}
});
see more complete code.