Issues with ActionListener - java

I'm trying to write a program that asks you to click on a button to generate a random number and then makes the user try to guess what that number is.
Right now I'm working on getting a button click to generate a random number and to tell the user that the random number has been generated through a JTextPane. For whatever reason this part of the code doesn't seem to be executing correctly.
I have already instanced the object in the main class and I've added an actionlistener to the button. I have no idea what's causing this not to work appropriately:
package GUIs;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.JToggleButton;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import java.awt.Font;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Principal extends JFrame {
//Elements
private JPanel contentPane;
private JTextField attemptField;
private JTextPane hint;
private JButton btnGenerate;
private JButton btnEnter;
//Events
private GenerateRandomNumber genRanNum;
//Misc variables
int ranNum = 1;
private JTextField textField;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Principal frame = new Principal();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Principal() {
//Generates JPanel
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);
//Generates text field where the user will write the number
attemptField = new JTextField();
attemptField.setBounds(130, 59, 130, 26);
contentPane.add(attemptField);
attemptField.setColumns(10);
//Generates the hint
hint = new JTextPane();
hint.setBackground(SystemColor.window);
hint.setText("First, generate a new number!");
hint.setBounds(130, 110, 192, 19);
contentPane.add(hint);
//Generates the button that should call for the creation of the new number
btnGenerate = new JButton("Generate number");
btnGenerate.setFont(new Font("Lucida Grande", Font.PLAIN, 10));
btnGenerate.setBounds(165, 153, 117, 29);
contentPane.add(btnGenerate);
btnGenerate.addActionListener(genRanNum);
//Generates button that will be used to enter the number
btnEnter = new JButton("Enter");
btnEnter.setBounds(269, 59, 58, 29);
contentPane.add(btnEnter);
}
public class GenerateRandomNumber implements ActionListener {
public void actionPerformed(ActionEvent e) {
ranNum = (int) (Math.random() * 101);
hint.setText("The number has been created!");
}
}
}

private GenerateRandomNumber genRanNum;
Your random number generator is null. I don't see where you ever create an instance of it.
btnGenerate.addActionListener(genRanNum);
The above statement does nothing because the variable is null. (ie. no ActionListener has been added to the button)
I don't even know how your GenerateRandomNumber class would compile because it doesn't have access to the "hint" variable of your "Principal" class.
Don't make the GenerateRandomNumber class a public class. Instead make it an inner class of the "Principal" class.
Read the section from the Swing tutorial on How to Use Actions for an example showing how to use inner classes. Note you can even use an Action instead of an ActionListener.

Related

How to pass inputted data from JDialog to parent JFrame when user clicks button in JDialog?

How do I pass user-inputted date from a JDialog to the parent JFrame when the user clicks a certain button in the JDialog?
Here's how I want the program to work: When the user clicks a button in the JFrame, a JDialog pops up. The user then enters some data of various types (string and integer). If the user clicks an "Add Task" button, the data is passed back to the original JFrame, which will display the data, and the JDialog closes. If the user clicks the "Cancel" button, the data is discarded and the JDialog closes.
I thought about using JOptionPane, but I don't think it allows for data of various types. I thought about creating a method in the JFrame and calling it from the JDialog, but I don't know how to reference the JFrame. I thought about creating a variable in the JDialog, but I don't know to stop the JDialog from immediately passing an empty variable to the JFrame.
Any help?
Code for JFrame:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Dialog.ModalityType;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.JDialog;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class MainInterface extends JFrame {
private JPanel contentPane;
public MainInterface() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 400, 800);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton addTask = new JButton("Add");
addTask.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
NewTask newTask = new NewTask();
newTask.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
// Set window title
newTask.setTitle("Add Task");
newTask.setVisible(true);
}
});
addTask.setBounds(0, 728, 97, 25);
contentPane.add(addTask);
JButton modifyTask = new JButton("Modify");
modifyTask.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
modifyTask.setBounds(95, 728, 97, 25);
contentPane.add(modifyTask);
JButton deleteTask = new JButton("Delete");
deleteTask.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
deleteTask.setBounds(190, 728, 97, 25);
contentPane.add(deleteTask);
JButton settingMenu = new JButton("Settings");
settingMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Setting settings = new Setting();
settings.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
settings.setVisible(true);
settings.setTitle("Settings");
}
});
settingMenu.setBounds(285, 728, 97, 25);
contentPane.add(settingMenu);
}
}
The JFrame is launched by another class, so it doesn't have a main method.
Code for JDialog:
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import org.omg.CORBA.PUBLIC_MEMBER;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.JTextField;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;
import javax.swing.JSpinner;
import java.awt.event.ActionListener;
import java.util.jar.Attributes.Name;
import java.awt.event.ActionEvent;
public class NewTask extends JDialog {
private final JPanel contentPanel = new JPanel();
private JTextField taskName;
public NewTask() {
setBounds(100, 100, 450, 600);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
{
JLabel lblNewLabel = new JLabel("Name:");
lblNewLabel.setBounds(24, 13, 38, 16);
contentPanel.add(lblNewLabel);
}
{
taskName = new JTextField();
taskName.setBounds(79, 10, 304, 22);
contentPanel.add(taskName);
taskName.setColumns(10);
}
JLabel lblNewLabel_1 = new JLabel("Time Required:");
lblNewLabel_1.setBounds(24, 58, 97, 16);
contentPanel.add(lblNewLabel_1);
JSpinner hourSpinner = new JSpinner();
hourSpinner.setBounds(125, 55, 44, 22);
contentPanel.add(hourSpinner);
JLabel lblNewLabel_2 = new JLabel("hours");
lblNewLabel_2.setBounds(175, 58, 44, 16);
contentPanel.add(lblNewLabel_2);
// Set maximum value for minutes to 59
int min = 0;
int max = 59;
int step = 1;
int i = 1;
SpinnerModel value = new SpinnerNumberModel(i, min, max, step);
JSpinner minuteSpinner = new JSpinner(value);
minuteSpinner.setBounds(225, 55, 44, 22);
contentPanel.add(minuteSpinner);
JLabel lblNewLabel_3 = new JLabel("minutes");
lblNewLabel_3.setBounds(281, 58, 56, 16);
contentPanel.add(lblNewLabel_3);
JLabel lblNewLabel_4 = new JLabel("Deadline:");
lblNewLabel_4.setBounds(24, 108, 56, 16);
contentPanel.add(lblNewLabel_4);
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton addButton = new JButton("Add Task");
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
addButton.setActionCommand("OK");
buttonPane.add(addButton);
getRootPane().setDefaultButton(addButton);
}
{
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Close dialog window
dispose();
}
});
cancelButton.setActionCommand("Cancel");
buttonPane.add(cancelButton);
}
}
}
}
I thought about creating a method in the JFrame and calling it from
the JDialog, but I don't know how to reference the JFrame.
Even though this could be a nice solution, referencing the object who called the method is very discouraged.
See why (first answer): How to find the object that called a method in Java
One possible approach would be to create a method in the JFrame and adding a JFrame as a parameter for your newTask() function. Then, when invoking newTask() you pass this as an argument: newTask(this); .
Inside the modified newTask(JFrame frame) method, you just use the argument passed to reference the method in the parent JFrame.
This might seem the same as referencing the object who called the method, but it's not. Here you are passing as an argument the parent JFrame, which may not always be the object which invoked the method.
I hope I was clear enough, have a nice day!

label name can not be resolved

I've created a label loginLabel to show message on wrong authentication. I've kept this logic inside actionPerformed method, but I am getting error as loginLabel can not be resolved. How to remove this error? I've created my GUI using window-builder.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
import java.awt.Color;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.*;
public class FirstView {
private JFrame frmFirstProject;
private JTextField txtUsername;
private JPasswordField txtPassword;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FirstView window = new FirstView();
window.frmFirstProject.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public FirstView() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmFirstProject = new JFrame();
frmFirstProject.getContentPane().setBackground(new Color(51, 204, 204));
frmFirstProject.setTitle("first project");
frmFirstProject.setBounds(100, 100, 714, 491);
frmFirstProject.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmFirstProject.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBorder(new LineBorder(new Color(0, 0, 0), 3));
panel.setBounds(63, 47, 580, 354);
frmFirstProject.getContentPane().add(panel);
panel.setLayout(null);
JLabel lblUsername = new JLabel("Username:");
lblUsername.setBounds(24, 25, 69, 22);
panel.add(lblUsername);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setBounds(24, 66, 69, 22);
panel.add(lblPassword);
txtUsername = new JTextField();
txtUsername.setBounds(97, 26, 86, 20);
panel.add(txtUsername);
txtUsername.setColumns(10);
txtPassword = new JPasswordField();
txtPassword.setBounds(97, 67, 86, 20);
panel.add(txtPassword);
JButton btnsubmit = new JButton("submit");
frmFirstProject.getRootPane().setDefaultButton(btnsubmit); //enter key
btnsubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
int val = 0;
Connection sqlCon = DB_con.getSQLConnection();
PreparedStatement ps = sqlCon.prepareStatement("select 1 from tbl_user_info where username = ? and password = ?");
ps.setString(1, txtUsername.getText().toUpperCase());
ps.setString(2, String.valueOf(txtPassword.getPassword()).toUpperCase());
ResultSet rs = ps.executeQuery();
if (rs.next()) {
val = rs.getInt(1);
}
if(val != 1)
{
loginLabel.setVisible(true);
}
System.out.println("the value is: "+val);
sqlCon.close();
System.exit(0);
} catch (Exception e) {
System.out.println(e.toString());
}
}
});
btnsubmit.setBounds(94, 125, 89, 23);
panel.add(btnsubmit);
JPanel panel_display = new JPanel();
panel_display.setBounds(36, 181, 355, 50);
panel.add(panel_display);
panel_display.setLayout(null);
JLabel loginLabel = new JLabel("Login Authentication Mismatched. Please try again.");
loginLabel.setFont(new Font("Tahoma", Font.PLAIN, 13));
loginLabel.setBounds(10, 11, 319, 28);
panel_display.add(loginLabel);
loginLabel.setVisible(false);
JLabel lbl_header = new JLabel("LIBRARY MANAGEMENT SYSTEM");
lbl_header.setFont(new Font("Tahoma", Font.BOLD, 14));
lbl_header.setBounds(211, 11, 288, 25);
frmFirstProject.getContentPane().add(lbl_header);
}
}
You are referring to the local variable loginLabel within the anonymous ActionListener class which you previously added to btnSubmit. This will not work as code inside the ActionListener class (or any other class) cannot see variables that are local to a method.
Instead you should declare loginLabel as a field, up at the top of the class:
private JPasswordField txtPassword;
private JLabel loginLabel;
This is visible to all methods inside the class and also any non-static classes defined inside your class (such as the aforementioned ActionListener).
Then simply change the line which creates your label inside your initialize() method from:
JLabel loginLabel = new JLabel("Login Authentication Mismatched. Please try again.");
to
loginLabel = new JLabel("Login Authentication Mismatched. Please try again.");
Defining the loginLabel before the ActionListener will be adequate in java 8, as java 8 implicitly marks local fields that are defined but never changed as final. If you are targetting java 7 or earlier you would need to explicitly make that variable final.
To avoid problems like "LabelX can not be resolved" or "ButtonY can not be resolved", I learned to do this:
On Eclipse, go to "Window" module...
Choose item "Preferences"...
Choose "WindowBuilder"...
Choose "Swing" or "SWT"...
In "Code Generation", choose "Field" in variable generation...
Inside "Event handlers", choose "Implement listener interface in parent class"...
It works using Java 1.7 or 1.8. Say bye bye to errors in ActionListner Class and GUI components Swing or SWT. And sure, i'm using WindowBuilder plugin to build the GUI application.

About Jcheckbox state, java

I am trying to do an action on button being clicked, but i need to make a check whether JCheckBox is checked or not.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.*;
import javax.swing.*;
public class RandomPassword extends JFrame{
RandomPassword(String s){
super(s);
setSize(300,300);
setVisible(true);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent ev){
System.exit(0);
}
});
setLayout(null);
setFont(new Font("Serif", Font.PLAIN, 20));
Label l1 = new Label("Введите количество символов:");
l1.setBounds(50, 100, 200, 30);
add(l1);
JTextField tf1 = new JTextField(1002);
tf1.setBounds(50,130,200,30);
add(tf1);
JTextArea ta1 = new JTextArea();
ta1.setPreferredSize(new Dimension(150,30));
ta1.setBounds(50,210,230,30);
add(ta1);
JCheckBox ch1 = new JCheckBox("Использовать заглавные буквы");
ch1.setBounds(50, 0, 200, 30);
add(ch1);
JCheckBox ch2 = new JCheckBox("Использовать цифры");
ch2.setBounds(50, 30, 200, 30);
add(ch2);
JCheckBox ch3 = new JCheckBox("Использовать спецсимволы");
ch3.setBounds(50, 60, 200, 30);
add(ch3);
JButton b1 = new JButton("Сгенерировать");
b1.setBounds(75, 170, 150, 30);
add(b1);
b1.addActionListener(new Action());
}
public static void main(String[] args){
new RandomPassword("Генератор случайных паролей");
}
static class Action implements ActionListener{
public void actionPerformed(ActionEvent e){
}
}
}
I want to make a Checkbox in static class Action, but he is throwing me an exception. What do i have to do?
Trying this one didn`t help me.
JButton b1 = new JButton(new AbstractAction("Сгенерировать") {
public void actionPerformed(ActionEvent e) {
ch1.isSelected();
}
});
You can access to the cliked JCheckBox with:
((JCheckBox)e.getSource())
The way your program is structured your check boxes are not in the scope of the actionPerformed method. One way to counter this would be to use an anonymous inner class directly in the contructor.
final JCheckBox ch3 = new JCheckBox("Использовать спецсимволы");
...
b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println(ch3.isSelected());
}});
Note that this way you need to make the check box variable final, so it can be accessed in the inner class. You can then use the isSelected method to check whether the check box is currently selected.
As an unrelated note, better put the call to setVisible(true) at the end of the constructor, otherwise it seems like some GUI elements are not drawn correctly.

Focus on Keylistener

So what I've got is that I would love to try and make an little login applet. I'm using Java Windowsbuilder for it, to make it easyer for me. I hope the code isn't to messy, because I'm just a starter.
The problem I've got is that My JButton "login" only registers a keyevent when it's selected trought tab, or when you first click it. What I want is that I can use the button always just by pressing the "ENTER" key.
Hope you guys solve my problem :)
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import org.eclipse.wb.swing.FocusTraversalOnArray;
import java.awt.Component;
import java.awt.event.KeyAdapter;
public class nummer1 extends JFrame{
private JPanel contentPane;
public static nummer1 theFrame;
private JTextField textFieldUsername;
private JTextField textFieldPass;
private nummer1 me;
private JLabel lblCheck;
private String password = "test", username = "test";
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
nummer1 frame = new nummer1();
nummer1.theFrame = frame;
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void Check(){
String Pass = textFieldPass.getText();
String Username = textFieldUsername.getText();
System.out.println(Pass);
if (Pass.equals(password) && Username.equals(username)){
lblCheck.setText("Correct Login");
}else{
lblCheck.setText("Invalid username or password");
}
}
/**
* Create the frame.
*/
public nummer1() {
me = this;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 356, 129);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblUsername = new JLabel("Username:");
lblUsername.setBounds(10, 11, 61, 14);
contentPane.add(lblUsername);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setBounds(10, 36, 61, 14);
contentPane.add(lblPassword);
textFieldUsername = new JTextField();
textFieldUsername.setBounds(81, 8, 107, 20);
contentPane.add(textFieldUsername);
textFieldUsername.setColumns(10);
me.textFieldUsername = textFieldUsername;
textFieldPass = new JTextField();
textFieldPass.setBounds(81, 33, 107, 20);
contentPane.add(textFieldPass);
textFieldPass.setColumns(10);
me.textFieldPass = textFieldPass;
JButton btnLogin = new JButton("Login");
contentPane.requestFocusInWindow();
btnLogin.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER){
me.Check();
System.out.println("hi");
}
}
});
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
me.Check();
}
});
btnLogin.setBounds(198, 7, 89, 23);
contentPane.add(btnLogin);
JLabel lblCheck = new JLabel("");
lblCheck.setHorizontalAlignment(SwingConstants.TRAILING);
lblCheck.setBounds(10, 65, 264, 14);
contentPane.add(lblCheck);
me.lblCheck = lblCheck;
contentPane.setFocusTraversalPolicy(new FocusTraversalOnArray(new
Component[]{lblUsername, lblPassword, textFieldUsername, textFieldPass, btnLogin, lblCheck}));
}
}
Thanks Emil!
What I want is that I can use the button always just by pressing the "ENTER" key
Sounds like you want to make the "login" button the default button for the dialog.
See Enter Key and Button for the problem and solution.
When using panels KeyListeners won't work unless the panel is focusable. What you can do is make a KeyBinding to the ENTER key using the InputMap and ActionMap for your panel.
public class Sample extends JPanel{
//Code
Sample() {
//More code
this.getInputMap().put(KeyStroke.getKeyStroke((char)KeyEvent.VK_ENTER), "Enter" );
this.getActionMap().put("Enter", new EnterAction());
}
private class EnterAction extends AbstractAction(){
#Override
public void ActionPerformed(ActionEvent e){
//Acion
}
}
}

Need help using JFileChooser for the first time

To be blunt about it, I'm looking for help as to how to actually use it. We have just been set work using this on my course, but our new teacher does not teach, and I'm really struggling with this one. So I have a basic JFrame set up using windows builder, and the object is to be able to open a text file as a string and put it into the text space, and then be able to find strings in the text and change them. I'll paste the code I have below, if anyone can help explain how to do this, I'll really appriciate it, thanks. :)
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.TextArea;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.File;
import javax.swing.filechooser.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class task1 extends JFrame {
private JPanel contentPane;
private JTextField findTxtBox;
private JButton findBtn;
private JTextField replaceTxtBox;
private JTextField fileTxtBox;
private JButton openBtn;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
task1 frame = new task1();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public task1() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 312);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
TextArea textArea = new TextArea();
textArea.setBounds(10, 45, 380, 160);
contentPane.add(textArea);
findTxtBox = new JTextField();
findTxtBox.setBounds(80, 211, 236, 20);
contentPane.add(findTxtBox);
findTxtBox.setColumns(10);
findBtn = new JButton("Find");
findBtn.setBounds(326, 210, 89, 23);
contentPane.add(findBtn);
JButton btnReplace = new JButton(" Replace");
btnReplace.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnReplace.setBounds(326, 240, 89, 23);
contentPane.add(btnReplace);
replaceTxtBox = new JTextField();
replaceTxtBox.setColumns(10);
replaceTxtBox.setBounds(80, 242, 236, 20);
contentPane.add(replaceTxtBox);
fileTxtBox = new JTextField();
fileTxtBox.setColumns(10);
fileTxtBox.setBounds(80, 11, 236, 20);
contentPane.add(fileTxtBox);
final JFileChooser fc = new JFileChooser();
fc.setFileFilter(new FileNameExtensionFilter("Text Files", "txt"));
fc.removeChoosableFileFilter(fc.getAcceptAllFileFilter());
openBtn = new JButton("Open File");
openBtn.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
fc.showOpenDialog(null);
}
});
openBtn.setBounds(326, 10, 89, 23);
contentPane.add(openBtn);
}
}
the object is to be able to open a text file as a string and put it into the text space, and then be able to find strings in the text and change them.
That involves a lot more than just using a file chooser. I suggest you start by reading the section from the Swing tutorial on How to Use File Choosers for a working example.
The file chooser is just used to get a file name not read a file. So next I would suggest you use a JTextArea (not a TextArea) to display the text from the file that you read. You can use the read(...) method of the JTextArea to do this.
All text components have a getText() method you can use the get the text. You can then search the string for whatever you want and replace the text by using the replace() method of a JTextArea.
Finally you should NOT be using the setBounds() method to set the size/location of a component. You should be using Layout Managers and let them do their job. The Swing tutorial also has a section on using layout managers.

Categories

Resources