I am creating a slot machine project(for fun).I am displaying the fruits in a JTextField. I have managed to display random fruits in the JTextFields, but the random fruits are the same, for example, the result would be -> Orange, Orange, Orange. Or it would be, Kiwi, Kiwi, Kiwi. ETC.
Here is my code.
import java.awt.BorderLayout;...
import java.util.Random;
public class Game extends JFrame {
String [] fruits = { "Cherry", "Lemon", "Orange", "Grape", "Kiwi" };
String fruit = fruits[(int) (Math.random() * fruits.length)];
private JPanel contentPane;
private JTextField Slot_1;
private JTextField Slot_2;
private JTextField Slot_3;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Game frame = new Game();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Game() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
Slot_1 = new JTextField();
Slot_1.setText("----------------");
Slot_1.setEditable(false);
Slot_1.setBounds(41, 53, 95, 28);
contentPane.add(Slot_1);
Slot_1.setColumns(10);
Slot_2 = new JTextField();
Slot_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
Slot_2.setText("-----------------");
Slot_2.setEditable(false);
Slot_2.setColumns(10);
Slot_2.setBounds(183, 53, 95, 28);
contentPane.add(Slot_2);
Slot_3 = new JTextField();
Slot_3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
Slot_3.setText("---------------");
Slot_3.setEditable(false);
Slot_3.setColumns(10);
Slot_3.setBounds(317, 53, 95, 28);
contentPane.add(Slot_3);
JButton btn_Pull = new JButton("Pull");
btn_Pull.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Slot_1.setText(fruit);
Slot_2.setText(fruit);
Slot_3.setText(fruit);
}
});
btn_Pull.setBounds(145, 108, 166, 29);
contentPane.add(btn_Pull);
JButton btnMenu = new JButton("Menu");
btnMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnMenu.setBounds(383, 243, 61, 29);
contentPane.add(btnMenu);
}
}
Thank you
String fruit = fruits[(int) (Math.random() * fruits.length)];
The value of fruit is fixed at the start of your class.
Slot_1.setText(fruit);
Slot_2.setText(fruit);
Slot_3.setText(fruit);
The value of fruit doesn't change just because you assign it to 3 different text fields.
If you want random values then you need to invoke the random() method 3 time. Maybe something like:
Slot_1.setText( fruits[(int) (Math.random() * fruits.length)] );
...
Or create a method that returns a random string:
private String getFruit()
{
return fruits[(int) (Math.random() * fruits.length)];
}
and use:
slot_1.setText( getFruit() );
Also:
Variable names should not start with an upper case character (Slot_1...). Your other variables are correct (fruits, fruit) so be consistent.
Don't use a null layout. Swing was designed to be used with layout managers.
Slot_1.setText(fruit);
Slot_2.setText(fruit);
Slot_3.setText(fruit);
You expect these the magically change somehow? fruit is simply a string variable, and you only set it once at the top of your class. You need to call the Math.random() function for each slot. You could do this by making fruit a function that got the random number and produced a new fruit each time, then you'd replace fruit above by fruit(). Or you could just copy the simple code line from the top int the lines here.
add a function to your class called generateFruit();
private String generateFruit()
{
return this.fruits[(int) (Math.random() * this.fruits.length)];
}
then call it instead of the set fruit variable.
Slot_1.setText(this.generateFruit());
I also added in a method that changes fruit1, fruit2 and fruit3, and I call that method in the action listener that changes the values. This will change the values every time you push pull.
public class Game extends JFrame {
String [] fruits = { "Cherry", "Lemon", "Orange", "Grape", "Kiwi" };
String fruit1 = fruits[(int) (Math.random() * fruits.length)];
String fruit2 = fruits[(int) (Math.random() * fruits.length)];
String fruit3 = fruits[(int) (Math.random() * fruits.length)];
private JPanel contentPane;
private JTextField Slot_1;
private JTextField Slot_2;
private JTextField Slot_3;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Game frame = new Game();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Game() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
Slot_1 = new JTextField();
Slot_1.setText("----------------");
Slot_1.setEditable(false);
Slot_1.setBounds(41, 53, 95, 28);
contentPane.add(Slot_1);
Slot_1.setColumns(10);
Slot_2 = new JTextField();
Slot_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
Slot_2.setText("-----------------");
Slot_2.setEditable(false);
Slot_2.setColumns(10);
Slot_2.setBounds(183, 53, 95, 28);
contentPane.add(Slot_2);
Slot_3 = new JTextField();
Slot_3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
Slot_3.setText("---------------");
Slot_3.setEditable(false);
Slot_3.setColumns(10);
Slot_3.setBounds(317, 53, 95, 28);
contentPane.add(Slot_3);
JButton btn_Pull = new JButton("Pull");
btn_Pull.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Slot_1.setText(fruit1);
Slot_2.setText(fruit2);
Slot_3.setText(fruit3);
newRandomPullValues();
}
});
btn_Pull.setBounds(145, 108, 166, 29);
contentPane.add(btn_Pull);
JButton btnMenu = new JButton("Menu");
btnMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnMenu.setBounds(383, 243, 61, 29);
contentPane.add(btnMenu);
}
public void newRandomPullValues() {
fruit1 = fruits[(int) (Math.random() * fruits.length)];
fruit2 = fruits[(int) (Math.random() * fruits.length)];
fruit3 = fruits[(int) (Math.random() * fruits.length)];
}
}
Related
When I add:
this.dispose();
The window is not closing, what can I do?.
I use Eclipse with windowsBuilder.
I want to close the actual window to open another window.
My code:
public class Ventana_login extends JFrame {
/**
*
*/
private static final long serialVersionUID = -7948060398287723741L;
private JPanel contentPane;
private JTextField txtUsuario;
private JPasswordField txtContrasena;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Ventana_login frame = new Ventana_login();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Ventana_login() {
setTitle("Sistema Gestor de Eventos v1.0");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblBienvenidoAlSistema = new JLabel("Bienvenido");
lblBienvenidoAlSistema.setHorizontalAlignment(SwingConstants.CENTER);
lblBienvenidoAlSistema.setFont(new Font("Tahoma", Font.BOLD, 16));
lblBienvenidoAlSistema.setBounds(10, 11, 424, 14);
contentPane.add(lblBienvenidoAlSistema);
JLabel lblUsuario = new JLabel("Usuario");
lblUsuario.setHorizontalAlignment(SwingConstants.RIGHT);
lblUsuario.setBounds(96, 79, 70, 14);
contentPane.add(lblUsuario);
JLabel lblContrasena = new JLabel("Contrase\u00F1a");
lblContrasena.setHorizontalAlignment(SwingConstants.RIGHT);
lblContrasena.setBounds(96, 109, 70, 14);
contentPane.add(lblContrasena);
txtUsuario = new JTextField();
txtUsuario.setBounds(176, 76, 150, 20);
contentPane.add(txtUsuario);
txtUsuario.setColumns(10);
JButton btnIniciarSesion = new JButton("Iniciar Sesi\u00F3n");
btnIniciarSesion.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
Dato_login d_lgn = new Dato_login();
Logica_login l_lgn = new Logica_login();
d_lgn.setUsuario(txtUsuario.getText());
char[] contrasenaChar = txtContrasena.getPassword();
String contrasenaClean = new String(contrasenaChar);
d_lgn.setContrasena(contrasenaClean);
Dato_login d_lgn2 = l_lgn.login(d_lgn.getUsuario(), d_lgn.getContrasena());
if (Logica_login.resultado) {
Ventana_menu v_menu = new Ventana_menu();
v_menu.setVisible(true);
v_menu.setLocationRelativeTo(null);
Ventana_menu.lblPerfilActual.setText(d_lgn2.getPerfil());
Ventana_menu.lblApellidoActual.setText(d_lgn2.getApellido());
Ventana_menu.lblNombreActual.setText(d_lgn2.getNombre());
Ventana_menu.lblUsuarioActual.setText(d_lgn2.getUsuario());
if (Ventana_menu.lblPerfilActual.getText().equals("Portero")) {
Ventana_menu.btnMantenimiento_Eventos.setEnabled(false);
Ventana_menu.btnMantenimiento_Invitaciones.setEnabled(false);
Ventana_menu.btnMantenimiento_Invitados.setEnabled(false);
Ventana_menu.btnMantenimiento_Usuarios.setEnabled(false);
Ventana_menu.btnReportes.setEnabled(true);
} else {
Ventana_menu.btnMantenimiento_Eventos.setEnabled(true);
Ventana_menu.btnMantenimiento_Invitaciones.setEnabled(true);
Ventana_menu.btnMantenimiento_Invitados.setEnabled(true);
Ventana_menu.btnMantenimiento_Usuarios.setEnabled(true);
Ventana_menu.btnReportes.setEnabled(true);
}
this.dispose();
} else {
JOptionPane.showMessageDialog(contentPane, "Acceso Denegado", "Error", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Exception:\n" + e, "Error: Ventana_login", JOptionPane.ERROR_MESSAGE);
}
}
});
btnIniciarSesion.setBounds(176, 163, 150, 30);
contentPane.add(btnIniciarSesion);
I will assume by window you mean JFrame:
then do:
myJframe.dispatchEvent(new WindowEvent(myJframe, WindowEvent.WINDOW_CLOSING));
I need a method so that when the user presses the nextCustomerBtn it will load the previous screen.
Any help would be much appreciated.
This is the extract from class MenuPage
JButton nextCustomerBtn = new JButton("Next Customer");
nextCustomerBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
nextCustomerBtn.setBounds(364, 306, 127, 29);
contentPane.add(nextCustomerBtn);
}
This is the code for the previous screen.
public class Restaurant extends JFrame {
private JPanel contentPane;
private JTextField restaurantTxt;
private JTextField numDiners;
private JTextField numDinersTxt;
private JTextField tableNumTxt;
private JTextField numTable;
private JButton numTableSubBtn;
private JButton proceedMenuBtn;
MenuPage parent;
/**
* Launch the application.
*/
////
public static String tableNumber;
public static String dinerNumber;
////
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Restaurant frame = new Restaurant();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Restaurant() {
super("Restaurant");
parent = new MenuPage();
initGUI();
// numTable = new JTextField("NewUser", 10);
}
public void initGUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 840, 368);
contentPane = new JPanel();
contentPane.setBackground(new Color(100, 149, 237));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
restaurantTxt = new JTextField();
restaurantTxt.setHorizontalAlignment(SwingConstants.CENTER);
restaurantTxt.setEditable(false);
restaurantTxt.setText("Matthew's Restaurant");
restaurantTxt.setBounds(340, 23, 191, 20);
contentPane.add(restaurantTxt);
restaurantTxt.setColumns(10);
numDiners = new JTextField("", 10);
numDiners.addKeyListener(new KeyAdapter() {
#Override
public void keyTyped(KeyEvent e) { //method to only allow the textfield to accept numbers, backspace or delete.
char c=e.getKeyChar();
if(!(Character.isDigit(c) || (c==KeyEvent.VK_BACK_SPACE)||c==KeyEvent.VK_DELETE)){
e.consume(); // consume will not allow the user to enter anyhting but a number.
if (e.getKeyCode() == 10) {
JOptionPane.showMessageDialog(Restaurant.this, "Please select a meal");
}
}
}
});
numDiners.setBounds(448, 89, 83, 26);
contentPane.add(numDiners);
numDiners.setColumns(10);
JButton numDinersSubBtn = new JButton("Submit");
numDinersSubBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dinerNumber = numDiners.getText();
numDiners.setText(""); // this sets the textfield to be blank when the submit button is entered.
}
});
numDinersSubBtn.setBounds(612, 89, 83, 29);
contentPane.add(numDinersSubBtn);
numDinersTxt = new JTextField();
numDinersTxt.setEditable(false);
numDinersTxt.setText("Number of diners ?");
numDinersTxt.setBounds(251, 89, 130, 26);
contentPane.add(numDinersTxt);
numDinersTxt.setColumns(10);
tableNumTxt = new JTextField();
tableNumTxt.setEditable(false);
tableNumTxt.setText("Table number ?");
tableNumTxt.setBounds(252, 164, 130, 26);
contentPane.add(tableNumTxt);
tableNumTxt.setColumns(10);
numTable = new JTextField("", 10);
numTable.addKeyListener(new KeyAdapter() {
#Override
public void keyTyped(KeyEvent e) {
char c=e.getKeyChar();
if(!(Character.isDigit(c) || (c==KeyEvent.VK_BACK_SPACE)||c==KeyEvent.VK_DELETE)){
e.consume();
//method to only allow the textfield to accept numbers, backspace or delete
if (e.getKeyCode() == 10) { // consume will not allow the user to enter anyhting but a number.
//tableNumber = numTable.getText();
//System.out.println("enter pressed");
}
}
}
});
numTable.setBounds(448, 164, 83, 26);
contentPane.add(numTable);
numTable.setColumns(10);
numTableSubBtn = new JButton("Submit");
numTableSubBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tableNumber = numTable.getText();
numTable.setText("");
}
});
numTableSubBtn.setBounds(612, 164, 83, 29);
contentPane.add(numTableSubBtn);
proceedMenuBtn = new JButton("Proceed to menu");
proceedMenuBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
MenuPage nw = new MenuPage(); // the new visual class window has been created and called MenuPage. The proceedMenuBtn
nw.NewScreen(); // takes the user to the NewScreen.
}
});
proceedMenuBtn.setBounds(608, 265, 135, 29);
contentPane.add(proceedMenuBtn);
JTextPane txtpnWelcomeToMatthews = new JTextPane();
txtpnWelcomeToMatthews.setEditable(false);
txtpnWelcomeToMatthews.setText("Welcome to Matthew's Restaurant\n\nTo get started with your dining experience please enter the number of diners and the table number of your choice.\n\nPress Submit when done.\n\nPress proceed to menu.\n\nEnjoy.");
txtpnWelcomeToMatthews.setBounds(20, 38, 183, 256);
contentPane.add(txtpnWelcomeToMatthews);
}
}
I'm trying to filter data in my array list according to my comboBox selected item wise. I still can't solve this problem.
public class FoodItem {
private String name;
private String type;
public FoodItem(String n,String t){
name=n;
type=t;
}
public String getType(){
return type;
}
public String getName(){
return name;
}
}
sample.java
<code>
public class A2Demo extends JFrame {
private JPanel contentPane;
private JTextField txtName;
List listFoodItem = new List();
JComboBox comboType = new JComboBox();
FoodItem[] foodItems;
private final JTextField txtBudget = new JTextField();
private final JButton btnBudget = new JButton("Search Budget");
private final JTextField textField = new JTextField();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
A2Demo frame = new A2Demo();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public A2Demo() {
textField.setBounds(93, 247, 134, 28);
textField.setColumns(10);
txtBudget.setBounds(183, 11, 86, 20);
txtBudget.setColumns(10);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 334);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
foodItems=new FoodItem[2];
foodItems[0]=new FoodItem("Chicken Cutlet","Main");
foodItems[1]=new FoodItem("Chendol","Dessert");
comboType.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
comboType.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent arg0) {
JOptionPane.showMessageDialog(null,comboType.getSelectedItem());
}
});
comboType.setBounds(32, 11, 93, 20);
contentPane.add(comboType);
for(int i=0; i<foodItems.length; i++)
comboType.addItem(foodItems[i].getType());
listFoodItem.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
txtName.setText(listFoodItem.getSelectedItem());
}
});
listFoodItem.setBounds(37, 63, 330, 125);
contentPane.add(listFoodItem);
JLabel lblName = new JLabel("Name");
lblName.setBounds(37, 217, 46, 14);
contentPane.add(lblName);
txtName = new JTextField();
txtName.setBounds(93, 214, 134, 20);
contentPane.add(txtName);
txtName.setColumns(10);
contentPane.add(txtBudget);
btnBudget.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null, comboType.getSelectedItem()+ " "+txtBudget.getText());
}
});
btnBudget.setBounds(280, 10, 127, 23);
contentPane.add(btnBudget);
contentPane.add(textField);
}
}
i want to display food name in the list. but combobox changeing to different type my list need to change according l
public class Sort_BenchMark extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JButton btnBubbleSort;
private JLabel label_1;
private JButton btnGenerate;
private JButton btnSelectionSort;
private JLabel lblSs;
private JLabel lblStatus;
/**
* Launch the application.
*/
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
Sort_BenchMark frame = new Sort_BenchMark();
frame.setVisible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Sort_BenchMark()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textField = new JTextField("Enter ");
textField.setForeground(Color.GRAY);
textField.addFocusListener(new FocusListener() {
#Override
public void focusLost(FocusEvent e) {
// TODO Auto-generated method stub
}
#Override
public void focusGained(FocusEvent e) {
textField.setText("");
textField.setForeground(Color.BLACK);
}
});
textField.setBounds(29, 30, 139, 20);
contentPane.add(textField);
textField.setColumns(10);
label_1 = new JLabel("");
label_1.setBounds(334, 20, 120, 30);
contentPane.add(label_1);
btnBubbleSort = new JButton("Bubble Sort");
btnBubbleSort.setBounds(204, 20, 120, 30);
contentPane.add(btnBubbleSort);
btnSelectionSort = new JButton("Selection Sort");
btnSelectionSort.setBounds(204, 70, 120, 30);
contentPane.add(btnSelectionSort);
lblSs = new JLabel("");
lblSs.setBounds(334, 70, 120, 30);
contentPane.add(lblSs);
lblStatus = new JLabel("");
lblStatus.setBounds(75, 87, 93, 23);
contentPane.add(lblStatus);
final JRadioButton rdbtnAvgCase = new JRadioButton("Avg Case");
rdbtnAvgCase.setBounds(29, 150, 109, 23);
contentPane.add(rdbtnAvgCase);
ButtonGroup b = new ButtonGroup();
b.add(rdbtnAvgCase);
btnGenerate = new JButton("Generate");
btnGenerate.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
btnBubbleSort.setEnabled(true);
btnSelectionSort.setEnabled(true);
final String s = textField.getText();
if(s.contentEquals(""))
{
lblStatus.setText("Enter length");
}
else
{
lblStatus.setText("Ready");
if(rdbtnAvgCase.isSelected())
{
btnBubbleSort.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Thread t1 = new Thread(new Runnable()
{
#Override
public void run()
{
btnBubbleSort.setEnabled(false);
label_1.setText("done");
btnBubbleSort.setEnabled(true);
}
});
t1.start();
}
});
btnSelectionSort.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Thread t3 = new Thread(new Runnable()
{
#Override
public void run()
{
btnSelectionSort.setEnabled(false);
lblSs.setText("done");
btnSelectionSort.setEnabled(true);
}
});
t3.start();
}
});
}
}
}
});
btnGenerate.setBounds(64, 62, 88, 25);
contentPane.add(btnGenerate);
}
}
The above code is about Swing.
The actual code how i designed is:-(In the frame)
Select the Average Case (RadioButton)
Enter any number in textfield (Enter)
click on generate
click on any sort button(Bubble Sort and Selection Sort)
Now, whats the problem is, If I click on BubbleSort the text field gets cleared. But it should not happen as per I designed. Can anyone suggest me the solution so that text field wont get clear after entered anything in it?
These lines here:
#Override
public void focusGained(FocusEvent e) {
textField.setText(""); //HERE
textField.setForeground(Color.BLACK);
}
in the focus listener code says that when you click in the textfield then set its text to a empty string.
Firstly, horrible nested ActionPerformed you've got there.
That aside, Vincent Ramdhanie is right as to where the problem is originating. The reason why it only happens when you click a certain button, is because when you disable a button, then it cannot have focus, which forces the focus to be on something else, which in the disable-btnBubbleSort's case, appears to be your textfield.
Instead of btnSelectionSort.setEnabled(false) and btnSelectionSort.setEnabled(true), try using setVisible(false) and setVisible(true).
If that doesn't work, drop the onfocus-part, and do something with a mouse-click event instead.
A software component is required which allows to find a given word in a given passage, whenever the component find the desired word in the passage the components will invoke all the listener that are attached to it that it has find the desired word.
This component must be used from a Swing UI based application showing user a text field to take a word and a text area for passage. There must be a label which will update its value showing count that how many times the given word has been found within the given passage.
this is my code it's displya gui but count field is not changed or set.
import java.awt.EventQueue;
public class compomentex implements ActionListener{
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
private JTextArea textArea;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
compomentex window = new compomentex();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public interface wordsearcherinterface
{
public void wordsearch();
}
public class wordsearcher implements wordsearcherinterface
{
public String word;
public String paragraph;
public void addwordsearch(wordsearcherinterface obj)
{
obj.wordsearch();
}
public void wordsearch()
{
//if(event.getSource()==Check)
String word;
String Words;
String [] Words2;
int disp=0;
word=textField.getText();
Words=textArea.getText();
Words2=Words.split(" ");
for(int i=0;i<Words2.length;i++)
{
if(Words2[i].equals(word))
{
disp++;
}
}
String show;
show=disp+"";
textField_1.setText(show);
if(disp==0)
{
JOptionPane.showMessageDialog(null, "The Word is not present int Passage");
}
}
}
* Create the application.
public compomentex() {
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(null);
JLabel lblWord = new JLabel("WORD");
lblWord.setBounds(29, 81, 46, 14);
frame.getContentPane().add(lblWord);
textField = new JTextField();
textField.setBounds(121, 78, 86, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
JLabel lblPassage = new JLabel("PASSAGE");
lblPassage.setBounds(29, 143, 46, 14);
frame.getContentPane().add(lblPassage);
JTextArea textArea = new JTextArea();
textArea.setBounds(97, 161, 196, 90);
frame.getContentPane().add(textArea);
JButton btnCheck = new JButton("CHECK");
btnCheck.setBounds(326, 213, 98, 23);
frame.getContentPane().add(btnCheck);
JLabel lblSeeker = new JLabel("SEEKER");
lblSeeker.setBounds(161, 11, 46, 14);
frame.getContentPane().add(lblSeeker);
JLabel lblCount = new JLabel("COUNT");
lblCount.setBounds(349, 81, 46, 14);
frame.getContentPane().add(lblCount);
textField_1 = new JTextField();
textField_1.setBounds(325, 106, 86, 20);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
Thanks in advance
There are lots of issues in your code. I have mentioned corrected code below. Please correct.
First - actionPerformed method is empty.
#Override
public void actionPerformed(ActionEvent arg0) {
new wordsearcher().wordsearch();
}
Second - instance variable textArea is not initialized.
textArea = new JTextArea();
Third - ActionListener is not added on button btnCheck
btnCheck.addActionListener(this);