Alternative solution on randomizing JLabel - java

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();
}
}
}

Related

Cannot interact with jFrame, only plays error note

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

Java- disable buttons on one jpanel with another.

So my goal is to disable buttons on lets say panel B depending one what button they press on panel A. so below I have 2 combo boxes that id like to be able to enable or disable base on the buttons pressed on the first panel. Ive tried googling this problem but I'm new to java so its pretty rough going so far.
heres my sample code of what I'm trying to do.
package pack2;
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.CardLayout;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
public class tessst {
public boolean enableChk1;
public boolean enableChk2;
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
tessst window = new tessst();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public tessst() {
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));
final JPanel panel = new JPanel();
frame.getContentPane().add(panel, "name_15095567731094");
panel.setLayout(null);
final JPanel panel_1 = new JPanel();
frame.getContentPane().add(panel_1, "name_15101078033315");
panel_1.setLayout(null);
JButton select2 = new JButton("2 boxes");
select2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
enableChk1 = true;
enableChk2 = true;
panel_1.revalidate();
frame.repaint();
panel_1.repaint();
frame.repaint();
panel.setVisible(false);
panel_1.setVisible(true);
}
});
select2.setBounds(276, 101, 89, 23);
panel.add(select2);
JButton select1 = new JButton("1 boxes");
select1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
enableChk1 = true;
panel_1.revalidate();
frame.repaint();
panel_1.repaint();
frame.repaint();
panel.setVisible(false);
panel_1.setVisible(true);
}
});
select1.setBounds(59, 101, 89, 23);
panel.add(select1);
JButton select0 = new JButton("no boxes");
select0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
enableChk1 = false;
enableChk2 = false;
panel_1.revalidate();
frame.repaint();
panel_1.repaint();
frame.repaint();
panel.setVisible(false);
panel_1.setVisible(true);
}
});
select0.setBounds(166, 169, 89, 23);
panel.add(select0);
JComboBox comboBox = new JComboBox();
comboBox.setEnabled(enableChk1);
comboBox.setModel(new DefaultComboBoxModel(new String[] {"1", "2", "3"}));
comboBox.setBounds(52, 100, 61, 20);
panel_1.add(comboBox);
JComboBox comboBox_1 = new JComboBox();
comboBox_1.setEnabled(enableChk2);
comboBox_1.setModel(new DefaultComboBoxModel(new String[] {"1", "2", "3"}));
comboBox_1.setBounds(265, 100, 79, 20);
panel_1.add(comboBox_1);
JButton back = new JButton("go back");
back.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
panel.setVisible(true);
panel_1.setVisible(false);
}
});
back.setBounds(10, 227, 89, 23);
panel_1.add(back);
}
}
I needed to declare my comboBox's above my buttons then declare them as final.
here are the changes
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class tessst {
public boolean enableChk1;
public boolean enableChk2;
JComboBox comboBox;
JComboBox comboBox_1;
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
tessst window = new tessst();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public tessst() {
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));
final JPanel panel = new JPanel();
frame.getContentPane().add(panel, "name_15095567731094");
panel.setLayout(null);
final JPanel panel_1 = new JPanel();
frame.getContentPane().add(panel_1, "name_15101078033315");
panel_1.setLayout(null);
JButton select2 = new JButton("2 boxes");
select2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
enableChk1 = true;
enableChk2 = true;
panel_1.revalidate();
frame.repaint();
panel_1.repaint();
frame.repaint();
panel.setVisible(false);
panel_1.setVisible(true);
comboBox.setEnabled(true);
comboBox_1.setEnabled(true);
}
});
select2.setBounds(276, 101, 89, 23);
panel.add(select2);
JButton select1 = new JButton("1 boxes");
select1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
enableChk1 = true;
panel_1.revalidate();
frame.repaint();
panel_1.repaint();
frame.repaint();
panel.setVisible(false);
panel_1.setVisible(true);
comboBox.setEnabled(true);
}
});
select1.setBounds(59, 101, 89, 23);
panel.add(select1);
JButton select0 = new JButton("no boxes");
select0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
enableChk1 = false;
enableChk2 = false;
panel_1.revalidate();
frame.repaint();
panel_1.repaint();
frame.repaint();
panel.setVisible(false);
panel_1.setVisible(true);
comboBox.setEnabled(false);
comboBox_1.setEnabled(false);
}
});
select0.setBounds(166, 169, 89, 23);
panel.add(select0);
comboBox = new JComboBox();
comboBox.setEnabled(enableChk1);
comboBox.setModel(new DefaultComboBoxModel(new String[] {"1", "2", "3"}));
comboBox.setBounds(52, 100, 61, 20);
panel_1.add(comboBox);
comboBox_1 = new JComboBox();
comboBox_1.setEnabled(enableChk2);
comboBox_1.setModel(new DefaultComboBoxModel(new String[] {"1", "2", "3"}));
comboBox_1.setBounds(265, 100, 79, 20);
panel_1.add(comboBox_1);
JButton back = new JButton("go back");
back.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
panel.setVisible(true);
panel_1.setVisible(false);
}
});
back.setBounds(10, 227, 89, 23);
panel_1.add(back);
}
}
replace your code with this one. Its working Fine. Hope you are expecting this thing.

Unresponsive JTextField

In my application I need to get a response between 1 and 9 from the user. I am using a JTextField to get the input. However when a button is pressed the user the JTextField becomes unresponsive. Here is a stripped down example of the problem:
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.*;
import javax.swing.*;
public class InputTest {
private JTextField inputBox;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new InputTest();
}
});
} // end main()
public InputTest() { // constructor
JFrame f = new JFrame("Input Test");
f.setBounds(100, 100, 450, 300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(null);
JLabel label = new JLabel("Enter an integer:");
label.setFont(new Font("Tahoma", Font.PLAIN, 14));
label.setBounds(109, 120, 109, 30);
f.add(label);
inputBox = new JTextField();
inputBox.setBounds(259, 120, 30, 30);
f.add(inputBox);
JButton button = new JButton("Button");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button Pressed");
}
});
button.setMnemonic('B');
button.setBounds(166, 198, 78, 23);
f.add(button);
f.setVisible(true);
inputBox.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if (c < '!' || e.getModifiers() > 0)
return;
if (c < '1' || c > '9') {
JOptionPane.showMessageDialog(null, c
+ " is not an integer");
// inputBox.setText("error");
System.out.println("You typed a non-integer");
} else
System.out.println("You typed " + c);
inputBox.setText(null);
}
});
} // end constructor
} // end class
You should almost never use a KeyListener with a Swing JTextComponent such as a JTextField, for example what happens when the user tries to copy and paste in their input? Instead consider using either a JFormattedTextField, or a JTextField with a DocumentFilter, or my choice -- a JSpinner.
import java.awt.event.ActionEvent;
import javax.swing.*;
public class InputTest2 extends JPanel {
private JSpinner spinner = new JSpinner(new SpinnerNumberModel(1, 1, 9, 1));
private JButton getSelectionButton = new JButton(new GetSelectionAction("Get Selection"));
public InputTest2() {
add(spinner);
add(getSelectionButton);
}
private static void createAndShowGui() {
InputTest2 mainPanel = new InputTest2();
JFrame frame = new JFrame("InputTest2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
private class GetSelectionAction extends AbstractAction {
public GetSelectionAction(String name) {
super(name);
}
#Override
public void actionPerformed(ActionEvent evt) {
int value = ((Integer)spinner.getValue()).intValue();
System.out.println("You've selected " + value);
}
}
}

Using Radio Buttons to set labels in Java

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;
}
}

Filtering out tab character with documentFilter

So, I have a program with JTextArea with DocumentFilter. It should (among other things) filter out tab characters and prevent them to be entered in the JTextArea completely.
Well, it works well when I type, but I can still paste it in. i shouldn't be able to, according to the code...
Below is kind of a SSCCE. Just run it, press ctrl+n and enter. All the colored fileds are JTextAreas with same DocumentFilter. The filter itself is the first class (DefaultDocFilter), only thing you need to look into.
package core;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Properties;
import java.util.ResourceBundle;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.border.Border;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.JTextComponent;
class DefaultDocFilter extends DocumentFilter
{
public void insertString(FilterBypass fb, int offs,String str, AttributeSet a) throws BadLocationException
{
if ((fb.getDocument().getLength() + str.length()) <= 200)
{
str.replaceAll("\n", " ");
str.replaceAll("\t", " ");
System.out.print(str);
fb.insertString(offs, str, a);
}
else
{
int spaceLeft = 200 - fb.getDocument().getLength();
if (spaceLeft <= 0)
return;
str.substring(0, spaceLeft);
str.replaceAll("\n", " ");
str.replaceAll("\t", " ");
fb.insertString(offs, str, a);
}
}
public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a) throws BadLocationException
{
if (str.equals("\n") || str.equals("\t"))
{
str = "";
}
if ((fb.getDocument().getLength() + str.length() - length) <= 200)
{
str.replaceAll("\n", " ");
str.replaceAll("\t", " ");
fb.replace(offs, length, str, a);
}
else
{
int spaceLeft = 200 - fb.getDocument().getLength() + length;
if (spaceLeft <= 0)
return;
fb.replace(offs, length, str.substring(0,spaceLeft).replaceAll("\n", " "), a);
}
}
}
#SuppressWarnings("serial")
class DefaultFont extends Font
{
public DefaultFont()
{
super("Arial", PLAIN, 20);
}
}
#SuppressWarnings("serial")
class Page extends JPanel
{
public JPanel largePage;
public int content;
public Page(JPanel panel, int index)
{
largePage = new JPanel();
largePage.setLayout(new BoxLayout(largePage, BoxLayout.Y_AXIS));
largePage.setMaximumSize(new Dimension(794, 1123));
largePage.setPreferredSize(new Dimension(794, 1123));
largePage.setAlignmentX(Component.CENTER_ALIGNMENT);
largePage.setBackground(Color.WHITE);
largePage.add(new Box.Filler(new Dimension(0, 96), new Dimension(0, 96), new Dimension(0, 96)));
setMaximumSize(new Dimension(556, 931));
setBackground(Color.LIGHT_GRAY);
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
add(new Box.Filler(new Dimension(556, 0), new Dimension(556, 931), new Dimension(556, 931)));
largePage.add(this);
largePage.add(new Box.Filler(new Dimension(0, 96), new Dimension(0, 96), new Dimension(0, 96)));
panel.add(largePage, index);
panel.add(new Box.Filler(new Dimension(0, 40), new Dimension(0, 40), new Dimension(0, 40)));
content = 0;
Main.pages.add(this);
}
}
#SuppressWarnings("serial")
class Heading extends JTextArea
{
public boolean type;
public AbstractDocument doc;
public ArrayList<JPanel/*Question*/> questions;
public ArrayList<JPanel/*List*/> list;
public Heading(boolean segment, Page page)
{
type = segment;
setBackground(Color.RED);
setFont(new Font("Arial", Font.BOLD, 20));
Border in = BorderFactory.createDashedBorder(Color.BLACK);
Border out = BorderFactory.createMatteBorder(0, 0, 10, 0, Color.WHITE);
setBorder(BorderFactory.createCompoundBorder(out, in));
setLineWrap(true);
setWrapStyleWord(true);
setText("Heading 1 Heading 1 Heading 1 Heading 1");
doc = (AbstractDocument)this.getDocument();
doc.setDocumentFilter(new DefaultDocFilter());
page.add(this, 0);
page.content++;
if (type)
{
questions = new ArrayList<JPanel>();
}
else
{
list = new ArrayList<JPanel>();
}
}
}
#SuppressWarnings("serial")
class Question extends JPanel
{
public JPanel questionArea, numberArea, answerArea;
public JLabel number;
public JTextArea question;
public AbstractDocument doc;
public Question(Page page, int pageNum, int index)
{
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
setBorder(BorderFactory.createMatteBorder(0, 0, 5, 0, Color.WHITE));
questionArea = new JPanel();
questionArea.setLayout(new BoxLayout(questionArea, BoxLayout.X_AXIS));
questionArea.setBorder(BorderFactory.createMatteBorder(0, 0, 8, 0, Color.WHITE));
numberArea = new JPanel();
numberArea.setLayout(new BorderLayout());
numberArea.setBackground(Color.WHITE);
number = new JLabel(pageNum+". ", JLabel.RIGHT);
number.setMinimumSize(new Dimension(100, 20));
number.setPreferredSize(new Dimension(100, 20));
number.setMaximumSize(new Dimension(100, 20));
number.setFont(new Font("Arial", Font.PLAIN, 17));
numberArea.add(number, BorderLayout.NORTH);
questionArea.add(numberArea);
question = new JTextArea();
question.setFont(new Font("Arial", Font.PLAIN, 17));
question.setBorder(BorderFactory.createDashedBorder(Color.BLACK));
question.setLineWrap(true);
question.setWrapStyleWord(true);
question.setBackground(Color.GREEN);
question.setText("Is this the first question?");
doc = (AbstractDocument)question.getDocument();
doc.setDocumentFilter(new DefaultDocFilter());
questionArea.add(question);
add(questionArea);
answerArea = new JPanel();
answerArea.setLayout(new BoxLayout(answerArea, BoxLayout.Y_AXIS));
add(answerArea);
page.add(this, index);
page.content++;
}
}
#SuppressWarnings("serial")
class Answer extends JPanel
{
public JPanel letterArea;
public JLabel letter;
public JTextArea answer;
public AbstractDocument doc;
public Answer(Question q, int index)
{
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
letterArea = new JPanel();
letterArea.setLayout(new BorderLayout());
letterArea.setBackground(Color.WHITE);
letter = new JLabel((char)(index+96)+") ", JLabel.RIGHT);
letter.setMinimumSize(new Dimension(150, 20));
letter.setPreferredSize(new Dimension(150, 20));
letter.setMaximumSize(new Dimension(150, 20));
letter.setFont(new Font("Arial", Font.PLAIN, 17));
letterArea.add(letter, BorderLayout.NORTH);
add(letterArea);
answer = new JTextArea();
answer.setFont(new Font("Arial", Font.PLAIN, 17));
Border in = BorderFactory.createDashedBorder(Color.BLACK);
Border out = BorderFactory.createMatteBorder(0, 0, 5, 0, Color.WHITE);
answer.setBorder(BorderFactory.createCompoundBorder(out, in));
answer.setLineWrap(true);
answer.setWrapStyleWord(true);
answer.addKeyListener(new KeyListener()
{
#Override
public void keyPressed(KeyEvent arg0)
{
System.out.print(((JTextComponent) arg0.getSource()).getText());
if (arg0.getKeyCode() == KeyEvent.VK_ENTER)
{
String JLabelText = ((JLabel) ((JPanel) ((JPanel) ((Component) arg0.getSource()).getParent()).getComponent(0)).getComponent(0)).getText();
int ansNum = (int)JLabelText.charAt(0)-95;
if (ansNum < 6)
{
Answer k = new Answer((Question) ((JTextArea) arg0.getSource()).getParent().getParent().getParent(), ansNum);
k.answer.grabFocus();
Main.mWindow.repaint();
Main.mWindow.validate();
}
}
}
public void keyReleased(KeyEvent arg0) {}
public void keyTyped(KeyEvent arg0) {}
});
doc = (AbstractDocument)answer.getDocument();
doc.setDocumentFilter(new DefaultDocFilter());
answer.setBackground(Color.PINK);
add(answer);
q.answerArea.add(this, index-1);
}
}
public class Main
{
public static Properties config;
public static Locale currentLocale;
public static ResourceBundle lang;
public static JFrame mWindow;
public static JMenuBar menu;
public static JMenu menuFile, menuEdit;
public static JMenuItem itmNew, itmClose, itmLoad, itmSave, itmSaveAs, itmExit, itmCut, itmCopy, itmPaste, itmProperties;
public static JDialog newDoc;
public static JLabel newDocText1, newDocText2;
public static JRadioButton questions, list;
public static ButtonGroup newDocButtons;
public static JButton newDocOk;
public static Boolean firstSegment;
public static JPanel workspace;
public static JScrollPane scroll;
public static ArrayList<Page> pages;
public static void newDocumentForm()
{
//new document dialog
mWindow.setEnabled(false);
newDoc = new JDialog(mWindow, "newDoc");
newDoc.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
newDoc.addWindowListener(new WindowListener ()
{
public void windowActivated(WindowEvent arg0) {}
public void windowClosing(WindowEvent arg0)
{
mWindow.toFront();
newDocText1 = null;
newDocText2 = null;
questions = null;
list = null;
newDocButtons = null;
newDocOk = null;
newDoc.dispose();
mWindow.setEnabled(true);
}
public void windowClosed(WindowEvent arg0) {}
public void windowDeactivated(WindowEvent arg0) {}
public void windowDeiconified(WindowEvent arg0) {}
public void windowIconified(WindowEvent arg0) {}
public void windowOpened(WindowEvent arg0) {}
});
newDoc.setSize(400, 200);
newDoc.setLocationRelativeTo(null);
newDoc.setResizable(false);
newDoc.setLayout(null);
newDoc.setVisible(true);
newDocText1 = new JLabel("newDocText1");
newDocText1.setBounds(5, 0, 400, 20);
newDocText2 = new JLabel("newDocText2");
newDocText2.setBounds(5, 20, 400, 20);
newDoc.add(newDocText1);
newDoc.add(newDocText2);
firstSegment = true;
questions = new JRadioButton("questions");
questions.setSelected(true);
questions.setFocusPainted(false);
questions.setBounds(10, 60, 400, 20);
questions.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
firstSegment = true;
}
});
list = new JRadioButton("list");
list.setFocusPainted(false);
list.setBounds(10, 80, 400, 20);
list.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
firstSegment = false;
}
});
newDoc.add(questions);
newDoc.add(list);
newDocButtons = new ButtonGroup();
newDocButtons.add(questions);
newDocButtons.add(list);
newDocOk = new JButton("ok");
newDocOk.addKeyListener(new KeyListener()
{
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_ENTER)
{
newDocOk.doClick();
}
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
});
newDocOk.setFocusPainted(false);
newDocOk.setBounds(160, 120, 80, 40);
newDocOk.setMnemonic(KeyEvent.VK_ACCEPT);
newDocOk.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
createNewDocument();
}
});
newDoc.add(newDocOk);
newDocOk.requestFocus();
}
public static void createNewDocument()
{
//dispose of new document dialog
mWindow.toFront();
newDocText1 = null;
newDocText2 = null;
questions = null;
list = null;
newDocButtons = null;
newDocOk = null;
newDoc.dispose();
mWindow.setEnabled(true);
//create document display
workspace = new JPanel();
workspace.setLayout(new BoxLayout(workspace, BoxLayout.PAGE_AXIS));
workspace.add(new Box.Filler(new Dimension(0, 40), new Dimension(0, 40), new Dimension(0, 40)));
workspace.setBackground(Color.BLACK);
scroll = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scroll.getVerticalScrollBar().setUnitIncrement(20);
scroll.setViewportView(workspace);
pages = new ArrayList<Page>();
Page p = new Page(workspace, 1);
new Heading(true, p);
Question q = new Question(p, 1, 1);
new Answer(q, 1);
mWindow.add(scroll, BorderLayout.CENTER);
mWindow.repaint();
mWindow.validate();
}
public static void main(String[] args) throws FileNotFoundException, IOException
{
//create main window
mWindow = new JFrame("title");
mWindow.setSize(1000, 800);
mWindow.setMinimumSize(new Dimension(1000, 800));
mWindow.setLocationRelativeTo(null);
mWindow.setLayout(new BorderLayout());
mWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mWindow.setVisible(true);
//create menu bar
menu = new JMenuBar();
menuFile = new JMenu("file");
menuEdit = new JMenu("edit");
itmNew = new JMenuItem("new");
itmNew.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
itmNew.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
newDocumentForm();
}
});
itmClose = new JMenuItem("close");
itmClose.setActionCommand("Close");
itmClose.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK));
itmLoad = new JMenuItem("load");
itmLoad.setActionCommand("Load");
itmLoad.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.CTRL_MASK));
itmSave = new JMenuItem("save");
itmSave.setActionCommand("Save");
itmSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
itmSaveAs = new JMenuItem("saveAs");
itmSaveAs.setActionCommand("SaveAs");
itmExit = new JMenuItem("exit");
itmExit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//Add confirmation window!
System.exit(0);
}
});
itmCut = new JMenuItem("cut");
itmCut.setActionCommand("Cut");
itmCut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK));
itmCopy = new JMenuItem("copy");
itmCopy.setActionCommand("Copy");
itmCopy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK));
itmPaste = new JMenuItem("paste");
itmPaste.setActionCommand("Paste");
itmPaste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK));
itmProperties = new JMenuItem("properties");
itmProperties.setActionCommand("properties");
itmProperties.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK));
menuFile.add(itmNew);
menuFile.add(itmClose);
menuFile.addSeparator();
menuFile.add(itmLoad);
menuFile.addSeparator();
menuFile.add(itmSave);
menuFile.add(itmSaveAs);
menuFile.addSeparator();
menuFile.add(itmExit);
menuEdit.add(itmCut);
menuEdit.add(itmCopy);
menuEdit.add(itmPaste);
menuEdit.addSeparator();
menuEdit.add(itmProperties);
menu.add(menuFile);
menu.add(menuEdit);
//create actionListener for menus
mWindow.add(menu, BorderLayout.NORTH);
mWindow.repaint();
mWindow.validate();
}
}
Why don't you assign String into DocumentFilter
str = str.replaceAll()?

Categories

Resources