I have a browse button which opens a dialog where the user can view directories and files. I am having some trouble appending the files the user selects to a JTextArea. I am trying to do this so the user can select multiple files at a time. The files eventually will be submitted to an Oracle database.
The code I have used for the filechooser is here:
final JFileChooser fc = new JFileChooser();
JList list = new JList();
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
if (JFileChooser.APPROVE_OPTION == fc.showOpenDialog(list)) {
File file = fc.getSelectedFile();
Can you please show me how to append the files to a JTextArea?
Thanks.
Edit:
I have added the following:
JButton btnBrowse = new JButton("Browse");
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
final JFileChooser fc = new JFileChooser();
fc.setMultiSelectionEnabled(true);
JList list = new JList();
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
if (JFileChooser.APPROVE_OPTION == fc.showOpenDialog(list)) {
File file = fc.getSelectedFile();
}
for (File file : fc.getSelectedFiles()) {
log.append(file.getPath());
}
}
});
But when selecting browse and choosing multiple files and then selecting open the files are not being displayed within the text area.
Full Code:
package com.example.android.apis.appwidget;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Font;
import javax.swing.JFileChooser;
import javax.swing.JList;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JCheckBox;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.File;
import java.awt.Color;
import javax.swing.UIManager;
public class VFSTool extends JFrame {
private JPanel contentPane;
static private final String newline = "\n";
JButton openButton, saveButton;
JTextArea log;
JFileChooser fc;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
VFSTool frame = new VFSTool();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Tool() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 499, 423);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JLabel lblVfsLoaderTool = new JLabel("Tool");
lblVfsLoaderTool.setBackground(new Color(255, 255, 153));
lblVfsLoaderTool.setForeground(UIManager.getColor("Button.darkShadow"));
lblVfsLoaderTool.setFont(new Font("Copperplate Gothic Light", Font.BOLD, 25));
lblVfsLoaderTool.setHorizontalAlignment(SwingConstants.CENTER);
contentPane.add(lblVfsLoaderTool, BorderLayout.NORTH);
JPanel panel = new JPanel();
panel.setBackground(UIManager.getColor("Button.darkShadow"));
contentPane.add(panel, BorderLayout.CENTER);
panel.setLayout(null);
JButton btnBrowse = new JButton("Browse");
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
final JFileChooser fc = new JFileChooser();
fc.setMultiSelectionEnabled(true);
JList list = new JList();
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
if (JFileChooser.APPROVE_OPTION == fc.showOpenDialog(list)) {
File file = fc.getSelectedFile();
}
for (File file : fc.getSelectedFiles()) {
log.append(file.getPath() + System.getProperty("line.separator"));
}
}
});
btnBrowse.setBounds(107, 185, 97, 25);
panel.add(btnBrowse);
JLabel lblCategory = new JLabel("label1");
lblCategory.setForeground(UIManager.getColor("Button.background"));
lblCategory.setBounds(12, 13, 82, 25);
panel.add(lblCategory);
JComboBox comboBox = new JComboBox();
comboBox.setForeground(UIManager.getColor("Button.background"));
comboBox.setBounds(91, 13, 113, 24);
panel.add(comboBox);
JLabel lblNewLabel = new JLabel("label2");
lblNewLabel.setForeground(UIManager.getColor("Button.background"));
lblNewLabel.setBounds(12, 50, 77, 25);
panel.add(lblNewLabel);
JComboBox comboBox_1 = new JComboBox();
comboBox_1.setBounds(91, 50, 113, 25);
panel.add(comboBox_1);
JLabel lblLanguage = new JLabel("label3");
lblLanguage.setForeground(UIManager.getColor("Button.background"));
lblLanguage.setBounds(12, 114, 56, 16);
panel.add(lblLanguage);
JComboBox comboBox_2 = new JComboBox();
comboBox_2.setBounds(91, 110, 113, 25);
panel.add(comboBox_2);
JCheckBox chckbxIncludeExt = new JCheckBox("include");
chckbxIncludeExt.setForeground(UIManager.getColor("Button.background"));
chckbxIncludeExt.setBackground(UIManager.getColor("Button.darkShadow"));
chckbxIncludeExt.setBounds(12, 219, 113, 25);
panel.add(chckbxIncludeExt);
JButton btnSubmit = new JButton("Submit");
btnSubmit.setBounds(107, 264, 97, 25);
panel.add(btnSubmit);
JTextArea textArea = new JTextArea();
textArea.setBounds(240, 14, 219, 220);
panel.add(textArea);
}
}
Enable multi-file selection using JFileChooser#setMultiSelectionEnabled, then iterate through all files returned from getSelectedFiles, appending the output of getPath to your JTextArea
if (JFileChooser.APPROVE_OPTION == fc.showOpenDialog(list)) {
for (File file : fc.getSelectedFiles()) {
myTextArea.append(file.getPath() + System.getProperty("line.separator"));
}
}
Edit:
You should be getting a stacktrace like this
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at swing9.VFSTool$2.actionPerformed(VFSTool.java:81)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
This is telling you that something is not initialized, i.e. your JTextArea log
Not only has this not been initialized but hasnt been added to the frame. You probably want the text displayed in textArea instead. This is only available in the scope of the constructor so will need to declared as a class member variable.
private JTextArea textArea;
Related
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!
I created a Swing application. I'm using a JProgressBar to show the progres and I want the progress to change when some tasks execute inside a button handler(ActionListener.actionPerformed), but it ins't working. Here is the code:
package com.capgemini.skillparser.ui;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;
import com.capgemini.skillparser.domain.Employee;
import com.capgemini.skillparser.excel.impl.SkillsXlsxReader;
import com.capgemini.skillparser.excel.impl.SkillsXlsxWriter;
import com.capgemini.skillparser.text.impl.EmployeeNumbersTextReader;
public class TelaPrincipal extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TelaPrincipal frame = new TelaPrincipal();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public TelaPrincipal() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 427);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel label = new JLabel(
new ImageIcon(
new ImageIcon(getClass().getClassLoader().getResource("capgemini-logo.jpg"))
.getImage().getScaledInstance(300, 100, Image.SCALE_DEFAULT)
)
);
label.setBounds(10, 11, 414, 73);
contentPane.add(label);
textField = new JTextField();
textField.setBackground(Color.LIGHT_GRAY);
textField.setBounds(10, 113, 414, 20);
contentPane.add(textField);
textField.setColumns(10);
JButton btnSelecionarPlanilha = new JButton("Selecionar planilha");
btnSelecionarPlanilha.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
FileNameExtensionFilter filter = new FileNameExtensionFilter("*.xlsx", "xlsx");
j.setFileFilter(filter);
int r = j.showSaveDialog(null);
if (r == JFileChooser.APPROVE_OPTION) {
textField.setText(j.getSelectedFile().getAbsolutePath());
}
}
});
btnSelecionarPlanilha.setBounds(10, 144, 217, 23);
contentPane.add(btnSelecionarPlanilha);
textField_1 = new JTextField();
textField_1.setBackground(Color.LIGHT_GRAY);
textField_1.setBounds(10, 178, 414, 20);
contentPane.add(textField_1);
textField_1.setColumns(10);
JButton btnSelecionarArquivoTxtfiltro = new JButton("Selecionar arquivo txt (filtro)");
btnSelecionarArquivoTxtfiltro.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
FileNameExtensionFilter filter = new FileNameExtensionFilter("*.txt", "txt");
j.setFileFilter(filter);
int r = j.showSaveDialog(null);
if (r == JFileChooser.APPROVE_OPTION) {
textField_1.setText(j.getSelectedFile().getAbsolutePath());
}
}
});
btnSelecionarArquivoTxtfiltro.setBounds(10, 209, 217, 23);
contentPane.add(btnSelecionarArquivoTxtfiltro);
textField_2 = new JTextField();
textField_2.setBackground(Color.LIGHT_GRAY);
textField_2.setBounds(10, 243, 414, 20);
contentPane.add(textField_2);
textField_2.setColumns(10);
JButton btnSelecionarDestino = new JButton("Selecionar destino");
btnSelecionarDestino.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
j.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int r = j.showSaveDialog(null);
if (r == JFileChooser.APPROVE_OPTION) {
textField_2.setText(j.getSelectedFile().getAbsolutePath());
}
}
});
btnSelecionarDestino.setBounds(10, 274, 217, 23);
contentPane.add(btnSelecionarDestino);
JProgressBar progressBar = new JProgressBar();
progressBar.setBounds(10, 318, 414, 23);
progressBar.setValue(0);
progressBar.setStringPainted(true);
contentPane.add(progressBar);
JButton btnGerarPlanilhaAjustada = new JButton("Gerar Planilha Ajustada");
btnGerarPlanilhaAjustada.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//---------------PROBLEM HERE---------------------------------------
try {
progressBar.setIndeterminate(true);
progressBar.setValue(30);
//read a xlsx file
progressBar.setValue(50);
//write a xlsx file
progressBar.setValue(100);
progressBar.setIndeterminate(false);
//nothing above related to progressBar works properly, these statements only execute after the button handler code finishes
}catch(Exception ex) {
ex.printStackTrace();
}
}
});
btnGerarPlanilhaAjustada.setBounds(101, 354, 230, 23);
contentPane.add(btnGerarPlanilhaAjustada);
}
}
I tried many alternative codes, but nothing worked. Some places suggests multi-thread approaches but I don't know how to structure my code to work with multi-thread in a manner that works well. All my tries in this sense have failed.
Can someone help me please? Thank you
Reading and writing are "heavy" operations that might take time to finish. That's why you will have to do them in background, otherwise the GUI thread, a.k.a the Event Dispatch Thread will be busy hence events will not be able to take place (gui will freeze).
You have to create a SwingWorker. The whole idea is this:
Button gets clicked
SwingWorker starts
Worker does a part-step of a heavy operation in background
Worker publishes the progress bar value to the GUI thread
Repeat 3 & 4
Worker is done.
See my example in your code (comments inside the code):
public class TelaPrincipal extends JFrame {
private SwingWorker<Void, Integer> worker;
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JProgressBar progressBar;
/**
* Launch the application.
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
TelaPrincipal frame = new TelaPrincipal();
frame.setVisible(true);
});
}
/**
* Create the frame.
*/
public TelaPrincipal() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 427);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel label = new JLabel();
label.setBounds(10, 11, 414, 73);
contentPane.add(label);
textField = new JTextField();
textField.setBackground(Color.LIGHT_GRAY);
textField.setBounds(10, 113, 414, 20);
contentPane.add(textField);
textField.setColumns(10);
JButton btnSelecionarPlanilha = new JButton("Selecionar planilha");
btnSelecionarPlanilha.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
FileNameExtensionFilter filter = new FileNameExtensionFilter("*.xlsx", "xlsx");
j.setFileFilter(filter);
int r = j.showSaveDialog(null);
if (r == JFileChooser.APPROVE_OPTION) {
textField.setText(j.getSelectedFile().getAbsolutePath());
}
}
});
btnSelecionarPlanilha.setBounds(10, 144, 217, 23);
contentPane.add(btnSelecionarPlanilha);
textField_1 = new JTextField();
textField_1.setBackground(Color.LIGHT_GRAY);
textField_1.setBounds(10, 178, 414, 20);
contentPane.add(textField_1);
textField_1.setColumns(10);
JButton btnSelecionarArquivoTxtfiltro = new JButton("Selecionar arquivo txt (filtro)");
btnSelecionarArquivoTxtfiltro.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
FileNameExtensionFilter filter = new FileNameExtensionFilter("*.txt", "txt");
j.setFileFilter(filter);
int r = j.showSaveDialog(null);
if (r == JFileChooser.APPROVE_OPTION) {
textField_1.setText(j.getSelectedFile().getAbsolutePath());
}
}
});
btnSelecionarArquivoTxtfiltro.setBounds(10, 209, 217, 23);
contentPane.add(btnSelecionarArquivoTxtfiltro);
textField_2 = new JTextField();
textField_2.setBackground(Color.LIGHT_GRAY);
textField_2.setBounds(10, 243, 414, 20);
contentPane.add(textField_2);
textField_2.setColumns(10);
JButton btnSelecionarDestino = new JButton("Selecionar destino");
btnSelecionarDestino.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
j.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int r = j.showSaveDialog(null);
if (r == JFileChooser.APPROVE_OPTION) {
textField_2.setText(j.getSelectedFile().getAbsolutePath());
}
}
});
btnSelecionarDestino.setBounds(10, 274, 217, 23);
contentPane.add(btnSelecionarDestino);
progressBar = new JProgressBar();
progressBar.setBounds(10, 318, 414, 23);
progressBar.setValue(0);
progressBar.setStringPainted(true);
contentPane.add(progressBar);
JButton btnGerarPlanilhaAjustada = new JButton("Gerar Planilha Ajustada");
btnGerarPlanilhaAjustada.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (!worker.isDone())
worker.cancel(true); //destroy previous worker
initWorker();
worker.execute();
}
});
btnGerarPlanilhaAjustada.setBounds(101, 354, 230, 23);
contentPane.add(btnGerarPlanilhaAjustada);
initWorker();
}
private void initWorker() {
worker = new SwingWorker<Void, Integer>() {
#Override
protected void process(List<Integer> chunks) {
int value = chunks.get(0);
progressBar.setValue(value);
}
#Override
protected Void doInBackground() throws Exception {
publish(10); //progress bar value that will be sent to process() method
Thread.sleep(2000); //assume read file takes 2 seconds
publish(50); //progress bar value that will be sent to process() method
Thread.sleep(2000); //assume another bg operation takes 2 secs
publish(99);
return null;
}
};
}
}
i am developing an application for which i have created different application windows. Now i'm in a confusion on how i can link one to another using a button, that is when i click a button, it has to navigate to the other application window. I have tried it with frames from same file, but that doesnt satisfy my need.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.Font;
import javax.swing.SwingConstants;
import java.awt.Color;
import java.awt.SystemColor;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.UIManager;
import java.awt.event.*;
public class Start {
private JFrame frame;
private JTextField txtLogInTo;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Start window = new Start();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private void initialize() {
frame = new JFrame();
frame.getContentPane().setBackground(SystemColor.inactiveCaption);
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewButton = new JButton("USER");
btnNewButton.setBackground(SystemColor.activeCaption);
btnNewButton.setBounds(152, 81, 132, 23);
frame.getContentPane().add(btnNewButton);
JButton btnNewButton_1 = new JButton("BUS ADMIN");
btnNewButton_1.setBackground(SystemColor.activeCaption);
btnNewButton_1.setBounds(152, 131, 132, 23);
frame.getContentPane().add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("SYSTEM ADMIN");
btnNewButton_2.setBackground(SystemColor.activeCaption);
btnNewButton_2.setBounds(152, 179, 132, 23);
frame.getContentPane().add(btnNewButton_2);
txtLogInTo = new JTextField();
txtLogInTo.setBounds(95, 27, 252, 36);
txtLogInTo.setBackground(SystemColor.inactiveCaption);
txtLogInTo.setHorizontalAlignment(SwingConstants.CENTER);
txtLogInTo.setFont(new Font("Tekton Pro Cond", Font.BOLD | Font.ITALIC, 20));
txtLogInTo.setText("LOG IN TO ENTER THE SYSTEM");
frame.getContentPane().add(txtLogInTo);
txtLogInTo.setColumns(10);
class handler implements ActionListener
{
//must implement method
//This is triggered whenever the user clicks the login button
public void actionPerformed(ActionEvent ae)
{
if(btnNewButton.isEnabled())
{User u;
}
}//if
}//method
}//inner class
}
and this above program is where i have to navigate when i click a button from the below program
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import java.awt.Font;
import javax.swing.JTextArea;
import javax.swing.JSplitPane;
import javax.swing.JScrollPane;
import javax.swing.JInternalFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import java.awt.SystemColor;
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JPopupMenu;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class User {
private JFrame frame,frame2;
private JTextField txtWelcomeUser;
private JTextField txtEnterYourDetails;
private JTextField txtName;
private JTextField txtAge;
private JTextField txtPhoneNo;
private JTextField txtMailId;
private JTextField txtStart;
private JTextField txtDestination;
private JTextArea textArea_4;
private JTextArea textArea_5;
private JTextField txtEn;
private ActionListener action;
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
User window = new User();
window.frame.setVisible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
public User() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(0, 0, 750, 550);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
txtWelcomeUser = new JTextField();
txtWelcomeUser.setBackground(SystemColor.inactiveCaption);
txtWelcomeUser.setFont(new Font("Tahoma", Font.PLAIN, 26));
txtWelcomeUser.setText("Welcome user");
txtWelcomeUser.setBounds(176, 11, 173, 52);
frame.getContentPane().add(txtWelcomeUser);
txtWelcomeUser.setColumns(10);
txtEnterYourDetails = new JTextField();
txtEnterYourDetails.setBackground(SystemColor.activeCaption);
txtEnterYourDetails.setFont(new Font("Tahoma", Font.PLAIN, 20));
txtEnterYourDetails.setText("Enter your details");
txtEnterYourDetails.setBounds(176, 74, 173, 36);
frame.getContentPane().add(txtEnterYourDetails);
txtEnterYourDetails.setColumns(10);
txtName = new JTextField();
txtName.setBackground(SystemColor.inactiveCaption);
txtName.setText("Name");
txtName.setBounds(93, 136, 86, 20);
frame.getContentPane().add(txtName);
txtName.setColumns(10);
txtAge = new JTextField();
txtAge.setBackground(SystemColor.inactiveCaption);
txtAge.setText("Age");
txtAge.setBounds(93, 167, 86, 20);
frame.getContentPane().add(txtAge);
txtAge.setColumns(10);
txtPhoneNo = new JTextField();
txtPhoneNo.setBackground(SystemColor.inactiveCaption);
txtPhoneNo.setText("Phone No");
txtPhoneNo.setBounds(93, 198, 86, 20);
frame.getContentPane().add(txtPhoneNo);
txtPhoneNo.setColumns(10);
txtMailId = new JTextField();
txtMailId.setBackground(SystemColor.inactiveCaption);
txtMailId.setText("Mail id");
txtMailId.setBounds(93, 229, 86, 20);
frame.getContentPane().add(txtMailId);
txtMailId.setColumns(10);
JTextArea textArea = new JTextArea();
textArea.setBounds(236, 134, 124, 20);
frame.getContentPane().add(textArea);
JTextArea textArea_1 = new JTextArea();
textArea_1.setBounds(236, 165, 124, 20);
frame.getContentPane().add(textArea_1);
JTextArea textArea_2 = new JTextArea();
textArea_2.setBounds(236, 196, 124, 20);
frame.getContentPane().add(textArea_2);
JTextArea textArea_3 = new JTextArea();
textArea_3.setBounds(236, 227, 124, 20);
frame.getContentPane().add(textArea_3);
txtStart = new JTextField();
txtStart.setBackground(SystemColor.inactiveCaption);
txtStart.setText("Start ");
txtStart.setBounds(93, 260, 86, 20);
frame.getContentPane().add(txtStart);
txtStart.setColumns(10);
txtDestination = new JTextField();
txtDestination.setBackground(SystemColor.inactiveCaption);
txtDestination.setText("Destination");
txtDestination.setBounds(93, 291, 86, 20);
frame.getContentPane().add(txtDestination);
txtDestination.setColumns(10);
textArea_4 = new JTextArea();
textArea_4.setBounds(236, 258, 124, 20);
frame.getContentPane().add(textArea_4);
textArea_5 = new JTextArea();
textArea_5.setBounds(236, 289, 124, 20);
frame.getContentPane().add(textArea_5);
JPanel panel = new JPanel();
panel.setForeground(new Color(0, 0, 0));
panel.setBackground(SystemColor.inactiveCaption);
panel.setBounds(433, 213, 124, 115);
frame.getContentPane().add(panel);
txtEn = new JTextField();
txtEn.setBackground(SystemColor.inactiveCaption);
txtEn.setText("Enter Bus No");
txtEn.setBounds(93, 322, 86, 20);
frame.getContentPane().add(txtEn);
txtEn.setColumns(10);
JTextArea textArea_6 = new JTextArea();
textArea_6.setBounds(236, 320, 124, 20);
frame.getContentPane().add(textArea_6);
JButton btnBookTicket = new JButton("Book Ticket");
btnBookTicket.setBackground(SystemColor.activeCaption);
btnBookTicket.setBounds(176, 376, 116, 23);
frame.getContentPane().add(btnBookTicket);
JPopupMenu popupMenu_1 = new JPopupMenu();
popupMenu_1.setBounds(327, 376, 200, 50);
frame.getContentPane().add(popupMenu_1);
if(!textArea.isEnabled()||!textArea_2.isEnabled()||!textArea_3.isEnabled()||!textArea_3.isEnabled()||!textArea_4.isEnabled()||!textArea_5.isEnabled()||!textArea_6.isEnabled())
{
JOptionPane.showMessageDialog(null, "You have not entered a few details","UnSuccessful",
JOptionPane.INFORMATION_MESSAGE);
}
if(btnBookTicket.isEnabled())
{
btnBookTicket.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "You have booked successfully","Success",
JOptionPane.INFORMATION_MESSAGE);
JButton button = (JButton) e.getSource();
if (button == btnBookTicket)
{
frame2 = new JFrame("FRAME 2");
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame2.setLocationByPlatform(true);
JPanel contentPane2 = new JPanel();
contentPane2.setBackground(Color.DARK_GRAY);
JButton btnBookTicket1 = new JButton("Cancel Ticket");
btnBookTicket1.setBackground(SystemColor.activeCaption);
btnBookTicket1.setBounds(0, 30, 35, 23);
contentPane2.add(btnBookTicket1);
frame2.getContentPane().add(contentPane2);
frame2.setSize(600, 600);
frame2.setVisible(true);
frame.setVisible(false);
}
btnBookTicket.addActionListener(action);
}
});
}
}
}
I was trying to replace the use of JOptionPane by a new custom dialog here is what I did:
package pk;
import java.util.Enumeration;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import java.awt.Font;
import javax.swing.JTextArea;
import java.awt.SystemColor;
import javax.swing.JPanel;
import java.awt.Color;
import javax.swing.border.LineBorder;
public class SIMessage extends JDialog implements ActionListener{
private static final long serialVersionUID = 1L;
public JButton oui=new JButton("Oui"),btnClose=new JButton(new ImageIcon("images\\logo\\delete.gif")),
non=new JButton("Non"),annuler=new JButton("Annuler"),ok=new JButton("OK");
public JLabel lblImgErr=new JLabel(new ImageIcon("images\\logo\\msgErreur.png")),
lblImgConf=new JLabel(new ImageIcon("images\\logo\\msgQuestion.png")),
lblImgWarning=new JLabel(new ImageIcon("images\\logo\\msgWarning.png")),
lblImgInfo=new JLabel(new ImageIcon("images\\logo\\msgInformation.png")),
lblImgQuestion=new JLabel(new ImageIcon("images\\logo\\msgQuestion.png")),
lblImgIconApp=new JLabel(new ImageIcon("images\\logo\\clntIco.ico"));
public JLabel title=new JLabel(),message=new JLabel();
public enum TypeMessage{
ERROR_MESSAGE,
CONFIRMATION_MESSAGE,
WARNING_MESSAGE,
INFORMATION_MESSAGE,
VALIDATION_MESSAGE
}
public SIMessage(JFrame parent,String title,TypeMessage type,String message) {
super(parent,true);
setUndecorated(true);
getContentPane().setLayout(new GridLayout(1, 1));
JPanel mainDgPanel = new JPanel();
mainDgPanel.setBorder(new LineBorder(new Color(255, 255, 255), 3, true));
mainDgPanel.setBounds(0, 0, 444, 156);
getContentPane().add(mainDgPanel);
mainDgPanel.setLayout(null);
mainDgPanel.setBackground(Color.decode(EcranPrincipal.blueThemeCP));
JTextArea txtrTextarea = new JTextArea(message);
txtrTextarea.setRows(2);
txtrTextarea.setBounds(123, 62, 340, 80);
txtrTextarea.setFont(new Font("Iskoola Pota", Font.PLAIN, 18));
txtrTextarea.setEditable(false);
txtrTextarea.setFocusable(false);
txtrTextarea.setOpaque(false);
txtrTextarea.setBorder(null);
txtrTextarea.setWrapStyleWord(true);
txtrTextarea.setLineWrap(true);
txtrTextarea.setForeground(Color.decode(EcranPrincipal.blueThemeBT));
mainDgPanel.add(txtrTextarea);
JPanel panelButtons = new JPanel();
panelButtons.setBounds(47, 115, 344, 30);
mainDgPanel.add(panelButtons);
switch(type)
{
case ERROR_MESSAGE:
{
JLabel lblNewLabel =lblImgErr;
lblNewLabel.setBounds(10, 69, 79, 14);
mainDgPanel.add(lblNewLabel);
JButton btnOk = ok;
panelButtons.add(btnOk);
break;
}
case CONFIRMATION_MESSAGE:
{
JLabel lblNewLabel =lblImgConf;
lblNewLabel.setBounds(10, 69, 79, 14);
mainDgPanel.add(lblNewLabel);
JButton btnOui = oui;
panelButtons.add(btnOui);
break;
}
case WARNING_MESSAGE:
{
JLabel lblNewLabel =lblImgWarning;
lblNewLabel.setBounds(10, 69, 79, 14);
mainDgPanel.add(lblNewLabel);
JButton btnOk = ok;
panelButtons.add(btnOk);
break;
}
case INFORMATION_MESSAGE:
{
JLabel lblNewLabel =lblImgInfo;
lblNewLabel.setBounds(10, 69, 79, 14);
mainDgPanel.add(lblNewLabel);
JButton btnOk = ok;
panelButtons.add(btnOk);
break;
}
case VALIDATION_MESSAGE:
{
JLabel lblNewLabel =lblImgConf;
lblNewLabel.setBounds(10, 69, 79, 14);
mainDgPanel.add(lblNewLabel);
JButton btnOui = oui;
panelButtons.add(btnOui);
JButton btnNon = non;
panelButtons.add(btnNon);
JButton btnAnnuler = annuler;
panelButtons.add(btnAnnuler);
break;
}
default:
}
ok.addActionListener(this);
oui.addActionListener(this);
JPanel panel = new JPanel();
panel.setBounds(0, 0, 444, 27);
mainDgPanel.add(panel);
panel.setBackground(Color.WHITE);
panel.setLayout(null);
JButton btnCloseDf = btnClose;
btnCloseDf.setBounds(411, 0, 39, 23);
panel.add(btnCloseDf);
JLabel lblIconApp =lblImgIconApp;
lblIconApp.setBounds(10, 4, 77, 14);
panel.add(lblIconApp);
JLabel lblTitle = new JLabel(title);
lblTitle.setBounds(190, 4, 46, 14);
panel.add(lblTitle);
this.pack();
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Object source=e.getSource();
if(source==oui||source==ok)
{
this.dispose();
}
}
Then I call:
SIMessage sm=new SIMessage(this, "Attention", SIMessage.TypeMessage.WARNING_MESSAGE,"You need to change ...");
callMethode2();
The problem is that it executes the call to Methode2 before showing any dialog while it is supposed to force the user to respond before continuing.
I see an empty window side by side with the window generated by callMethod2!, so what is wrong?
You should set the modality for Dialog.
A modal window is a graphical control element subordinate to an application's main window. It creates a mode that disables the main window but keeps it visible with the modal window as a child window in front of it. Users must interact with the modal window before they can return to the parent application.
So, Set the modal flag of the dialog when initializing it.
setModal(True)
edit:
I don't know what you exactly changed in your code, but the code below works fine for me:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author Emad
*/
import java.awt.BorderLayout;
import java.util.Enumeration;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import java.awt.Font;
import javax.swing.JTextArea;
import java.awt.SystemColor;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import javafx.event.ActionEvent;
import javax.swing.border.LineBorder;
public class SIMessage extends JDialog implements ActionListener {
private static final long serialVersionUID = 1L;
public JButton oui = new JButton("Oui"), btnClose = new JButton(new ImageIcon("images\\logo\\delete.gif")),
non = new JButton("Non"), annuler = new JButton("Annuler"), ok = new JButton("OK");
public JLabel lblImgErr = new JLabel(new ImageIcon("images\\logo\\msgErreur.png")),
lblImgConf = new JLabel(new ImageIcon("images\\logo\\msgQuestion.png")),
lblImgWarning = new JLabel(new ImageIcon("images\\logo\\msgWarning.png")),
lblImgInfo = new JLabel(new ImageIcon("images\\logo\\msgInformation.png")),
lblImgQuestion = new JLabel(new ImageIcon("images\\logo\\msgQuestion.png")),
lblImgIconApp = new JLabel(new ImageIcon("images\\logo\\clntIco.ico"));
public JLabel title = new JLabel(), message = new JLabel();
#Override
public void actionPerformed(java.awt.event.ActionEvent e) {
// TODO Auto-generated method stub
Object source = e.getSource();
if (source == oui || source == ok) {
this.dispose();
}
}
public enum TypeMessage {
ERROR_MESSAGE,
CONFIRMATION_MESSAGE,
WARNING_MESSAGE,
INFORMATION_MESSAGE,
VALIDATION_MESSAGE
}
public SIMessage(JFrame parent, String title, TypeMessage type, String message) {
super(parent, true);
setUndecorated(true);
getContentPane().setLayout(new GridLayout(1, 1));
JPanel mainDgPanel = new JPanel();
mainDgPanel.setBorder(new LineBorder(new Color(255, 255, 255), 3, true));
mainDgPanel.setBounds(0, 0, 444, 156);
getContentPane().add(mainDgPanel);
// mainDgPanel.setBackground(Color.decode(EcranPrincipal.blueThemeCP));
JTextArea txtrTextarea = new JTextArea(message);
txtrTextarea.setRows(2);
txtrTextarea.setBounds(123, 62, 340, 80);
txtrTextarea.setFont(new Font("Iskoola Pota", Font.PLAIN, 18));
txtrTextarea.setEditable(false);
txtrTextarea.setFocusable(false);
txtrTextarea.setOpaque(false);
txtrTextarea.setBorder(null);
txtrTextarea.setWrapStyleWord(true);
txtrTextarea.setLineWrap(true);
// txtrTextarea.setForeground(Color.decode(EcranPrincipal.blueThemeBT));
mainDgPanel.add(txtrTextarea);
JPanel panelButtons = new JPanel();
panelButtons.setBounds(47, 115, 344, 30);
mainDgPanel.add(panelButtons);
switch (type) {
case ERROR_MESSAGE: {
JLabel lblNewLabel = lblImgErr;
lblNewLabel.setBounds(10, 69, 79, 14);
mainDgPanel.add(lblNewLabel);
JButton btnOk = ok;
panelButtons.add(btnOk);
break;
}
case CONFIRMATION_MESSAGE: {
JLabel lblNewLabel = lblImgConf;
lblNewLabel.setBounds(10, 69, 79, 14);
mainDgPanel.add(lblNewLabel);
JButton btnOui = oui;
panelButtons.add(btnOui);
break;
}
case WARNING_MESSAGE: {
JLabel lblNewLabel = lblImgWarning;
lblNewLabel.setBounds(10, 69, 79, 14);
mainDgPanel.add(lblNewLabel);
JButton btnOk = ok;
panelButtons.add(btnOk);
break;
}
case INFORMATION_MESSAGE: {
JLabel lblNewLabel = lblImgInfo;
lblNewLabel.setBounds(10, 69, 79, 14);
mainDgPanel.add(lblNewLabel);
JButton btnOk = ok;
panelButtons.add(btnOk);
break;
}
case VALIDATION_MESSAGE: {
JLabel lblNewLabel = lblImgConf;
lblNewLabel.setBounds(10, 69, 79, 14);
mainDgPanel.add(lblNewLabel);
JButton btnOui = oui;
panelButtons.add(btnOui);
JButton btnNon = non;
panelButtons.add(btnNon);
JButton btnAnnuler = annuler;
panelButtons.add(btnAnnuler);
break;
}
default:
}
ok.addActionListener(this);
oui.addActionListener(this);
JPanel panel = new JPanel();
panel.setBounds(0, 0, 444, 27);
mainDgPanel.add(panel);
panel.setBackground(Color.WHITE);
panel.setLayout(null);
JButton btnCloseDf = btnClose;
btnCloseDf.setBounds(411, 0, 39, 23);
panel.add(btnCloseDf);
JLabel lblIconApp = lblImgIconApp;
lblIconApp.setBounds(10, 4, 77, 14);
panel.add(lblIconApp);
JLabel lblTitle = new JLabel(title);
lblTitle.setBounds(190, 4, 46, 14);
panel.add(lblTitle);
this.pack();
this.setVisible(true);
}
public static void main(String[] args)
{
SIMessage sm=new SIMessage(null, "Attention", SIMessage.TypeMessage.WARNING_MESSAGE,"You need to change ...");
System.out.println("hello");
}
}
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.