Is a text file in Java a GUI - java

Is it right to think that when you create a text file in Java, you are essentially creating a text file like the one that appears with programs like notepad?
I have a JComboBox menu with various selections. I also created a text file and had it so that the user selection will be written in the text file. So the question is, how can I have this text file that I've created to appear? (as a GUI or any other way...)
My Code:
static JFrame frame;
FileWriter f;
BufferedWriter bw;
int myAge;
String myStringAge;
for (int i = 1; i <= 100; ++i) {
ageList.add(i);
}
DefaultComboBoxModel modelAge = new DefaultComboBoxModel();
for (Integer i : ageList) {
modelAge.addElement(i);
}
JComboBox ageEntries = new JComboBox();
ageEntries.setModel(modelAge);
//Add ItemListener
ageEntries.addItemListener(new ageListener());
class ageListener implements ItemListener {
public void itemStateChanged(ItemEvent event){
myAge = (Integer) event.getItem();
myStringAge = Integer.toString(myAge);
try {
bw.write(myStringAge);
bw.close();
} catch (Exception e){
}
}

A text file is not a GUI. Use JTextArea to display text. Have a look at http://docs.oracle.com/javase/tutorial/uiswing/components/textarea.html

You can do so using JEditorPane. You might want to create a new JFrame for it. Don't forget to setContentType() to "text/plain". Then you can just create a FileReader for your file and pass it to the editor pane throught the read() method.

Start with Basic I/O. That should answer your question (and the next 9).

Related

Java GUI import textfile data to a JTable

I am writing a program, for my assignment, which should get some user input data from GUI(jtextfield) to a textfile and then retrive those data from the textfile to another GUI(JTable).
I have some basic knowledge about the file handling and JAVA swing, and I get some problems now.
First of all, please let me tell what I have done now (code below).
appending the data
public void actionPerformed(ActionEvent ae) {
//once clicked the button write the file
Object[] cols = new Object[]{
model.getText(),
make.getText(),
year.getText()
};
try {
FileOutputStream fstream = new FileOutputStream("words.txt", true);
ObjectOutputStream outputFile = new ObjectOutputStream(fstream);
outputFile.writeObject(cols);
//bw.close();
outputFile.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
Reading the data from the word file to Jtable
public class read extends JFrame {
JTable table = new JTable();
JScrollPane pane;
Object[] cols = null;
public read() throws ClassNotFoundException, IOException {
cols = new String[]{"c1", "c2", "c3",};
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.setColumnIdentifiers(cols);
File f = new File("words.txt");
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
Object[] data = (Object[]) ois.readObject();
model.addRow(data);
pane = new JScrollPane(table);
pane.setBounds(100, 150, 300, 300);
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setLocationRelativeTo(null);
setSize(500, 500);
}
public static void main(String[] args) throws ClassNotFoundException, IOException {
new read();
}
}
It's working now but it only retrive one piece of data from the file, I want it to show all the data added to the file.
My questions are:
My words file looks like different:
and I am not sure if it just me or it just what it should be? Because I am expecting that it should be exact what I write, so even the addrow(object) method is not working I can add row using getline.
(Important) Because I write multible different data to the words file(and its shown in the image above), but it only shows one.
I assume that is because I should add an array of objects to the table in read.java instead of just addrow(object) but i dont know how, I mean I dont know how to let the array recognise that there are a lot of objects in the words file. also, is it okay to write the data as object to the file and retrive them in the read.java, is it a proper way?
Can someone tell me how, thanks fore your help.
Please don't hesitate to ask if I didn't state it properly.

How to display the next text lines once user presses the next button?

I am trying to create a program which allows the user to choose a text file
from their directory. That then gets displayed in a JTextArea within the Frame created using Swing.
I've created a button with a action command that's supposed to allow the user once pressed to get the next text lines from the file, displayed within the text area until it reaches the end of file.
To do that I used the sub-string command to go through the String variable and display it .
But it seems to not to do that instead it just displays all the text found within the file.
Below you will find the code that allows the program to open the file and display as well
as the buttons created to aid in navigating through the text.
package reader;
public class Viewer extends JFrame{
private static final long serialVersionUID = 1L;
private static JFrame Frame;
private JPanel Cpanel;
JScrollPane scrollPane;
String book = "";
int currentChar = 10;
static JTextArea textArea;
JFileChooser fileChooser;
File f;
public static void DocViewer() {
new Viewer("new document");
}
public Viewer(String s) {
Frame = new JFrame("Reader");
textArea = new JTextArea(20,60);
textArea.setFont(new Font("Calibri", Font.PLAIN, 12));
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);
textArea.setEditable(false);
scrollPane = new JScrollPane(textArea);
f = new File("C://Program Files//Java//jdk1.6.0//bin//");
fileChooser = new JFileChooser(f);
Frame.getContentPane().setBackground(Color.red);
Frame.setLayout(new GridLayout(3, 1));
Cpanel = new JPanel();
Cpanel.setLayout(new FlowLayout());
Cpanel.setBackground(Color.RED);
JButton StButton = new JButton("open");
JButton QButton = new JButton("back");
JButton TestButton = new JButton("next");
TestButton.setHorizontalTextPosition(SwingConstants.LEFT);
StButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String book = "";
// int currentChar=10;
int returnVal = fileChooser.showOpenDialog(Viewer.this);
try {
File file = fileChooser.getSelectedFile();
FileInputStream fin = new FileInputStream(file);
BufferedReader d = new BufferedReader(
new InputStreamReader(fin, "UTF-8"));
book = "";
if (returnVal == JFileChooser.APPROVE_OPTION) {
while (book != null) {
book = d.readLine();
textArea.append(book + "\n");
System.out.println(book);
}
}
System.out.println("returnVal = " + returnVal
+ " and ba.fileChooser.APPROVE_OPTION = "
+ JFileChooser.APPROVE_OPTION);
fin.close();
} catch (Exception ex) {
}
}
});
QButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// System.exit(0);
Viewer.EXIT_ON_CLOSE();
Loader.main(null);
}
});
TestButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String page = "";
for (int l = 1; l >= 10; l = l + 2) {
page += book.substring(l, l + 49);
page += "\n";
currentChar += 50;
}
}
});
Cpanel.add(StButton);
Cpanel.add(QButton);
Cpanel.add(TestButton);
Frame.add(Cpanel, BorderLayout.NORTH);
Frame.add(scrollPane, BorderLayout.CENTER);
Frame.setSize(300,300);
Frame.setVisible(true);
}
}
Your code is only doing what you tell it to do.
Your button's ActionListener has a while loop that loops through the entire file writing all the contents to the JTextArea. So I'm not sure why this behavior surprises you.
If it were me, I'd read the entire file into an ArrayList<String> with each new line being added one at a time. I'd do this once, perhaps in a class constructor if you know what file to read in advance, perhaps in response to getting a File via a JFileChooser if you don't.
Then in my button grab the next line in this List, using an int index variable to store the index number, and append this line to my JTextArea.
Maybe even better than using a JTextArea would be to use a JList.
Done.
Edit
You've asked more questions, so I'll try to subdivide the steps a little:
Create an ArrayList<String> as an instance field (non-static class variable)
Open your file put it into a Scanner object
Using a while loop, loop while the Scanner has a next line
Inside the loop, use the Scanner to grab the next line and put it into the List.
Also give the class an int index field.
On button push, get the String in the ArrayList corresponding to the index, and then increment the index
Publish that String in your JTextField using its append method.
If still stuck, break down your steps even further and try to find specifically where you're stuck. Google for a solution, and if still stuck, come here with your specific question and code.
Check the java info resources. In particular look at the Beginner's resources for links.
As an aside, you will want to learn and use Java naming conventions. Variable names should all begin with a lower letter while class names with an upper case letter.

How do i set text in rows of a JTable? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I'm trying to make a program in java JFrame with a table.
I want to save my text from the rows.
I put the text in a text file and that is working.
But i want to get my text from my text file into my table.
I have tried a lot of things but nothing is working.
can somebody help pls?
'Hypothetically' if you stored the text in your file line by line, for example like this:
tester.txt:
Star Wars
Star Trek
The Lord of The Rings
Then you could read it in line by line and when you have read enough lines add a row to the table. In order to add a row to an existing table I believe you do need to use the Model, or if creating from fresh prepare the data beforehand and then create. Below is a rough example using the above txt file:
public class SO {
public static void main(String[] args) {
//Desktop
Path path = Paths.get(System.getProperty("user.home"), "Desktop", "tester.txt");
//Reader
try (BufferedReader reader = new BufferedReader(new FileReader(path.toFile()))){
Vector<String> row = new Vector<String>();
//Add lines of file
int numOfCellsInRow = 3; //Num of cells we want
int count = 0;
while (count < numOfCellsInRow){
row.addElement(reader.readLine());
count++;
}
//Column names
Vector<String> columnNames = new Vector<String>();
columnNames.addElement("Column One");
columnNames.addElement("Column Two");
columnNames.addElement("Column Three");
Vector<Vector<String>> rowData = new Vector<Vector<String>>();
rowData.addElement(row);
//Make table
JTable table = new JTable(rowData, columnNames);
//How you could add another row by drawing more text from the file,
//here I have just used Strings
//Source: http://stackoverflow.com/questions/3549206/how-to-add-row-in-jtable
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.addRow(new Object[]{"Darth Vader", "Khan", "Sauron"});
//Make JFrame and add table to it, then display JFrame
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Two things to note, firstly I have used Vectors, but these are discouraged due I believe to speed issues so you may want to look into varying on these. The second and main issue is the text in the file. Only by knowing how you intend to store the text can we know how to read it back successfully into the table. Hopefully though this example can point you in the right direction.
EDIT
Regarding your re-posted code, firstly I made this final:
final Path path = Paths.get(System.getProperty("user.home"), "Desktop", "File.txt");
Then altered your listener method to take the text input based of the file you make by clicking the save button:
btnGetFile.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//This prevents exception
if(!Files.exists(path)){//If no file
JOptionPane.showMessageDialog(null, "File does not exist!");//MSg
return;//End method
}
/*changed this bit so that it reads the data and
* should then add the rows
*/
try (BufferedReader reader = new BufferedReader(new FileReader(path.toFile()))){
String line;
while((line = reader.readLine()) != null){//Chek for data, reafLine gets first line
Vector<String> row = new Vector<String>();//New Row
row.addElement(line);//Add first line
int numOfCellsInRow = 3; //Num of cells we want
int count = 0;
//We only want 2 because we got the first element at loop start
while (count < (numOfCellsInRow - 1)){
row.addElement(reader.readLine());
count++;
}
model.addRow(row);//Add rows from file
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
Added comments to try and explain what is going on.
It worked for my by adding the rows from the file to the JTable. Hopefully it works for you now also!

Getting JCheckBox selected box value

I want to ask is there a way to get information from JCheckBox without actionListener. In my code I scan a file of strings and each line has data which, if selected, should be added to an array in my program. Problem is that i will never know how many JCheckBoxes I will have, it depends from file.
So, my question is how to put selected strings to an array (or list) with a press of a button (ok) so i could do something else with them (in my case i need to get data from file or from hand input and put it in a red-black tree, so I will need to push selected strings to my putDataInTheTree method).
EDIT: Also, is it possible not to show those JCheckBoxes that already has been added to the program? I.E. if i choose fluids, next time I call input method fluids wont show in my panel?
Thanks in advance!
How it looks:
My code is so far:
public void input() {
try {
mainWindow.setEnabled(false);
fromFile = new JFrame("Input from file");
fromFile.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
fromFile.setLayout(new BorderLayout());
fromFile.setSize(300,200);
panelFromFile = new JPanel();
panelFromFile.setLayout(new java.awt.GridLayout(0,1));
JScrollPane scrollPane2 = new JScrollPane(panelFromFile);
scrollPane2.setMaximumSize(new Dimension(300, 180));
FileReader File = new FileReader(data);
BufferedReader Buffer = new BufferedReader(File);
while ((info = Buffer.readLine()) != null) {
if (info != null) {
JCheckBox check = new JCheckBox(info);
panelFromFile.add(check);
}
}
ok = new JButton("ok");
ok.addActionListener(this);
fromFile.add(scrollPane2, BorderLayout.CENTER);
fromFile.add(ok, BorderLayout.SOUTH);
fromFile.setLocationRelativeTo(null);
fromFile.setResizable(false);
fromFile.setVisible(true);
}
catch(Exception e) {
text.append("Error in INPUT method");
text.append(System.getProperty("line.separator"));
}
}
Add your checkboxes to a collection, and when the button is pressed, iterate through the checkboxes and get the text associated with each checked checkbox:
private List<JCheckBox> checkBoxes = new ArrayList<JCheckBox>();
...
while ((info = Buffer.readLine()) != null) {
if (info != null) {
JCheckBox check = new JCheckBox(info);
panelFromFile.add(check);
this.checkBoxes.add(check);
}
}
...
public void actionPerformed(ActionEvent e) {
List<String> infos = new ArrayList<String>();
for (JCheckBox checkBox : checkBoxes) {
if (checkBox.isSelected() {
infos.add(checkBox.getText());
}
}
// TODO do something with infos
}
If you store the checkboxes (e.g. in a List) you can loop over them and query their selected state when the OK button is pressed.
To obtain the String from the checkbox, you could opt to use the putClientProperty and getClientProperty methods, as explained in the class javadoc of JComponent

Can a user-chosen image be inserted directly into a JEditorPane?

What I am trying to do is open up a JFilechooser that filters jpeg,gif and png images, then gets the user's selection and inserts it into the JEditorPane. Can this be done? or am i attempting something impossible? Here is a sample of my program.(insert is a JMenuItem and mainText is a JEditorPane)
insert.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JFileChooser imageChooser = new JFileChooser();
imageChooser.setFileFilter(new FileNameExtensionFilter("Image Format","jpg","jpeg","gif","png"));
int choice = imageChooser.showOpenDialog(mainText);
if (choice == JFileChooser.APPROVE_OPTION) {
mainText.add(imageChooser.getSelectedFile());
}
}
});
What i tried to do is use the add method, i know it's wrong but just to give you an idea of what i'm trying to do.
Before you complain, i'm sorry about the code formatting, i don't really know all the conventions of what is considered good or bad style.
Thank you very much.
This is the part of the code i use to save the html file.
else if (e.getSource() == save) {
JFileChooser saver = new JFileChooser();
saver.setFileFilter(new FileNameExtensionFilter(".html (webpage format)" , "html"));
int option = saver.showSaveDialog(this);
if (option == JFileChooser.APPROVE_OPTION) {
try {
BufferedWriter out = new BufferedWriter(new FileWriter(saver.getSelectedFile().getPath()));
out.write(mainText.getText());
out.close();
} catch (Exception exception) {
System.out.println(exception.getMessage());
}
}
}
Its easier to just use a JTextPane. Then you can use insertIcon(...) anywhere in the text.
Edit:
I have never had much luck trying to manipulate HTML but I've used code like the following before:
HTMLEditorKit editorKit = (HTMLEditorKit)textPane.getEditorKit();
text = "hyperlink";
editorKit.insertHTML(doc, textPane.getCaretPosition(), text, 0, 0, HTML.Tag.A);
So presumably the code would be similiar for the IMG tag.
This should do it:
mainText.setContentType("text/html");
String image = String.format("<img src=\"%s\">", imageChooser.getSelectedFile());
mainText.setText(image);

Categories