using method-declared variable in mutators? - java

Confused on the logic of getting a variable out of a method in a class and using it in a mutator.
Edit: here is my code dump
My Code:
package tests;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.filechooser.FileNameExtensionFilter;
public class LoadingBox extends JPanel {
String[] inFiles = new String[0];
public void loadIt(){
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("TXT FILES", "txt");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(getParent());
if(returnVal == JFileChooser.APPROVE_OPTION) {
File file = chooser.getCurrentDirectory();
String path = file.getPath();
String filename = chooser.getSelectedFile().getName();
String fullpath = path + "/" + filename;
}
}
public String[] getFiles() {
return inFiles;
}
public void setFiles(String[] inFiles) {
this.inFiles = inFiles;
}
}
Heres where it's going
package tests;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class FileScan {
ArrayList<String> stringArray = new ArrayList<String>();
ArrayList<Integer> numArray = new ArrayList<Integer>();
LoadingBox LoadFile = new LoadingBox();
String[] files = {LoadFile.getFiles()[0]};
//ITS GOING RIGHT HERE^^^^^^^^^^^^^^^
public void scan(String[] args) throws IOException {
Scanner input = null;
new FileScan();
try {
input = new Scanner(new File(files[0]));
//add strings and integers from file to different arrays
while (input.hasNext()) {
String token = input.nextLine();
try{
int o = Integer.parseInt(token);
numArray.add(o);
}
catch(NumberFormatException nfe){
stringArray.add(token);
}
}
}
finally {
if (input != null) {
input.close();
}
}
}
//Some more getters and setters down here
Stack overflow is making me type more so I'm going to ramble out some words down here so that I can post.

I don't know what the error you're getting is, so I'm just going to rewrite your code and hope it solves your problem.
package tests;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.filechooser.FileNameExtensionFilter;
public class LoadingBox extends JPanel {
private String inFiles;
public void loadIt(){
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("TXT FILES", "txt");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(getParent());
if(returnVal == JFileChooser.APPROVE_OPTION) {
File file = chooser.getCurrentDirectory();
String path = file.getPath();
String filename = chooser.getSelectedFile().getName();
String fullpath = path + "/" + filename;
this.setFiles(fullpath);
}
}
public String getFiles() {
return inFiles;
}
public void setFiles(String inFiles) {
this.inFiles = inFiles;
}
}
package tests;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class FileScan {
private ArrayList<String> stringArray;
private ArrayList<Integer> numArray;
private LoadingBox loadFile;
private String files;
public FileScan(){
stringArray = new ArrayList<String>();
numArray = new ArrayList<Integer>();
loadFile = new LoadingBox();
loadFile.loadIt();
files = LoadFile.getFiles();
}
public void scan(String[] args) throws IOException {
Scanner input = null;
new FileScan();
try {
input = new Scanner(new File(files));
//add strings and integers from file to different arrays
while (input.hasNext()) {
String token = input.nextLine();
try{
int o = Integer.parseInt(token);
numArray.add(o);
}
catch(NumberFormatException nfe){
stringArray.add(token);
}
}
}
finally {
if (input != null) {
input.close();
}
}
}

Related

Using File Dialogue Box Rather than FilePath Java

New to Java - I am trying to import a .txt file containing integers.
Eventually I want to import the integers into an arraylist and then create a frequency distribution and calculate the average.
Currently I am struggling to use the file dialogue box which is my end goal. I can import the .txt using the file path in my code shown. If any one could help me out with how to use the dialogue box instead it would be greatly appreciated!
import java.io.*;
import java.util.*;
public class Distribution {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println("Enter a complete file path to file you would like to open:");
String fileName = input.nextLine();
File inFile = new File(fileName);
FileReader ins = null;
try {
ins = new FileReader(inFile);
int ch;
while ((ch = ins.read()) != -1) {
System.out.print((char) ch);
}
}
catch (Exception e) {
System.out.println(e);
}
finally {
try {
ins.close();
}
catch (Exception e) {
}
}
} // main end
}
Well, It's simple and easy.
import java.io.File;
import java.io.FileReader;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
class DistributionUI {
public static void main(String[] args) {
System.out.println("Enter a complete file path to file you would like to open:");
final JFileChooser fchooser = new JFileChooser() {
private static final long serialVersionUID = 1L;
public void approveSelection() {
File inFile = getSelectedFile();
if (inFile.exists() ) {
FileReader ins = null;
try {
ins = new FileReader(inFile);
int ch;
while ((ch = ins.read()) != -1) {
System.out.print((char) ch);
}
} catch (Exception e) {
System.out.println(e);
} finally {
try {
ins.close();
} catch (Exception e) {
}
}
}
super.approveSelection();
}
};
fchooser.setCurrentDirectory(new File("."));
fchooser.setAcceptAllFileFilterUsed(false);
FileNameExtensionFilter filter = new FileNameExtensionFilter("my file", "txt");
fchooser.addChoosableFileFilter(filter);
fchooser.showOpenDialog(null);
} // main end
}

how to access main class jtextfield in Extended class

I have a main class File
and another extend class File 2
how can i access a textfield declared in File with awt and Swing to the extended class File2 ?
main class:-
import java.util.*;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class FileReceive extends FileReceiveUtil {
int msgIndex = 1;
Statement s;
public static File f;
public static String phoneNo, phoneNoLo, sk;
public static String str = "";
public static String path = "";
public String ran, ran11;
public String mes, sharedString;
FileReceive() throws Exception {
super("COM4");
}
#Override
public void processSMS(String str) throws Exception {
}
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame("File Receive");
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 2));
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
JLabel nameId = new JLabel("Enter Destination Path");
JButton browseb = new JButton("Browse");
JLabel bodyTempId = new JLabel("Path : ");
final JTextField jtf = new JTextField(" ");
JButton sendB = new JButton("Receive");
panel.add(nameId);
panel.add(browseb);
panel.add(bodyTempId);
panel.add(jtf);
panel.add(sendB);
frame.add(panel);
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
this()
browseb.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser jf = new JFileChooser();
String str1 = "";
int m = jf.showOpenDialog(null);
if (m == JFileChooser.APPROVE_OPTION) {
f = jf.getSelectedFile();
str = f.getPath();
path = f.getAbsolutePath();
jtf.setText(path);
}
}
});
sendB.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
FileReceiveUtil util = null;
try {
util = new FileReceive();
} catch (Exception ex) {
Logger.getLogger(FileReceive.class.getName()).log(Level.SEVERE, null, ex);
}
ArrayList al = new ArrayList();
try {
util.startReceive(al, 10);
} catch (Exception ex) {
Logger.getLogger(FileReceive.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
}
Extended class :-
import java.awt.event.ActionEvent;
import java.io.*;
import java.util.*;
import javax.comm.*;
import javax.swing.JTextField;
public abstract class FileReceiveUtil implements Runnable {
private static int responseCode = -1;
private static String userCredentials = null;
private static String cookie = null;
private static String site = null;
private static String actionStr = null;
private Enumeration portList;
private CommPortIdentifier portId;
private SerialPort serialPort;
private OutputStream outputStream;
private String strPortName;
private InputStream inputStream;
private boolean boolKeepReceiving = true;
private Thread threadRX;
private ArrayList alSMSStore;
private int intDelay;
public FileReceiveUtil(String strPortName) throws Exception {
this.strPortName = strPortName;
initCommPort();
}
private void initCommPort() throws Exception {
boolean boolPortOK = false;
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equalsIgnoreCase(strPortName)) {
this.serialPort = (SerialPort) portId.open("SimpleWriteApp", 2000);
outputStream = serialPort.getOutputStream();
inputStream = serialPort.getInputStream();
serialPort.notifyOnDataAvailable(true);
serialPort.setSerialPortParams(230400,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
boolPortOK = true;
break;
}
}
}
if (!boolPortOK) {
throw new Exception("Port " + strPortName + " does not exist!");
}
}
private String readSMS() throws Exception {
StringBuffer sb = new StringBuffer();
sb.append(writeATCmd());
return sb.toString();
}
private String writeATCmd() throws Exception {
//Thread.sleep(2000);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] data = new byte[1];
// Thread.sleep(10);
int ch = inputStream.read(data);
//System.out.println(x);
bos.write(data, 0, 1);
byte[] bytes = bos.toByteArray();
File someFile = new File("D:\\yadhu.txt");
FileOutputStream fos = new FileOutputStream(someFile,true);
fos.write(bytes);
fos.flush();
fos.close();
String str = bytes.toString();
System.out.println("Data : "+ str);
return str;
}
private void startReceivingSMS() throws Exception {
final String ERROR = "ERROR";
while (boolKeepReceiving) {
Thread.sleep(intDelay);
try {
System.out.println(" File recieved ");
String str = readSMS();
} catch (Throwable t) {
System.out.println("ERROR RECEIVING MSG");
t.printStackTrace();
}
}
}
final public void startReceive(ArrayList alSMSStore, int intDelay) throws Exception {
this.alSMSStore = alSMSStore;
this.intDelay = intDelay;
threadRX = new Thread(this);
threadRX.start();
}
final public void run() {
try {
startReceivingSMS();
} catch (Throwable t) {
t.printStackTrace();
}
}
final public void stopReceivingSMS() {
this.boolKeepReceiving = false;
}
public ArrayList getReceivedMessages() {
return this.alSMSStore;
}
private static void exit(String errorMsg) {
System.err.println(errorMsg);
System.exit(1);
}
public abstract void processSMS(String message) throws Exception;
}
i want " File someFile = new File("D:\yadhu.txt"); " to change this and add file name from the jtextfield on gui
please help
make the JTextField global in the class instead of a local function item.

how i can change the end of r.keyPress(KeyEvent.VK_W) the W out of the VK

Alright, So im doing Keypressed and keyreleased, and that works with VK_ stuff.... i have a GUi ready and im able to save and load config files, but i was wondering on how i can change the end of r.keyPress(KeyEvent.VK_W) the W out of the VK with my code....
Here is my main
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class Main {
public static void main(String[] args) throws Exception{
Config bot = new Config();
bot.setVerbose(true);
bot.connect("irc.twitch.tv", 6667, "oauth:6u54pi07uzegv42dwee65gpgzmwwgi");
bot.joinChannel("#mmolegion");
JFrame frame = new JFrame("TwitchBot");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(700, 500));
frame.setLocationRelativeTo(null);
frame.setResizable(true);
KeyGetter.LoadKeys();
try {
Config.loadConfig();
} catch (Exception e) {
e.printStackTrace();
}
JMenuBar mb = new JMenuBar();
JMenu file = new JMenu("File");
mb.add(file);
JMenu edit = new JMenu("Edit");
mb.add(edit);
JMenuItem options = new JMenuItem("Options");
options.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
Config.openConfig(frame);
}
});
frame.setJMenuBar(mb);
edit.add(options);
frame.pack();
frame.setVisible(true);
}
}
and he is my Config
import java.awt.Choice;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import org.jibble.pircbot.PircBot;
public class Config extends PircBot{
public static String left = "up", right = "right", up = "up", down = "down";
private static ArrayList<Choice> choices;
public Config() {
this.setName("Rex__Bot");
}
public void onMessage(String channel, String sender, String login, String hostname, String message) {
if(message.equals("up")) {
try {
Robot r = new Robot();
r.keyPress(KeyEvent.VK_W);
r.delay(300);
r.keyRelease(KeyEvent.VK_W);
}catch(Exception ex) {
ex.printStackTrace();
}
}
}
public static void openConfig(JFrame frame){
choices = new ArrayList<Choice>();
JFrame options = new JFrame("Options");
options.setSize(600, 400);
options.setResizable(false);
options.setLocationRelativeTo(frame);
options.setLayout(null);
Choice left = addChoice("left", options, 30, 30);
left.select(Config.left);
Choice right = addChoice("right", options, 30, 80);
right.select(Config.right);
Choice up = addChoice("up", options, 150, 30);
up.select(Config.up);
Choice down = addChoice("down", options, 150, 80);
down.select(Config.down);
JButton done = new JButton("ok");
done.setBounds(150, 220, 100, 30);
done.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
options.dispose();
saveChanges();
}
});
options.add(done);
options.setVisible(true);
}
public static void saveChanges(){
Choice left = choices.get(0);
Choice right = choices.get(1);
Choice up = choices.get(2);
Choice down = choices.get(3);
Config.left = left.getSelectedItem();
Config.right = right.getSelectedItem();
Config.up = up.getSelectedItem();
Config.down = down.getSelectedItem();
try{
saveConfig();
}
catch(Exception e){
e.printStackTrace();
}
}
public static Choice addChoice(String name, JFrame options, int x, int y){
JLabel label = new JLabel(name);
label.setBounds(x, y - 20, 100, 20);
Choice key = new Choice();
for(String s: getKeyNames()){
key.add(s);
}
key.setBounds(x, y, 100, 20);
options.add(key);
options.add(label);
choices.add(key);
return key;
}
public static ArrayList<String> getKeyNames(){
ArrayList<String> result = new ArrayList<String>();
for(String s: KeyGetter.keyNames){
result.add(s);
if(s.equalsIgnoreCase("F24")){
break;
}
}
return result;
}
public static void loadConfig() throws Exception{
File directory = new File(getDefaultDirectory(), "/Twitchbot");
if(!directory.exists()){
directory.mkdirs();
}
File config = new File(directory,"config.txt");
if(!config.exists()){
config.createNewFile();
System.out.println("File not found, saving default");
saveConfig();
return;
}
#SuppressWarnings("resource")
Scanner s = new Scanner(config);
HashMap<String, String> values = new HashMap<String, String>();
while(s.hasNextLine()){
String[] entry = s.nextLine().split(":");
String key = entry[0];
String value = entry[1];
values.put(key, value);
}
if(!values.containsKey("left") || !values.containsKey("right") || !values.containsKey("up") || !values.containsKey("down")){
System.out.println("Invalid names in config, saving default config");
saveConfig();
return;
}
String left = values.get("left");
String right = values.get("right");
String up = values.get("up");
String down = values.get("down");
if(!(getKeyNames().contains(left) && getKeyNames().contains(right) && getKeyNames().contains(up) && getKeyNames().contains(down))){
System.out.println("Invalid key in config, saving default config");
}
Config.left = left;
Config.right = right;
Config.up = up;
Config.down = down;
}
public static void saveConfig() throws Exception{
File directory = new File(getDefaultDirectory(), "/Twitchbot");
if(!directory.exists()){
directory.mkdirs();
}
File config = new File(directory,"config.txt");
PrintWriter pw = new PrintWriter(config);
pw.println("left:" + left);
pw.println("right:" + right);
pw.println("up:" + up);
pw.println("down:" + down);
pw.close();
}
public static String getDefaultDirectory(){
String OS = System.getProperty("os.name").toUpperCase();
if(OS.contains("WIN")){
return System.getenv("APPDATA");
}
if(OS.contains("MAC")){
return System.getProperty("user.home") + "Library/Application Support";
}
return System.getProperty("user.home");
}
}
and here is my KeyGetter
import java.awt.event.KeyEvent;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
public class KeyGetter {
public static HashMap<String, Integer> keys;
public static ArrayList<String> keyNames;
public static void LoadKeys(){
keys = new HashMap<String, Integer>();
keyNames = new ArrayList<String>();
Field[] fields = KeyEvent.class.getFields();
for(Field f: fields){
if(Modifier.isStatic(f.getModifiers())){
if(f.getName().startsWith("VK")){
try{
int num = f.getInt(null);
String name = KeyEvent.getKeyText(num);
keys.put(name, num);
keyNames.add(name);
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
}
}
So is there anyway of changing the The last letter of VK_W with my config file?
I don't know if you can do this.
Why don't you just save int values. For example KeyEvent.VK_W transforms to:
public static final int VK_W = 87;
So it would be much easier if you would just save int walues to your configuration.
Here can you find the whole list:
KeyEvent.VK_W
So you can just use the following code:
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == 87) {
System.out.println("W pressed");
}
}
Instead of:
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_W) {
System.out.println("W pressed");
}
}

Regarding JFileChooser

I have developed a program that is counting the number of lines in a file that is shown below
Scanner in=new Scanner(System.in);
System.out.println("Enter the Drive name like C,D,E etc");
String drive=in.next();
System.out.println("Enter the main folder name");
String main_folder=in.next();
File directory=new File(drive+":"+"//"+main_folder+"//");
Map<String, Integer> result = new HashMap<String, Integer>();
//File directory = new File("C:/Test/");
File[] files = directory.listFiles();
for (File file : files) {
if (file.isFile()) {
Scanner scanner = new Scanner(new FileReader(file));
int lineCount = 0;
try {
for (lineCount = 0; scanner.nextLine() != null; lineCount++);
} catch (NoSuchElementException e) {
result.put(file.getName(), lineCount);
} }}
for( Map.Entry<String, Integer> entry:result.entrySet()){
System.out.println(entry.getKey()+" ==> "+entry.getValue());
}
but I was trying to add a swing interface JFilechooser , I want that user should select the particular folder and all the files inside that folder to be get selected and rest above as my code works as it is , Please advise
Please advise for desiging the jfile chooser so that I can integrate my above code.
I have design one more solution that is
package aa;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.FileDialog;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class FileBrowse extends JFrame {
private JButton browseSwing = new JButton("Choose File");
private JTextField textField = new JTextField(30);
private JButton approve = new JButton("Ok");
public FileBrowse() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600,80);
setResizable(false);
browseSwing.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (arg0.getSource()==browseSwing)
onBrowseSwing();
}});
Container container = getContentPane();
container.setLayout(new FlowLayout());
container.add(browseSwing);
container.add(textField);
container.add(approve);
//pack();
}
protected void onBrowseSwing() {
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showDialog(this, "Open/Save");
if (result == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
textField.setText(file.toString());
String x = file.toString();
fileRead(x);
}
}
public void fileRead(String input){
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(input);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
int count = 0;
int count2 = 0;
//Read File Line By Line
while((strLine = br.readLine())!= null ){
if (strLine.trim().length() != 0){
count++;
}else{
count2++;
}
}
System.out.println("-------Lines Of COdes-------");
System.out.println("number of lines:" + count);
System.out.println("number of blank lines:" + count2);
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
public static void main(String[] args) {
new FileBrowse().setVisible(true);
}
}
but it chooses the individual files I want that all the files to be get selected inside that folder Test
You could use this code (adapted from here):
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("choosertitle");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
Map<String, Integer> result = new HashMap<String, Integer>();
File directory = new File(choosers.getSelectedFile().getAbsolutePath()); //This is where you need to change.
File[] files = directory.listFiles();
for (File file : files)
{
if (file.isFile())
{
Scanner scanner = new Scanner(new FileReader(file));
int lineCount = 0;
try
{
for (lineCount = 0; scanner.nextLine() != null; lineCount++)
;
} catch (NoSuchElementException e)
{
result.put(file.getName(), lineCount);
}
}
}
for (Map.Entry<String, Integer> entry : result.entrySet())
{
System.out.println(entry.getKey() + " ==> " + entry.getValue());
}
}
This code should replace this section:
Scanner in=new Scanner(System.in);
System.out.println("Enter the Drive name like C,D,E etc");
String drive=in.next();
System.out.println("Enter the main folder name");
String main_folder=in.next();
File directory=new File(drive+":"+"//"+main_folder+"//");
Also, just a recommendation, when working with consoles and system paths, you should ideally use File.seperator. This will automatically provide you with the respective system's path separation character.
As per your edit, in your case you are using the fileChooser.getSelectedFile();. This will only get you the file that the user has selected, as per its name. What you should use is the fileChooser.getSelectedFile().getAbsolutePath() and iterate over the files which are within that same directory (as shown above).
EDIT 2: I use this code to display 2 buttons with their respective event handlers:
public static void main(String args[]) {
JFrame frame = new JFrame("Button Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton btnExit= new JButton("EXIT");
ActionListener actionListenerExitButton = new ActionListener() {
#Override
public void actionPerformed(ActionEvent actionEvent) {
System.out.println("Exit Button Was Clicked");
}
};
btnExit.addActionListener(actionListenerExitButton);
JButton btnEnter = new JButton("ENTER");
ActionListener actionListenerEnterButton = new ActionListener() {
#Override
public void actionPerformed(ActionEvent actionEvent) {
System.out.println("Enter Button Was Clicked");
}
};
btnEnter.addActionListener(actionListenerEnterButton);
Container contentPane = frame.getContentPane();
contentPane.add(btnExit, BorderLayout.SOUTH);
contentPane.add(btnEnter, BorderLayout.NORTH);
frame.setSize(300, 100);
frame.setVisible(true);
}
All that you need to do now is to plug in the code I have provided earlier in the appropriate event handler.

How to populate JList with certain words from txt file

I need help with JList. Need to add a text file to a list but txt file is named library.txt with:
title1 author1 description1 publisher1
title2 author2 description2 publisher2
title3 author3 description3 publisher3
title4 author4 description4 publisher4
What program needs to do is to fill list only with titles from txt and when user select certain title from list the program needs to write the description to a JTextArea.
This is what I got so far.
import java.awt.FlowLayout;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JTextArea;
public class Library extends JFrame {
private JList lista;
private JTextArea tekst;
DefaultListModel model;
public Library() {
super("Biblioteka");
this.setSize(300, 300);
setLayout(new FlowLayout());
model = new DefaultListModel();
lista = new JList(model);
add(lista);
tekst = new JTextArea(20, 20);
add(tekst);
File fajl = new File("library.txt");
BufferedReader ulaz = null;
try {
FileReader fr = new FileReader(fajl);
ulaz = new BufferedReader(fr);
String linija;
try {
while ((linija = ulaz.readLine()) != null) {
//lista.add(linija);
//System.out.println(linija);
String[] reci = linija.split("\t");
String naslovi = null;
for (int i = 0; i < reci.length; i++) {
naslovi = reci[0];
}
int pos = lista.getModel().getSize();
model.addElement(naslovi.toString());
}
} catch (IOException ex) {
Logger.getLogger(Library.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(Library.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String[] args) {
Library l = new Library();
l.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
l.setSize(300, 430);
l.setVisible(true);
}
}
As Andrew mentioned in his comments use a POJO (plain old java object) like
class Book {
String title;
String author;
String description:
/* other fields*/
}
Then rewrite your loop similar to
while ((linija = ulaz.readLine()) != null) {
String[] reci = linija.split("\t");
for (int i = 0; i < reci.length; i++) {
Book book = new Book();
book.title = reci[0];
book.description = reci[2];
/* other stuff here */
model.addElement(book);
}
}
Use then a ListCellRenderer to display only the title in the List and a ListSelectionListener to listen and update the text area accordingly

Categories