How can i prevent CTRL+C on a JTextField in java? - java

How can i prevent a user from copying the contents of a JTextField?
i have the following but i cannot figure a way to get multiple keys at the same time?
myTextField.addKeyListener(new KeyAdapter() {
#Override
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if (!Character.isDigit(c)) {
e.consume();
}
}
});

For this, you will have to modify your KeyAdapter so that it can register when a key was pressed and when it was released, so that we may know when both keys were pressed simultaneously, the following code should do the trick:
textfield.addKeyListener(new KeyAdapter() {
boolean ctrlPressed = false;
boolean cPressed = false;
#Override
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()) {
case KeyEvent.VK_C:
cPressed=true;
break;
case KeyEvent.VK_CONTROL:
ctrlPressed=true;
break;
}
if(ctrlPressed && cPressed) {
System.out.println("Blocked CTRl+C");
e.consume();// Stop the event from propagating.
}
}
#Override
public void keyReleased(KeyEvent e) {
switch(e.getKeyCode()) {
case KeyEvent.VK_C:
cPressed=false;
break;
case KeyEvent.VK_CONTROL:
ctrlPressed=false;
break;
}
if(ctrlPressed && cPressed) {
System.out.println("Blocked CTRl+C");
e.consume();// Stop the event from propagating.
}
}
});
i was just adding this to one of my JTextFields.

Related

Replace many "else if" with something else

I am using an ActionListener and have lots of else if statements in order to know which button is pressed and run some code depending on the button.
Is there a way to make the code nicer? I have nearly 10 else if statements following each other, is there something else I could use instead?
Sample of code:
class BtnListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == menu.getOpen()) {
getFile();
} else if (e.getSource() == btnPlay) {
} else if (e.getSource() == btnQuit)) {
}
}
Thanks.
You can fill Map<Object, Consumer<ActionEvent>> before using of listener, for example in constructor, where key is source and value is a consumer for action event. In action perform just get consumer by key and invoke it.
class BtnListener implements ActionListener {
Map<Object, Consumer<ActionEvent>> eventsMap = new HashMap<>();
public BtnListener() {
eventsMap.put(menu.getOpen(), actionEvent -> this.getFile());
eventsMap.put(btnPlay, actionEvent -> { //do something
});
eventsMap.put(btnQuit, actionEvent -> { //do something else
});
}
#Override
public void actionPerformed(ActionEvent e) {
Optional.of(e)
.map(ActionEvent::getSource)
.map(eventsMap::get)
.ifPresent(
actionEventConsumer -> actionEventConsumer.accept(e)
);
}
}
You may use the action command of the button, and a switch-case block :
public void actionPerformed(ActionEvent e){
switch(e.getActionCommand()) {
case "Open":
open();
break;
case "Delete":
delete();
break;
default :
break;
}
}
Of course you will have to set the action command of each button first, like :
openButton.setActionCommand("Open");
Note that switch-case with String objects only exists since JDK 7 : Strings in switch Statements
You can switch statement instead lot of else if ladder.
class BtnListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == menu.getOpen()) {
getFile();
}
switch( e.getSource() ){
case btnPlay:
break;
case btnQuit:
break;
default:
}
}
}
the best way to avoid all the "overheads" is to Lambda-Expressioned the buttons. Example:
JButton b1 = new JButton("Play");
b1.addActionListener(e -> play());
...
JButton bn = new JButton("Stop");
bn.addActionListener(e -> stop());
...
private void play() {
....// playing codes
}
...
private void stop() {
...// stopping codes
}
...

Clear textField immediately after entering char in Java Swing

After entering into textField one of this letters: "e,E,f,F,g,G", the comboBox in my app is changing. I want to clear my textField immediately after entering one of this letters but i can't do this. I use :
tekstField.setText("");
but it doesn't work. Probably it because that i can't eat listener in Swing.
textField.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
updateLog(e);
}
public void removeUpdate(DocumentEvent e) {
}
public void insertUpdate(DocumentEvent e) {
updateLog(e);
}
public void updateLog(DocumentEvent e) {
Document doc = (Document) e.getDocument();
int docLength = doc.getLength();
String key;
try {
key = e.getDocument().getText(0, docLength);
if (docLength == 1 && !key.matches("^[0-9]$")) {
char labSymbol = key.charAt(0);
switch (labSymbol) {
case 'E' :
case 'e' :
labTypeComboBox.setSelectedIndex(0);
break;
case 'F' :
case 'f' :
labTypeComboBox.setSelectedIndex(1);
break;
case 'G' :
case 'g' :
labTypeComboBox.setSelectedIndex(2);
break;
default :
break;
}
tekstField.setText("");
}
} catch (BadLocationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
Anybody know how to solve this problem?

How can I change JLabel text during work of JButton?

I would like my button 'licz' to: change text value of info to ''loading'', do something and change 'info' to "done". ('licz' is here a JButton, 'info' JLabel)
licz.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
info.setText("Loading..."); // Here
if(go())
{
brute(0);
info.setText("Done!"); //here
if(odwrot)
JOptionPane.showMessageDialog(frame, "good");
else
JOptionPane.showMessageDialog(frame, "bad");
}
else
{
JOptionPane.showMessageDialog(frame, "bad");
info.setText("Done"); // And here
}
}
});
But the program makes "something" first, changes 'info' label to "loading" and immediately to "done", how to keep these in case?
The event of actionPerformed is handled on the event handling thread, and should terminate fast to have a responsive GUI. Hence call invokeLater.
licz.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
info.setText("Loading...");
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
boolean good = false;
if (go())
{
brute(0);
good = odwrot;
}
JOptionPane.showMessageDialog(frame, good ? "good" : "bad");
info.setText("Done");
}
});
}
});
Or in java 8:
licz.addActionListener((e) -> {
info.setText("Loading...");
EventQueue.invokeLater(() -> {
boolean good = false;
if (go())
{
brute(0);
good = odwrot;
}
JOptionPane.showMessageDialog(frame, good ? "good" : "bad");
info.setText("Done");
});
});

How to use KeyEvent

I'm writing small graphics editor and I want catch event when I press Ctrl+A
I use such code (this is test version):
#Override
public void keyPressed(KeyEvent e) {
System.out.println("Press");
switch (e.getKeyCode()){
case KeyEvent.VK_A :
System.out.println("A");
break;
}
}
but I don't know how to catch Ctrl+a
I tryed something like this
case KeyEvent.VK_CONTROL+KeyEvent.VK_A :
System.out.println("A+CTRL");
break;
but this code KeyEvent.VK_CONTROL+KeyEvent.VK_A returns int and maybe another key combination returns the same number
So can someone can help me
You can use isControlDown() method:
switch (e.getKeyCode())
{
case KeyEvent.VK_A :
if(e.isControlDown())
System.out.println("A and Ctrl are pressed.");
else
System.out.println("Only A is pressed");
break;
...
}
Try this.....
f.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
if ((e.getKeyCode() == KeyEvent.VK_A) && ((e.getModifiers() & KeyEvent.CTRL_MASK) != 0)) {
System.out.println("woot!");
}
}
#Override
public void keyReleased(KeyEvent e) {
}
});
Try isControlDown method on KeyEvent: http://docs.oracle.com/javase/6/docs/api/java/awt/event/InputEvent.html#isControlDown%28%29

basic boolean states problems

I am trying to write a piece of code so that when a key is pressed it will execute something, but then the key will have to be released and then repressed again in order to retrigger the event. So if the user just holds down the key, it wont keep doing it over and over, instead they will have to press and release repeatedly.
So far, I have:
if(keyLifted)
{
if(Keyboard.isKeyDown(45))
{
keyLifted = false;
dostuff;
}
else if(Keyboard.isKeyDown(46))
{
keyLifted = false;
dostuff();
}
else
{
keyLifted = true;
}
}
but this is flawed for obvious reasons (it will only reset the key to being unlifted if the key is already lifted: if the key was pressed, it wont be set to unpressed). I have tried a couple variations, but I just cant get it to work.
Thanks in advance for any help!
You should use a KeyListener to capture keyboard events. Here you go:
public class KeyListenerExample extends JFrame {
public KeyListenerExample() {
addKeyListener(new KeyAdapter() {
private boolean keyLifted;
public void keyReleased(KeyEvent e) {
keyLifted = true;
}
public void keyPressed(KeyEvent e) {
keyLifted = false;
switch (e.getKeyChar()) {
case 45:
doStuff();
break;
case 46:
doStuff();
break;
}
}
});
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private void doStuff() {
System.out.println("stuff");
}
/**
* #param args
*/
public static void main(String[] args) {
new KeyListenerExample();
}
}
I just kept the keyLifted because it is in your example. But I think for the usual keyboard stuff you don't need it.

Categories