The below code is used to create a line graph. I am able to display the integers in the TextArea but i am not able to display the sentences above the integers in the text file. How do i rectify this program?
The screenshot of the text file is given below.
I want the first three lines of the text file also to be printed in the TextArea.
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
import org.jfree.chart.*;
import org.jfree.chart.plot.*;
import org.jfree.data.xy.*;
public class Pio {
static JFrame frame1 = new JFrame("Graph");
static String URL = null;
static JTextArea txt = new JTextArea();
static JPanel panel = new JPanel();
public static void main(String[] args) throws IOException {
JButton but = new JButton("Open file");
![enter image description here][2]
panel.add(but);
frame1.add(panel, BorderLayout.WEST);
frame1.setVisible(true);
frame1.setSize(1000,400);
but.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JFileChooser chooser = new JFileChooser();
int ret = chooser.showDialog(null, "Open file");
if (ret == JFileChooser.APPROVE_OPTION)
{
File file = chooser.getSelectedFile();
URL = file.getAbsolutePath();
}
File f = new File(URL);
FileReader inputF = null;
try {
inputF = new FileReader(f);
}
catch (FileNotFoundException e1) {
e1.printStackTrace();
}
BufferedReader in = new BufferedReader(inputF);
int[] a = new int[100];
int[] b = new int[100];
String s=null;
try {
s = in.readLine();
}
catch (IOException e1) {
e1.printStackTrace();
}
int i = 0;
while (s != null && i < 100)
{ // your arrays can only hold 1000 ints
String pair[] = s.split(" ");
a[i] = Integer.parseInt(pair[0]);
b[i] = Integer.parseInt(pair[1]);
i++; // don't forget to increment
try {
s = in.readLine();
}
catch (IOException e1) {
e1.printStackTrace();
}
}
try {
in.close();
}
catch (IOException e1) {
e1.printStackTrace();
}
System.out.println("the output of the file is " + f);
XYSeries data = new XYSeries("Line Graph");
int n = a.length;
for (int j = 0; j < n; j++) {
data.add(a[j], b[j]);
}
XYDataset xY = new XYSeriesCollection(data);
JFreeChart chart=ChartFactory.createXYLineChart(
"line graph",
"Cycles",
"Temperature",
xY,
PlotOrientation.VERTICAL,
true,
true,
true);
ChartPanel p=new ChartPanel(chart);
p.setVisible(true);
p.setLocation(100,100);
p.setSize(500,500);
frame1.add(p,BorderLayout.EAST);
}
});
}
}
there nothing about JTextArea, use constructor JTextArea(int rows, int columns)
put JTextArea to the JScrollPane, this JScrollPane put or the EAST or WEST area
put JPanel with JButton to the SOUTH or NORTH area
if ChartPanel doesn't returns any PrefferedSize (I doubt that), or this value isn't correct, then set for own PrefferedSize, put ChartPanel to the CENTER area
as you saw there any code line about setSize, JFrame has implemented BorderLayout in the API
use pack() instead of setSize()
setLocation() if required
last code lines in the ActionListener (your code logics) must be
frame.validate();
frame.repaint();
frame.pack();
in this form (your code logics) is Swing GUI during FileIO unresponsible for Mouse and Key Events, wrap FileIO to the Runnable#Tread or use SwingWorker for redirecting this long and hard task to the background task
create ChartPanel as local variable (as JFrame) and first code line in the ActionListener must be
.
frame.remove(ChartPanel);
Two display two componenets you can use a JSplitPane.
While loading data into your array append it to a JTextArea (area1 in the sample code)
final JTextArea area1 = new JTextArea();
...
area1.append("X=" + a[i] + " Y=" + b[i] + "\n");
Then rather than adding the chart to the frame add both the Chart and the TextArea to the JSplitPane
ChartPanel p = new ChartPanel(chart);
JSplitPane splitpane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
frame1.add( splitpane , BorderLayout.CENTER );
splitpane.add(p);
splitpane.add(area1);
pane.validate();
frame1.validate();
frame1.repaint();
To append data the the JTextArea use
area1.append("Creating a line graph\n");
area1.append("Selected file " + f + "\n");
while (s != null && i < 100) { // your arrays can only hold 1000 ints
String pair[] = s.split(" ");
try{
a[i] = Integer.parseInt(pair[0]);
b[i] = Integer.parseInt(pair[1]);
area1.append("X=" + a[i] + " Y=" + b[i] + "\n");
} catch (NumberFormatException e) {
area1.append(s + "\n");
}
try {
s = in.readLine();
i++; // don't forget to increment
} catch (IOException e1) {
e1.printStackTrace();
}
}
area1.append("Finished reading data\n");
...
In this example I'm assuming that the headder will fail parseInt and (if is does) appending the String s.
Related
This question is similar to this : How do you reference a button inside of its actionlistener?
I want to create a simple form containing 8 toggle buttons. if i select the toggle button and click save button, it will write into the text file i.e "Button x, On". Next time i open the form, the form will check in the notepad if Button x is already on. If on, the toggle button will already be selected and vice versa.
I know how to write to and read from the notepad, but i am not sure how to check if i.e the user select button 2 then the code will write into second line " Button2, on"
Here is my code so far to write :
Path path = Paths.get(csvFile);
// check if button x is selected, if yes : <- how to refer to button x ?
BufferedWriter bw = new BufferedWriter(New FileWriter(csvFile, true);
writer.write ("button x,on" + "\r\n");
writer.close
and this is my code when the form is opened :
BufferedReader br = null;
String line = "";
String resFilesplitby = ",";
br = new BufferedReader(new FileReader(csvFile));
while((line = br.readLine()) != null){
String[] condition = line.split(csvFilesplitby);
String power = condition[1];
// check if button x is already selected
if (button x power.equals("on")){
button x.isSelected();
}
}
I manage to found a simple way to solve the problem
By adding the button to an array.
JToggleButton[] buttons = new JToggleButton[8];
buttons[0] = seat1; //this is variable name of my button.
buttons[1] = seat2;
buttons[2] = seat3;
buttons[3] = seat4;
buttons[4] = seat5;
buttons[5] = seat6;
buttons[6] = seat7;
buttons[7] = seat8;
// do the work here
for (JToggleButton btn : buttons){
if(btn.isSelected){
}
}
For simplicity I recommend that you write all of the button statuses at the same time, and write them directly as a boolean value:
//Write the state of all the buttons in a single line:
writer.write (
x1.isSelected() + "," +
x2.isSelected() + "," +
x3.isSelected() + "," +
x4.isSelected() + "," +
x5.isSelected() + "," +
x6.isSelected() + "," +
x7.isSelected() + "," +
x8.isSelected());
Then reading it back as a single line and just compare each of the 8 items split by the ",":
String[] condition = line.split(csvFilesplitby);
if (condition[0].equalsIgnoreCase("true")){
x1.setSelected(true);
}else if (condition[1].equalsIgnoreCase("true")){
x2.setSelected(true);
}else if (condition[2].equalsIgnoreCase("true")){
x3.setSelected(true);
}else if (condition[3].equalsIgnoreCase("true")){
x4.setSelected(true);
}else if (condition[4].equalsIgnoreCase("true")){
x5.setSelected(true);
}else if (condition[5].equalsIgnoreCase("true")){
x6.setSelected(true);
}else if (condition[6].equalsIgnoreCase("true")){
x7.setSelected(true);
}else if (condition[7].equalsIgnoreCase("true")){
x8.setSelected(true);
}
Obviously you should add some error checking and make sure all buttons are deselected before you set if they are selected or not. But I am sure you can work that part out.
Alternatively you can try something like below :
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import javax.swing.*;
public class Ques1 extends JFrame implements ActionListener {
private JPanel panel;
private JToggleButton[] buttons;
public Ques1() {
initComponents();
buttonswork();
}
private void initComponents() {
buttons = new JToggleButton[6];
panel = new JPanel();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.LINE_AXIS));
panel.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
for (int i = 0; i < buttons.length; i++) {
JToggleButton tb = buttons[i];
tb = new JToggleButton("tb" + (i + 1));
tb.addActionListener(this);
panel.add(tb);
}
getContentPane().add(panel);
pack();
}
private void buttonswork() {
try {
String line = "";
String buttonString = "tb1-0\n"
+ "tb2-0\n"
+ "tb3-0\n"
+ "tb4-1\n"
+ "tb5-1\n"
+ "tb6-0\n";
BufferedReader br = new BufferedReader(new StringReader(buttonString));
while ((line = br.readLine()) != null) {
Component[] components = panel.getComponents();
for (Component c : components) {
if (c instanceof JToggleButton) {
String ac = ((JToggleButton) c).getActionCommand();
((JToggleButton) c).addActionListener(this);
if (ac.equalsIgnoreCase(line.split("-")[0])) {
((JToggleButton) c).setSelected(Integer.parseInt(line.split("-")[1]) == 1);
}
}
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
new Ques1().setVisible(true);
});
}
#Override
public void actionPerformed(ActionEvent e) {
switch (e.getActionCommand()) {
case "tb1":
//do your work here ...
break;
case "tb2":
//do your work here ...
break;
}
}
}
I'm attempting to make a code that will use JFileChooser and JPassword for getting input of encrypted code or code to be encrypted.
Here is the code to be encrypted "Be sure to drink your Ovaltine!" to be saved in a .rtf or a .txt file. The key is "annie". The output should be
"Fv '$zi (# pzm"| (wy& `%ip(zzm%".
I have two different class files under the project "Password". One class is called "File Opener". It calls the class "Password1".
Here is Password1.java.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
/* PasswordDemo.java requires no other files. */
public class Password1 extends JPanel
implements ActionListener {
private String key;
private static String OK = "ok";
private JFrame controllingFrame; //needed for dialogs
private JPasswordField passwordField;
public Password1(JFrame f) {
//Use the default FlowLayout.
controllingFrame = f;
//Create everything.
passwordField = new JPasswordField(10);
passwordField.setActionCommand(OK);
passwordField.addActionListener(this);
JLabel label = new JLabel("Enter the key: ");
label.setLabelFor(passwordField);
JComponent buttonPane = createButtonPanel();
//Lay out everything.
JPanel textPane = new JPanel(new FlowLayout(FlowLayout.TRAILING));
textPane.add(label);
textPane.add(passwordField);
add(textPane);
add(buttonPane);
}
protected JComponent createButtonPanel() {
JPanel p = new JPanel(new GridLayout(0,1));
JButton okButton = new JButton("OK");
okButton.setActionCommand(OK);
okButton.addActionListener(this);
p.add(okButton);
return p;
}
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
controllingFrame.dispose();
if (OK.equals(cmd)) { //Process the password.
char[] input = passwordField.getPassword();
key = new String(input);
//Zero out the possible password, for security.
Arrays.fill(input,'0');
passwordField.selectAll();
resetFocus();
} else {
System.out.println("Please enter a key.");
}
}
public String getKey(){
return key;
}
//Must be called from the event dispatch thread.
protected void resetFocus() {
passwordField.requestFocusInWindow();
}
public static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Key");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
final Password1 newContentPane = new Password1(frame);
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Make sure the focus goes to the right component
//whenever the frame is initially given the focus.
frame.addWindowListener(new WindowAdapter() {
public void windowActivated(WindowEvent e) {
newContentPane.resetFocus();
}
});
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
//Turn off metal's use of bold fonts
UIManager.put("swing.boldMetal", Boolean.FALSE);
createAndShowGUI();
}
});
}
}
And here is the FileOpener.java.
import javax.swing.*;
import java.io.*;
import javax.swing.filechooser.*;
import java.awt.event.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class FileOpener extends JPanel implements ActionListener {
static private final String newline = "\n";
private Password1 p1;
JButton decodeButton, encodeButton;
JFileChooser fc;
JTextArea log;
Scanner in = new Scanner(System.in);
JFrame frame;
File file;
int count;
public FileOpener(){
// create and set up the window.
frame = new JFrame("Open Your File");
// make the program close when the window closes
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// create the box layout
frame.getContentPane( ).setLayout(new BoxLayout(frame.getContentPane( ), BoxLayout.Y_AXIS));
//label prompting user for input
JLabel label1 = new JLabel ("Would you like to encode or decode your file?", JLabel.CENTER);
frame.getContentPane().add(label1);
//create a filer chooser
fc = new JFileChooser();
// add a button object
decodeButton = new JButton("Decode");
decodeButton.addActionListener(this);
frame.getContentPane( ).add(decodeButton);
encodeButton = new JButton("Encode");
encodeButton.addActionListener(this);
frame.getContentPane( ).add(encodeButton);
// display the window.
frame.pack( );
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
//Handle open button action.
if (e.getSource() == encodeButton) {
frame.dispose();
int returnVal = fc.showOpenDialog(FileOpener.this);
if (returnVal == JFileChooser.APPROVE_OPTION ) {
try {
file = fc.getSelectedFile();
p1 = new Password1(frame);
p1.createAndShowGUI();
//get length of key
String key = p1.getKey();
int length3 = key.length();
count = 0;
int keyAsciiValues[] = new int[length3];
String name1 ="";
//get ascii value of each letter in key
for (int k=0; k<length3; k++){
char a = key.charAt(k);
int ascii1 = (int)a;
//put ascii value of letter in key to array
keyAsciiValues[k]= ascii1;
}
FileInputStream file2= new FileInputStream(file);
//create a scanner for it
in = new Scanner(file2);
//read in message
String name;
name = in.nextLine();
for (int k=0; k<length3; k++){
char a = key.charAt(k);
int ascii1 = (int)a;
//put ascii value of letter in key to array
keyAsciiValues[k]= ascii1;
}
//measure length of code message array
int length1 = name.length();
//measures length of strings in code message array
for(int j=0;j<length1;j++){
char c = name.charAt(j);
int ascii = (int)c;
ascii += keyAsciiValues[count];
if(c != ' '){
count++;
}
if(count>length3-1){
count = 0;
}
while(ascii>126){
ascii-= 93;
}
char b=(char)ascii;
if(c == ' '){
b = ' ';
}
name1 += b;
}
System.out.println(name1);
} catch (FileNotFoundException k){
//the file was not found!
System.out.println("File could not be opened!");
}
}
//Handle save button action.
} else if (e.getSource() == decodeButton) {
frame.dispose();
int returnVal = fc.showOpenDialog(FileOpener.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
try {
file = fc.getSelectedFile();
p1 = new Password1(frame);
p1.createAndShowGUI();
//open the file
//get length of key
String key = p1.getKey();
int length3 = key.length();
count = 0;
int keyAsciiValues[] = new int[length3];
String name1 ="";
//get ascii value of each letter in key
for (int k=0; k<length3; k++){
char a = key.charAt(k);
int ascii1 = (int)a;
//put ascii value of letter in key to array
keyAsciiValues[k]= ascii1;
}
//create a scanner for it
in = new Scanner(file);
//read in message
String name;
name = in.nextLine();
for (int k=0; k<length3; k++){
char a = key.charAt(k);
int ascii1 = (int)a;
//put ascii value of letter in key to array
keyAsciiValues[k]= ascii1;
}
//measure length of code message array
int length1 = name.length();
//measures length of strings in code message array
for(int j=0;j<length1;j++){
char c = name.charAt(j);
int ascii = (int)c;
ascii -= keyAsciiValues[count];
if(c != ' '){
count++;
}
if(count>length3-1){
count = 0;
}
while(ascii<33){
ascii+= 93;
}
char b=(char)ascii;
if(c == ' '){
b = ' ';
}
name1 += b;
}
System.out.print(name1);
} catch (FileNotFoundException k){
//the file was not found!
System.out.println("File could not be opened!");
}
}
in.close();
log.append("Opening: " + file.getName() + "." + newline);
}
}
public static void main(String args[]) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
FileOpener f = new FileOpener();
}
}
It was working fine before I added the JFileChooser and the Password stuff aka there shouldn't be anything wrong with the actual ciphering part of the code.
It's giving me a java.lang.NullPointerException at line at line 70 in FileOpener.
int length3 = key.length();
Thanks!
In the createAndShowGUI() method, you show your Password1 instance in a JFrame, not a modal JDialog. Therefore, this display instruction is non-blocking, i.e. it does not stop code execution, nor does it wait until you click a button that closes the window.
As a result, you retrieve the Password1 instance key before its actionPerformed() method can execute and initialize the key attribute, hence the key is still null and you get a NullPointerException when you invoke any method on it.
My suggestion is using a modal JDialog in createAndShowGUI() to manage your Password1 interface (initialization using a JPanel is much like what you are already doing with a JFrame). This way, when you invoke createAndShowGUI(), the FileOpener.actionPerformed() method execution will block until you are done with the Password1 dialog, hence you will make sure key is properly initialized before you retrieve and use it in FileOpener.actionPerformed().
One last thing: be careful with frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);! Using it on your main window is OK but using it on any secondary window will make the whole program shut down completely as soon as you close it. But anyway, the JDialog version of setDefaultCloseOperation() doesn't accept EXIT_ON_CLOSE as a valid argument, so you will remain using it only on your main FileOpener window, which is fine.
I wrote the program to create file and add in field using by jframe but it not working correctly, please help me thanks!!
read file get field full name and customer number and add one more field using jframe
full name and customer number working fine but jframe not working correctly.. so please help me...
and actually I need verticall scroll down as well, please help me..
suppose is there a 6 records in files in..
i need to put in jframe:
00240000844928953504
00240000844928953505
00240000844928953506
00240000844928953507
00240000844928953508
00240000844928953509
file output is not correct actually it put all 6 scanner line in all lines file out..
custID,fullname, 00240000844928953504
00240000844928953505
00240000844928953506
00240000844928953507
00240000844928953508
00240000844928953509
custID,fullname, 00240000844928953504
00240000844928953505
00240000844928953506
00240000844928953507
00240000844928953508
00240000844928953509
it like this!!:(
it should be like this!!
custID,fullname,00240000844928953504
custID,fullname,00240000844928953505
....
HEre is my code!!
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class scanner {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
final JFrame frame = new JFrame("Scan Here: ");
JPanel panel = new JPanel();
final JTextArea text = new JTextArea(20, 40);
JButton button = new JButton("Enter");
frame.add(panel);
panel.add(text);
panel.add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
BufferedReader br = null;
BufferedWriter lbwp = null;
String scanner = (text.getText());
System.out.println(scanner);
try {
File folderall = new File("FilesIn");
File[] BFFileall = folderall.listFiles();
for (File file : BFFileall) {
String str = file.getName();
String reprintbwletterbwpca = ("FileOut" + "\\" + str);
lbwp = new BufferedWriter(new FileWriter(reprintbwletterbwpca));
lbwp.write("\"CUSTID\",\"FullName\",\"ONECODE\"," + "\n");
br = new BufferedReader(new FileReader(file));
String line;
line = br.readLine();
while ((line = br.readLine()) != null) {
String[] actionID = line.split("\\\",\"");
String custnumber = actionID[3];
String fullname = actionID[18];
String add1 = actionID[19];
lbwp.write("\"" + custnumber + "\",\"" + fullname+ "\"," + "\"" + scanner + "\"," + "\n");
}
lbwp.close();
}
} catch(Exception e1) {
e1.printStackTrace();
}
frame.dispose();
}});
frame.setSize(500, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Please help me!!
Here you have two lists :
A list of entries coming from the file you are reading, each entry is read in "line" String.
A list of values you have input in a JTextArea separated by "\n".
First of all, you propably need to check if you have the same number of entries in the both lists. You also need to split your String scanner using "\n" as the separator.
As you are reading line by line, you can also use the following code which won't check if the number of entries are equals :
int index = 0;
String[] ids = scanner.split("\n");
while ((line = br.readLine()) != null) {
String[] actionID = line.split("\\\",\"");
String custnumber = actionID[3];
String fullname = actionID[18];
String add1 = actionID[19];
if (ids.length > index) {
lbwp.write("\"" + custnumber + "\",\"" + fullname+ "\"," + "\"" + ids[index] + "\"," + "\n");
} else {
lbwp.write("\"" + custnumber + "\",\"" + fullname+ "\"\n");
}
index++;
}
EDIT: replace the condition
I have a code that reads a multiple text files from a folder and I need to put them in a table.So far,everything is good except that every line from my text files are displayed in a different table.I know that the problem is that the table receives each line separately.I tried to create an object and fill it and then call inside the table but I couldn't make it work so if anyone can tell me the solution that would be great. Also I need to be able to compare the values and find an average,so if you have any tips for that to,would be great
here's an example of my text file
17/10/2012 10:00:06.67 [RX] - E usbR<LF>
817EE765FF53-53<LF>
817AA765FF53-34<LF>
817CC765FF53-25<LF>
00<LF>
E qEnd<LF>
and this is what I need to get in the table
ID RSSI
817EE765FF53 53
817AA765FF53 34
817CC765FF53 25
here is the code
import java.awt.BorderLayout;
import java.io.*;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class Foldersearch1
{
public static void main(String[] args)
{
// Directory path here
String path = "C:/Users/Nikica/Desktop/text files";
String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
files = listOfFiles[i].getName();
if (files.endsWith(".txt") || files.endsWith(".TXT"))
{
System.out.println(files);
();
String currentLine="";
File textFile = new File(folder.getAbsolutePath() + File.separator + files);
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(textFile);
try (DataInputStream in = new DataInputStream(fstream)) {
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
String line;
//Read File Line By Line
// int p=0;
// Object[][] Table=null;
while ((strLine = br.readLine()) != null) {
processLine(strLine);
Table(strLine);
// Print the content on the console
//System.out.println (strLine);
}
}
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
}
}
public static void processLine(String line) {
// skip header & footer
if (line.startsWith("17/10/2012 10:00:06.67 [RX] - E usbR<LF>") || line.startsWith("E qEnd<LF>")) {return;}
String ID = line.substring(0, 12);
String RSSI = line.substring(13, 15);
System.out.println("ID [" + ID + "]\t RSSI [" + RSSI +"]");
}
public static void Table(String line) {
JFrame frame = new JFrame("proba");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
if (line.startsWith("17/10/2012 10:00:06.67 [RX] - E usbR<LF>") || line.startsWith("E qEnd<LF>")) return;
String ID = line.substring(0, 12);
String RSSI = line.substring(13, 15);
Object rowData[][] = { { ID, RSSI } };
Object columnNames[] = { "ID", "RSSI" };
JTable table = new JTable(rowData, columnNames);
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
}
}
To make your code work with minimal changes, Create a Vector with the rowdata, and use the constructor public JTable(Vector rowData, Vector columnNames). The following code snippet should give you an idea on how to do it.
Vector<String> columnNames = new Vector<String>();
columnNames.add("ID");
columnNames.add("RSSI");
Vector<Vector<String>> rowData = new Vector<Vector<String>>();
for(int i=0; i<20; i++) {
Vector<String> row = new Vector<String>();
row.add("ID_" + i);
row.add("RSSI_" + i);
rowData.add(row);
}
JTable table = new JTable(rowData, columnNames);
I am trying to highlight some code in a JEditorPane like this:
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;
public class Driver
{
public static void main(String[] args)
{
try
{
//create a simple frame with an editor pane
JFrame frame = new JFrame("Highlight Test");
JEditorPane pane = new JEditorPane();
frame.getContentPane().add(pane);
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
//string to put in the pane
String text = "1234567890";
//grab the highlighter for the pane
Highlighter highlighter = pane.getHighlighter();
//store all the text at once
pane.setText(text);
//go through all the characters
for(int i = 0; i < text.length(); i++)
{
//highlight the latest character
highlighter.addHighlight(i, i + 1, DefaultHighlighter.DefaultPainter);
//sleep for a quarter second
Thread.sleep(250);
}
}catch(Exception ex){}
}
}
This will highlight the characters one at a time and all the characters will remain highlighted. Now, I'd like the same behavior (all the characters remain highlighted) but I'd like to change the text in between highlights, like this:
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;
public class Driver
{
public static void main(String[] args)
{
try
{
//create a simple frame with an editor pane
JFrame frame = new JFrame("Highlight Test");
JEditorPane pane = new JEditorPane();
frame.getContentPane().add(pane);
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
//string to put in the pane
String text = "1234567890";
//grab the highlighter for the pane
Highlighter highlighter = pane.getHighlighter();
//go through all the characters
for(int i = 0; i < text.length(); i++)
{
//place a new string in the pane
pane.setText(pane.getText() + text.charAt(i));
//highlight the latest character
highlighter.addHighlight(i, i + 1, DefaultHighlighter.DefaultPainter);
//sleep for a quarter second
Thread.sleep(250);
}
}catch(Exception ex){}
}
}
Notice the text in the pane is changing and then I'm applying a new highlight. The old highlights go away- I'd like them to stay. My assumption is the highlights go away each time you setText(). So, is there any way to keep the highlights in the text component while changing the text?
i didn't tried the following code but what i suggest is just try to highlight both latest character and previous ones too like this:
//go through all the characters
for(int i = 0; i < text.length(); i++)
{
//place a new string in the pane
pane.setText(pane.getText() + text.charAt(i));
//highlight the previous characters
if (i > 0) {
for ( int j=i-1; j >= 0; j--)
highlighter.addHighlight(j, j+1 , DefaultHighlighter.DefaultPainter);
}
//highlight the latest character
highlighter.addHighlight(i, i + 1, DefaultHighlighter.DefaultPainter);
//sleep for a quarter second
// Thread.sleep(250);
}
}catch(Exception ex){}