Web_Sailor 0 Junior Poster

Hi :)

I want that one of my fields in database should be redirected to some URL. For Example:

Sample Table:

1111 2222 3333 4444 5555
6666 7777 8888 9999 1100

Suppose I want my 3 field to be redirected to a URL when a user clicks on the output table view:

I want the the selected value should be sent to the URL. Like below:-

http://sampleurl%4444

Is there a way to do that ? Would appreciate some guidance.

Thanks
;)

Web_Sailor 0 Junior Poster

Web_Sailor,

we couldn't reach your point exactly..Please come up with clear information.

As per my understanding:
And why not you design your table in loadJSP.jsp . and assign response to a div tag like :

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<%
  String q = request.getParameter("q");

  //String str = "Loading JSP String from Ajax: Loading......";
  String[] str = {"one","two","three"};
  java.util.Date dt = new java.util.Date();
  for(int i=0; i<str.length; i++){
  out.println(str[i]);
 [B] // Design you table here and assign strings here[/B]
  }
document.getElementById("printTable").innerHTML=xmlhttp.responseText
<body>
        <a href="javascript:loadContent('parameterValue')">Load Ajax Content</a>
        <table border ="3">

         <tr><td><div id="printTable"></div></td></tr>
      
        </table>
    </body>

out.println(str);
// Design you table here and assign strings here
}

Thats the problem. I am able to construct a table but with only 1 cell. Howto construct the table here so that it is dynamically constructed as usually happens ?

Web_Sailor 0 Junior Poster

Why don't you go for AJAX for reading txt file every time with out refreshing your page.
Google for AJAX Tutorials...

Have come up with this code. Now the problem is howto generate the html table values with Ajax ? Can somebody suggest howto incorporate file reading dynamically and html table generation. There are few things I want this program to do:-

To read multiple fields from a file. So howto pass multiple parameters and then read them while putting inside html table

This is the JSP index page

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>

        <script type="text/javascript">
                 var xmlhttp

                 function loadContent(str){
                     xmlhttp=GetXmlHttpObject();

                     if(xmlhttp==null){
                         alert("Your Browser does not support Ajax HTTP");
                         return;
                     }
                     var url ="loadJSP.jsp";
                     url=url+"?q="+str;
                     //url=url+"q="+str
                     xmlhttp.onreadystatechange=getOutput;
                     xmlhttp.open("GET", url,true);
                     xmlhttp.send(null);
                 }
                 function getOutput(){
                     if(xmlhttp.readyStatechange=4){
                         document.getElementById("prtCnt").innerHTML=xmlhttp.responseText;
                         var string1 = document.getElementById("prtCnt").innerHTML=xmlhttp.responseText;
                     }
                 }
                 function GetXmlHttpObject(){
                     if(window.XMLHttpRequest){
                         return new XMLHttpRequest();
                     }
                     if(window.ActiveXObject){
                         return new ActiveXObject("Microsoft.XMLHTTP");
                     }
                     return null;
                 }
        </script>
        <script>
            function wow(){
                var mystr = document.getElementById("prtCnt").innerHTML=xmlhttp.responseText
                return  document.write(mystr);
            }
        </script>
    </head>
    <body>
        <a href="javascript:loadContent('parameterValue')">Load Ajax Content</a>
        <table border ="3"><div>

         <tr><td id="prtCnt"></td></tr>
      </div>
        </table>
    </body>
</html>

This is the other JSP program

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<%
  String q = request.getParameter("q");

  //String str = "Loading JSP String from Ajax: Loading......";
  String[] str = {"one","two","three"};
  java.util.Date dt = new java.util.Date();
  for(int i=0; i<str.length; i++){
  out.println(str[i]);
  }
  out.println(dt);

Please suggest howto enhance this basic program

Web_Sailor 0 Junior Poster

Hi,


I have a submit button in my JSP page. I also have drop down menus and text area in my form. Now my condition is like if drop down values or text area are null in this case if a user wants to submit he should get an alert message to fill the parameters first and it should stay on the same page.

Any suggestions ?

Thanks

Web_Sailor 0 Junior Poster

Hi...

I am creating an HTML Table in my JSP page taking values from text file. Now the problem comes when I read the file again to update the Table content. In this case I have to refresh my whole page to see updated Table. :icon_cry:

How can I refresh only the Table part of page without refreshing the whole page ? :?:

Would appreciate suggestions. :idea:

Thanks

Web_Sailor 0 Junior Poster

Thanks Shanti .... It really helped. Why didn't I think that ... lol.
Perhaps because I am new to JSP.

Thanks

Web_Sailor 0 Junior Poster

Hi :-/

I have a java function that I want to call inside my JSP page. My function has got parameters.Now the problem is I cannot call it using JavaScript and if I put it inside <% %> tags it just executes while loading the webpage itself. I need to call my java function with a button.

Would appreciate some guidance :)

Thanks

Web_Sailor 0 Junior Poster

Actually I am using it like this and the inner if loop is creating problems for me

int count = 0;
          while(pch != NULL)
          {
             if(++count){
                          for ( int i = 0 ; i < vec.size(); i++ ){
                                 if(count==vec[i]){
                                            cout << vec[i] << endl;
                                            vec.push_back(pch);
                                 }
                          } 
              }
                 pch = strtok(NULL,"\t");
          }

It works fine when I comment //if(count==vec)

Web_Sailor 0 Junior Poster

Hi,

I want to prevent the sorting and preserve the original order in my container. below is the example.
How can I do it ?

   string one = "6";
   string two = "7";
   string three = "2";
   string four = "8";

   veck.push_back(one);
   veck.push_back(two);
   veck.push_back(three);
   veck.push_back(four); 

   veck.push_back("9");
   veck.push_back("12");
   veck.push_back("13");
   veck.push_back("5");



   I want to preserve the order of elements in my Vector which should be:-

   6, 7, 2, 8, 9 ,12 ,13, 5

   but when I try to insert into some other container using for loop it becomes sorted :

   2, 5, 6, 7, 8, 9, 12, 13

   e.g, 

   for(int i =0; i < veck.size(); i++){
       newVec.push_back(veck[i]);
   }

   Howto preserve the order of elements in my original container and avoid sorting ?

Thanks

Web_Sailor 0 Junior Poster

Hi,

kirennian commented: really? :/ +0
Web_Sailor 0 Junior Poster

Hi :)

I am using basic replace function but getting some runtime error as below:-

terminate called after throwing an instance of 'std::out_of_range'
  what():  basic_string::replace
Aborted

I already know the position where I should replace so don't need to find it. Can somebody tell me how to avoid this error ? :icon_evil:

Here is my code:-

#include<iostream>

#include<string.h>

#include<fstream>

#include <stdlib.h>

using namespace std;

int main(int argc ,char* argv[]){

       string line1;

	   ifstream myFile(argv[1]);

	   if(! myFile){

	      cout << "Error opening file" << endl;

		  return -1;

	   }

	   while(! myFile.eof()){

	       getline(myFile, line1);
			 line1.replace(10, 1, "W");
                         cout << line1 << endl;

	   }

	   myFile.close();
    return 0;

}

Thanks ;)

Web_Sailor 0 Junior Poster

Hi,

I need to create a user name and password login client server. Attached is my attempt. This is my first try on socket and network programming in C. I have reached to a certain level but just a little problem is stopping me because of less C knowledge. I need to compare my inbuilt user names with the user cin strings.

like

user name = one
password = 1

user name = two
password = 2

How do I modify my code to do that.

Attached is my client and server.

/* A simple server in the internet domain using TCP
   The port number is passed as an argument */
#include <stdio.h>
#include <string.h>
#include <sys/types.h> 
#include <sys/socket.h>
#include <netinet/in.h>


void error(char *msg)
{
    perror(msg);
    exit(1);
}

int main(int argc, char *argv[])
{
     int sockfd, newsockfd, portno, clilen;
     char buffer[256];
     //const char* const CONST_STRING = "somename";



     struct sockaddr_in serv_addr, cli_addr;
     int n;
     if (argc < 2) {
         fprintf(stderr,"ERROR, no port provided\n");
         exit(1);
     }
     sockfd = socket(AF_INET, SOCK_STREAM, 0);
     if (sockfd < 0) 
        error("ERROR opening socket");
     bzero((char *) &serv_addr, sizeof(serv_addr));
     portno = atoi(argv[1]);
     serv_addr.sin_family = AF_INET;
     serv_addr.sin_addr.s_addr = INADDR_ANY;
     serv_addr.sin_port = htons(portno);
     if (bind(sockfd, (struct sockaddr *) &serv_addr,
              sizeof(serv_addr)) < 0) 
              error("ERROR on binding");
     listen(sockfd,5);
     clilen = sizeof(cli_addr);
     newsockfd = accept(sockfd, 
                 (struct sockaddr *) &cli_addr, 
                 &clilen);
     if (newsockfd < 0) 
          error("ERROR on accept");
     bzero(buffer,256);
     n = read(newsockfd,buffer,255);
     if (n < 0) error("ERROR reading from socket");
     //char inter[] = buffer;
     //if (strcmp(buffer,CONST_STRING) …
Web_Sailor 0 Junior Poster

Thanks a lot James :). It works ;). IT was a great learning experience for me since I had never used SwingWorker before :icon_evil:.

Web_Sailor 0 Junior Poster

Thanks James. I am able to execute my long process in swingworker thread. Now the other problem is that I am able to run my function only once. It does not execute when i try to run it again using my JButton.

I just read that "SwingWorker is only designed to be executed once. Executing a SwingWorker more than once will not result in invoking the doInBackground method twice. "

In this case how can I run my code which uses swingworker multiple times like suppose using my JButton ? Is there any way ?

Thanks for all your help

Web_Sailor 0 Junior Poster

Hi James is there any other way to make it visible ? Can you give me some example

Web_Sailor 0 Junior Poster

Hi gurus's :cool:

I have got an actionListner in my code. The problem is that when I try to set my JLabel as true it does not work and does not show up in the GUI ? :@

Button.addActionListener(
 new ActionListner(){
   public void actionPerformed(ActionEvent e){

       label.setVisible(true);
       myFunction() //here's some timeconsuming Function called.
       label.setVisible(false);

   }
 });

Now if I add a second actionListener to the same Button the Label works but requires 2 Mouse Presses which is bad :(

Why is it happening so and how can I get it work the way I want ? :-/

Thanks :confused:

Web_Sailor 0 Junior Poster

Ok guys .... Solved myself .. Thanks :twisted:

Web_Sailor 0 Junior Poster

Hi.. :?:

I have written a program that reads a file and loads it into the 2D matrix but the problem is that it only loads the first line into 2D Matrix and duplicates the same. Can somebody point out the mistake.

Here is my input file

14	12	5	4	6
10	9	4	3	10
9	5	2	13	2
14	14	10	12	2
9	1	3	12	2

Here is my faulty output:-

mazeLine = [[14, 12, 5, 4, 6], [14, 12, 5, 4, 6], [14, 12, 5, 4, 6], [14, 12, 5, 4, 6], [0, 0, 0, 0, 0]]

Below is my code:-

public class Reader {
    
    public Reader(){
    }

    public static void main(String args[]) throws FileNotFoundException, IOException{
        BufferedReader br = new BufferedReader(new FileReader("test.txt"));
        int[][] mazeLine = new int[0][];
        String line = br.readLine();
        String[] tokens = line.split("\t");
        //int width  = Integer.parseInt(tokens[0]);
        //int height = Integer.parseInt(tokens[1]);
        int width = 5;
        int height = 5;
        //line = br.readLine();
        //line = br.readLine();
        // use mazeLine to read in the grid data from the file
        mazeLine = new int[height][width];
        int row = 0;
        while((line = br.readLine()) != null) {
            //tokens = line.split("\t");
        // for(int row =0; row < tokens.length; row++)  {
            for(int j = 0; j < tokens.length; j++) {
                mazeLine[row][j] = Integer.parseInt(tokens[j]);
            }
         //}
            row++;
        }
        br.close();
        System.out.printf("mazeLine = %s%n", Arrays.deepToString(mazeLine));
        //Add first line into array
//        int firstLine = mazeLine.length;

    }
}

Thanks ;)

Web_Sailor 0 Junior Poster

Hi ..

I tried another way like this:-

#include <iostream>
#include <vector>
#include <map>
#include <set>
using namespace std;

int main ()
{
  multimap<string,int> mm;
  multimap<string,int>::iterator it;
  multimap<vector<string>,multimap<string,int> > mymm;
  multimap<vector<string>,multimap<string,int> >::iterator itx;
 
  vector<string> v1;
  vector<string>::iterator itv;

  

  pair<multimap<vector<string>,pair<string,int> >::iterator,multimap<vector<string>,pair<string,int> >::iterator> ii;


  mm.insert(pair<string,int>("a",10));
  mm.insert(pair<string,int>("b",20));
  mm.insert(pair<string,int>("c",30));
  mm.insert(pair<string,int>("d",40));
  mm.insert(pair<string,int>("e",50));
  mm.insert(pair<string,int>("f",60));

  v1.push_back("1");
  v1.push_back("2");
  v1.push_back("3");
  v1.push_back("4");
  v1.push_back("5");
  v1.push_back("6");  

  mymm.insert(make_pair(v1,mm));


  for (itx = mymm.begin(); itx != mymm.end(); ++itx){

        for ( itv= v1.begin() ; itv < v1.end(); itv++ ){
             if(*itv=="1"){
                  for( it = itx->second.begin() ; it != itx->second.end() ; ++it ){
                          cout << it->first << ',' << it->second << " " ;
                          cout << '\n' ;
                  }
             }
        }
  }

  return 0;
}

The output is :-

a,10 
b,20 
c,30 
d,40 
e,50 
f,60

I expected only

a,10

since I am trying to filter using if loop like this

if(*itv=="1")

How can I get the desired results of only

a,10

Thanks

Web_Sailor 0 Junior Poster

> Its printing only the first elements

Well, you have a multimap which contains multimaps :
multimap<string,multimap<string,int> > mymm;

So you need a nested loop to print the contents of the inner multimaps. Something like:

for (itx = mymm.begin(); itx != mymm.end(); ++itx)
{
  cout << "  [" << itx->first << "] " ;
  for( it = itx->second.begin() ; it != itx->second.end() ; ++it )
        cout << it->first << ',' <<  it->second << "   " ;
  cout << '\n' ;
}

Hi.. I made some changes like this:-

for (itx = mymm.begin(); itx != mymm.end(); ++itx){

    if(itx->first.compare("1")==0){
             cout << " [" << itx->first << "] " ;
       for( it = itx->second.begin() ; it != itx->second.end() ; ++it )
             cout << it->first << ',' << it->second << " " ;
             cout << '\n' ;
       }
     }

I am getting results like below:-

[1] b,20 b,30 b,40 c,50 c,60 d,60 
 [1] b,20 b,30 b,40 c,50 c,60 d,60

But I want the results to come like this:-

[1] b,20 
 [1] b,30

How can I do that ?
Thanks

Web_Sailor 0 Junior Poster

Hi,

I have a written a program using multimap and its not giving me the results I am expecting. I have used pair in my program. There is some problem which I am unable to figure out. Perhaps I am using pair for the first time with multimap.

Here is my code:-

#include <iostream>
#include <map>
#include <set>
using namespace std;

int main ()
{
  multimap<string,int> mm;
  multimap<string,int>::iterator it;
  multimap<string,multimap<string,int> > mymm;
  multimap<string,multimap<string,int> >::iterator itx;

  pair<multimap<string,pair<string,int> >::iterator,multimap<string,pair<string,int> >::iterator> ii;


  mm.insert(pair<string,int>("b",20));
  mm.insert(pair<string,int>("b",30));
  mm.insert(pair<string,int>("b",40));
  mm.insert(pair<string,int>("c",50));
  mm.insert(pair<string,int>("c",60));
  mm.insert(pair<string,int>("d",60));

  mymm.insert(make_pair("1", mm));
  mymm.insert(make_pair("1", mm));
  mymm.insert(make_pair("2", mm));
  mymm.insert(make_pair("2", mm));
  mymm.insert(make_pair("3", mm));
  mymm.insert(make_pair("3", mm));


for (itx = mymm.begin(); itx != mymm.end(); ++itx)
{
  cout << "  [" << itx->first << "] " << itx->second.begin()->first << " " <<  itx->second.begin()->second << endl;
}

  return 0;
}

Here are the results:-

[1] b 20
  [1] b 20
  [2] b 20
  [2] b 20
  [3] b 20
  [3] b 20

Its printing only the first elements

[1] b 20

I expect the results like this:-

[1] b 20
  [1] b 30
  [2] b 40
  [2] b 50
  [3] b 60
  [3] b 60

I would actually like to filter my results like suppose I want only keys with "2" to be printed:-

[2] b 40
  [2] b 50

Thanks

Web_Sailor 0 Junior Poster

Thanks guys. Appreciate your help.:P

Web_Sailor 0 Junior Poster

1) In my version I'd use a third vector to hold the results which eleminates to erase from either of the two source vectors, but you can do it as you please. Are duplicates allowed in either of the source vectors or the result vector?
2) use two iterators, one to traverse each vector each vector.
3) check each vector to see if either is empty before entering the following loop
4) use a nested loop so that you compare element of vec1 with each element of vec2. If any two elements are equal then don't add the current vec1 element to the result vector. This will look for elements in vec1 not in vec2
5) then do the loops over again comparing each element of vec2 with each element of vec1. This will look for elements in vec2 not in vec1
6) at the end of the looping you can display the result vector.

Hi duplicates are not allowed in my case:-

I tried something like this. Near the solution i guess ;-)
I want only

E
F
G
H

to be printed but its printing

B
C
D
E
F
G

How can I get that ?

#include<iostream>
#include<string>
#include<vector>
using namespace std;

int main(){

           vector<string> v1;
           vector<string> v2;
           vector<string>::iterator iter1;
           vector<string>::iterator iter2;		   

           v1.push_back("A");
           v1.push_back("B");
           v1.push_back("C");
           v1.push_back("D");

           v2.push_back("A");
           v2.push_back("B");
           v2.push_back("C");
           v2.push_back("D");
           v2.push_back("E");
           v2.push_back("F");
           v2.push_back("G");


  // assign elements in vector a value
  iter1 = v1.begin();
  iter2 = v2.begin();
  
  int …
Web_Sailor 0 Junior Poster

Hi,

I am trying to compare 2 vectors to remove any kind of overlap. I have written a simple program but it gives a segmentation fault once I increase / decrease number of vector elements in both.

Is there a better way of doing this. Especially suppose one of the vector is empty or both are empty my program won't work. Can anybody help.

Here is my program:-

#include<iostream>
#include<string>
#include<vector>
using namespace std;

int main(){

           vector<string> v1;
           vector<string> v2;

           v1.push_back("A");
           v1.push_back("B");
           //v1.push_back("C");
           //v1.push_back("D");

           v2.push_back("A");
           v2.push_back("B");
           v2.push_back("C");
           v2.push_back("D");
           //v2.push_back("E");
           //v2.push_back("F");
           //v2.push_back("G");

           vector<string>::iterator iter = v2.begin();

    while( iter != v2.end() )
    {
         for(int i=0; i<v1.size(); i++){
            if (*iter == v1[i]){
                    iter = v2.erase( iter );
            }
            else{
                 ++iter;
            }
         }
    }

     for(int i=0; i<v2.size(); i++){
          cout << v2[i];
          cout << endl;
     }

}

In this program output is correct:-

C 
D

but if I increase or decrease elements the problem starts and gives segmentation faults.

Thanks

Web_Sailor 0 Junior Poster

Hi all,

I have a java swing based client server application. The GUI is in swing and I am using glass fish as my server. Is there a way or any software available to create an environment where I can test my application by creating virtual user connections so that I can perform a load test.

Also is there a software for regression test on this kind of swing application.

Thanks

Web_Sailor 0 Junior Poster

Hi gurus,

I have a simple question regarding file parsing. I am trying to parse a file and store the fields I require in a multimap. Now I want to pass an array which is of int type and specifies field number to be extracted in a file. I am able to do it to some extent but here I am able to pass only the first value of an array correctly which specifies a field number.

To simplify things here is what i am doing:

suppose my input file:-

aaa	bbb	ccc	ddd	111	222	333
eee	fffff	gg	hhh	444	555	666
iiiiiii	jjjjj	kk	llllllll	777	888	999

Now my 5 strings field1, field2, field3, field4, field5 are quite straight forward which will take the first 5 fields of input file and store them into the multimap as following:-

aaa	bbb	ccc	ddd	111
eee	fffff	gg	hhh	444
iiiiiii	jjjjj	kk	llllllll	777

Now the most important thing comes in the addfields string. Here I want to store fields based on the input fields given in the array

arr[]

which is a function argument. So as my int values in main for

arr[]

are

arr[] = {6,7}

so I want my addfields string to contain both the fields and store in a multimap.

What I mean is 6th and 7th field should be added to addfields string so that it can have values

222	333
555 …
Web_Sailor 0 Junior Poster

Hi,

I am trying to solve a riddle. I am passing a value to multimap like this:-

combined = string1+"\t"+string2
and then setting the output to fix size using maximum length and

cout.width(combined.length()) 
cout.fill(' ')

The problem is that the fixed length format is not coming properly but when I use a space instead of tab I get the output correctly:-

combined = string1+"    "+string2.

Then I print it like below.

for (it=(mmx.begin()); it!=(mmx.end()); it++){ 
   cout.width(MaxStringSize1);
   cout.fill('0');
   cout << it->first <<"\t";
   cout.width(MaxStringSize2);
   cout.fill(' ');
   cout << it->second << endl;
 }

The output comes perfectly. Can somebody tell me why is multimap not taking the tab ? whereas it works perfectly with spaces ?

Thanks

Web_Sailor 0 Junior Poster

So just to clarify in your example the output should look like:

<space><space>y12-100<space> z1234-250<space><space>  x1adsf-5
<space><space>y12-150<space> z1234-300
 <space><space>y12-200

this? (with width = 8)

I'm just a tad confused...

It should be like this.

x1adsf-50
   y12-100
   y12-150
   y12-200
 z1234-250
 z1234-300
Web_Sailor 0 Junior Poster

Hi,

I have a data I want to make fix length records Like suppose:-

one two three four
one two three
one

In this case the fixed length should be of the maximum string length which is of the first line. My code below is giving creating faulty fix lengths. Can somebody help.

so the output will be like this

one two three four
     one two three
               one

Here is my code and I have to do it with multimap:-

#include <iostream>
#include <map>
#include <string>
#include <algorithm>
using namespace std;

 bool pairStringComp(pair<string,int> i,pair<string,int> j){ //compare pairs by string size
  return i.first.size()<j.first.size();
 }

 int main(){

 multimap<string,int> mymm;
 multimap<string,int>::iterator it;

 mymm.insert(pair<string,int>("x1adsf",50));
 mymm.insert(pair<string,int>("y12",100));
 mymm.insert(pair<string,int>("y12",150));
 mymm.insert(pair<string,int>("y12",200));
 mymm.insert(pair<string,int>("z1234",250));
 mymm.insert(pair<string,int>("z1234",300));

  int maxStringSize=max_element(mymm.begin(), mymm.end(),pairStringComp)->first.size(); 

 for (it=(mymm.begin()); it!=(mymm.end()); it++){ //cout pairs sorted lexicographically
   cout.width(maxStringSize);
   cout<<it->first<<"-"<<it->second<<endl;
 }
    return 0;
 }

Thanks

Web_Sailor 0 Junior Poster

Hi,

I have a jRadiobuttongroup. I have 3 types of jradiobuttons in my group.

A     B     C
1     1    1
2     2    2
3     3    3
4     4    4

Now the problem is that when I selected suppose A type of buttons
some of the A type buttons get selected by themselves randomly even though i don't select them. I want to control it in the way that if I click on 3 in A type it should stay while I click the B suppose 2 but what happens is that randomly some buttons are getting selected which are creating a great amount of confusion.

What should I do to stop such a behaviour of getting randomly selected on their own ?

Here is the jRadiobuttongroup code:--

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.JRadioButton;
import javax.swing.JButton;
 
public class MixedButtons extends javax.swing.JFrame {
 
	public MixedButtons() {
		super("JRadioButtonTable Example");
		DefaultTableModel dm;
                dm =new DefaultTableModel(new Object[][]{},new Object[] {"Serial"});
                dm= new DefaultTableModel(new Object[][]{
                                 {new String("one")},
				 {new String("two")},
				 {new String("three")},
				 {new String("four")},
			         {new String("five")}},
		    new Object[]{"Question", "Answer"});
                //dm.insertRow(0, new Object[] { "r1" });
                //dm.addColumn("Serial");
		JTable table = new JTable(dm);
                //table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		String[] answer = {"A", "B", "C"};
                String[] keyword = {"Yes"};
	        table.getColumn("Answer").setCellRenderer(new RadioButtonRenderer(answer));
		table.getColumn("Answer").setCellEditor(new RadioButtonEditor(new RadioButtonPanel(answer)));
                

     
		setContentPane(new JScrollPane(table));
	}
 
	// Cell base
	class RadioButtonPanel extends JPanel {
		private JRadioButton[] buttons;
		private JRadioButton noSelectionButton;
 
		RadioButtonPanel(String[] str) {
			setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
			buttons = new JRadioButton[str.length];
			ButtonGroup group = new ButtonGroup();

			noSelectionButton = new JRadioButton();
			group.add(noSelectionButton);                       
			for (int i = …
Web_Sailor 0 Junior Poster

Hi :)
I was trying to find the max length in my multimap.
here is how I define it:

multimap<int, string> mm;
multimap<int,string>::iterator it;

mm.insert(pair<int, string>(some_int, myvalues));

Now the main part that I want to discuss is this. I have created 2 functions to find the size of records in my multimap. These functions work fine for me when I use

multimap<string, string>

but when I use int type they give me compile time erros:-
Something like below

error: request for member ‘size’ in ‘i.std::pair<int, int>::first’, which is of non-class type ‘int’

Can somebody tell me how to make it work for multimap<int, string> type also ? :-/

Below are my functions for maxlength finding. Fisrst one is faultty and the 2nd one works:-

bool maxlengthfirst(std::pair<int, int> i,std::pair<int, int> j){ 

              return i.first.size()<j.first.size();

  }



  bool maxlengthsecond(pair<string,string> i,pair<string,string> j){ 

              return i.second.size()<j.second.size();

  }

Ultimately I want to use it like this and it works for <string,string> type of multimap:

for (it=(mm.begin()); it!=(mm.end()); it++)

          {

               cout.width(secondSize);

               cout.fill('0');              

               cout << it->first <<"\t";

               cout.width(firstSize);

               cout.fill(' ');

               cout << it->second << endl;

          } 

  mm.clear();
}

Thanks :icon_razz:

Web_Sailor 0 Junior Poster

Hi,

I want to change the color of a selected jradiobutton in a button group to RED when clicked on it. I am not able to do it make it happen till now. The problem is actually that when I select any jradiobutton the selection spot should stay and get blocked at that particular radiobutton. Its not happening so I thought lemme try with color change atleast .Here is my ActionListener code:-

public void actionPerformed(ActionEvent e) {
                                if(e.getActionCommand().equals("myJRadioButton")){ 
       JRadioButton source = (JRadioButton)e.getSource();
       source.setFocusPainted(true);
       source.setEnabled(false);
       //ButtonModel model = source.getModel();
       //Group.setSelected(model, true);                                                           
}
}

So how do I set the focus only to the selected button and freeze it there or change the color of the selected button to show that it was selected by user ?

Thanks in advance

Web_Sailor 0 Junior Poster

Lets suppose this code. My requirement is like the code below. Is there a way I can do such a thing using vector ? without loading into memory ?

// multimap::count
#include <iostream>
#include <map>
#include<vector>
#include<string>
using namespace std;

int main ()
{
  multimap<string,string> mymm;
  multimap<string,string>::iterator it;
  vector<string> vec1;
  vector<string>::iterator itv;

  mymm.insert(pair<string,string>("andrew","andrew S* years old"));
  mymm.insert(pair<string,string>("peter","peter 1 years old"));
  mymm.insert(pair<string,string>("peter","peter 2 years old"));
  mymm.insert(pair<string,string>("peter","peter 3 years old"));
  mymm.insert(pair<string,string>("mathew","mathew 1 years old"));
  mymm.insert(pair<string,string>("mathew","mathew 2 years old"));
  mymm.insert(pair<string,string>("Dsouza","Dsouza S* years old"));
  mymm.insert(pair<string,string>("Austin","Austin 1 years old"));
  mymm.insert(pair<string,string>("Austin","Austin 2 years old"));
  mymm.insert(pair<string,string>("Austin","Austin 3 years old"));
  mymm.insert(pair<string,string>("Austin","Austin 4 years old"));
  mymm.insert(pair<string,string>("Austin","Austin 5 years old"));
  mymm.insert(pair<string,string>("David","David S* years old"));
  mymm.insert(pair<string,string>("John","John 1 years old"));
  mymm.insert(pair<string,string>("John","John 2 years old"));

  vec1.push_back("Austin");
  vec1.push_back("andrew");
  vec1.push_back("David");
  vec1.push_back("peter"); 
  vec1.push_back("mathew");
  vec1.push_back("Dsouza");
  vec1.push_back("John");
                             
    for(itv=vec1.begin(); itv < vec1.end(); itv++)
  {
       int i = 0;
       int k = 0;
    for (it=mymm.equal_range(*itv).first; it!=mymm.equal_range(*itv).second; ++it)
      if((int)mymm.count(*itv)>2){      
         if(i==0){
            cout << "one"<<"\t"<<(*it).second << endl;
         }    
         else if(i>0 && i < ( mymm.count(*itv) - 1)){
            cout << "middle"<<"\t"<<(*it).second << endl;
         }
         else if(i !=0 ){     
            cout << "end"<<"\t"<<(*it).second << endl;
         }
       i++;
      }
      else if((int)mymm.count(*itv)==1){      
            cout << "Single"<<"\t"<<(*it).second << endl;   
      }
      else if((int)mymm.count(*itv)==2){      
         if(k==0){
            cout << "one" << "\t"<< (*it).second << endl;
         }
         else {
            cout << "end" << "\t" << (*it).second << endl; 
         } 
         k++;
      }
  }
  return 0;
}

Thanks

Web_Sailor 0 Junior Poster

Hi :icon_smile:

I have written a C++ program which works very fine. The problem comes in terms of efficiency and speed. I am using a multimap which is required for my type of requirement.

multimap<string,string>

Now the problem is that for files more than 100 MB it takes a lot of time to load the data into multimap which slows down the program.

I am inserting Strings into the multimap. I even used references of string for insertion into multimap but not of much help.

My question is more conceptual. So what do I need to do to speed up my program ?

If I insert my strings into a vector and then insert that vector into multimap - will that increase the speed of my program ?

I mean something like this:

multimap<vector<string>,vector<string>>

Would appreciate any advice

Thanks in advance :-/

Web_Sailor 0 Junior Poster

Hi,

I am struggling with a Layout problem. Here is the definition of the problem:-

1) I have a JFrame where I specify space alignment in GroupLayout for JScrollPane as per the other (JButton/ comboBox etc..). My JScrollPane contains a JTable. I use get and set methods to set scrollpane values which is created in the JFileChooser code.

2) Now while updating my JTable content using JFileChooser. I create JScrollPane and add it to the JFrame outside JFileChooser:-
Here is my JFileChooser code snippet.

constructTable(filename);
               scroll = new JScrollPane(table);
               setScrollPane(scroll);
                //JFrame.add(scroll);
               jframe.repaint();

Later I add it outside JFilechooser to the GroupLayout which is then added to the jframe

jframe.add(grouppanell);

The problem is that when the JTable is added after the Jfilechooser adds a file. The ScrollPane comes always at the top thus dismantling all my grouplayout alignment.

Now one solution to it is if I specify the scrollpane Layout using GridBagLayout in the JFileChooser code itself but when I maximize or minimize the wiindow again The Layout alignments are destroyed and scrollpane dissappears. When I click it appears again.

Jframe.setLayout(new GridBagLayout());
                GridBagConstraints c = new GridBagConstraints();
                boolean shouldFill = true;
                if (shouldFill) {
		//natural height, maximum width
		c.fill = GridBagConstraints.HORIZONTAL;
                }
                c.fill = GridBagConstraints.HORIZONTAL;
                c.ipady = -102;      //make this component tall
                c.weightx = 0.0;
                c.gridwidth = 0;
                c.gridx = 0;
                c.gridy = 0;
                jframe.add(scroll, c);//This way works but scrollpane disaapears when maximize window

This way works where I use GridbagLayout and scrollpane …

Web_Sailor 0 Junior Poster

I want to control the number of clicks in my button group which is inside DefaultTableModel of JTable. Like only one click for a certain Radiobutton.

Suppose I have 3 radio buttons in a button group:

1) A
2) B
3) C

If a user clicks A he can select it only once by one click. For Second or third click it gets blocked. Now the problem is that I am not able to use

e.getClickCount()

method in my Button group Actionlistner.

Here is my code.
JTable MouseListner:-

jtable.addMouseListener(new MouseListener() {
            public void mouseClicked(MouseEvent evt) {}
            public void mouseEntered(MouseEvent evt) {}
            public void mouseExited(MouseEvent evt) {}
            public void mousePressed(MouseEvent e) {
                int selectRow,selectColumn;
                Point p = e.getPoint();
                selectRow = getTable().rowAtPoint(new Point(e.getX(),e.getY()));
                if(e.getClickCount() == 1) {
                row = selectRow+1;
                setRow(row);
                }
                else if(e.getClickCount() > 2) {System.out.println("NOT ALLOWED");}
                }
             public void mouseReleased(MouseEvent evt) {}
            });

For jButton ActionListner like this:-

buttons[i].addActionListener(new java.awt.event.ActionListener() {
                                     public void actionPerformed(ActionEvent e) {
                                         if(e.getActionCommand().equals("myRadioButton")){
                                             //System.out.println("value");
                                             if (e.getClickCount() == 1) {}
                                             System.out.println(getRow());
                                             buttons[1].setEnabled(false);
                                         }
                                     }
                                     });

Would appreciate any help :P

Thanks

Web_Sailor 0 Junior Poster

I have got a problem with the layouts. I am creating a Grouplayout for my JLabels / Buttons etc in a window .. Then I am adding a Jtable using the JFileChooser for which I am specifying GridBagLayout and then adding the layout to Jframe again after JFilechooser creates a JTable calling the Table creation function. Also one more problem is that for once the JfileChooser creates the JTable fine but when the I choose another file with file chooser the First JTable doesn't refresh and the second JTable just distorts the format. How do I refresh the JTable after I select the other file ?

All formats work fine the way I am doing now but when I click to maximize the window the whole JTable Layout is gone or lost somewhere ! Sometimes something mistereous like JTable appears when I click on the Window.

I have a separate GroupLayout for the rest of the JButtons / JLabels / Jcomboboxes... in my window which I add to the Jframe (fr) here. I create a GroupLayout like below for the rest of stuff like this:-

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(panel); // rest of the stuff in my window except Jtable.

I just keep a space in my window to accomodate JTable and then set the layout using GridBagLayout in my JFileChooser code.

Then I add separate GridBagLayout for my JTable.

Here is my JFileChooser code where I am creating a layout for my JTable.


       
Web_Sailor 0 Junior Poster

Yes I removed final from DefaultTableModel...

Web_Sailor 0 Junior Poster

Hi I changed my getter and setter methods like this but still no success :(

public JTable getTable(){
         return this.table;
     }
     public void setTable(JTable table){
          this.table = table;
     }
Web_Sailor 0 Junior Poster

Actaully I am trying to do something like this link below.

http://www.java2s.com/Code/Java/Swing-Components/RadioButtonTableExample.htm

Where my first line of file will be the first field of Jtable and then second field will be my selections buttons.

Thanks

Web_Sailor 0 Junior Poster

Great !! It helped me a lot to organize my code ... really helpful.
One more thing I just want to show the first line of a file in JTable thats why I am using if loop with scanner. I did all the changes you said but still not able to make the data appear in JTable. The System.out.println is printing all my fields correctly but not able to fill the table. What could be the reason.

Thanks in advance

Web_Sailor 0 Junior Poster

Ya I corrected that initialization problem. Now I am not getting any runtime errors but my table is still not been filled after selecting the file. I think there is some minor problem that I am not looking at. Can you please help me to point it out. Here is the modified code:-

import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.Font;
import java.awt.font.TextAttribute;
import java.text.AttributedString;
import javax.swing.AbstractCellEditor;
import javax.swing.JFileChooser;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableColumn;

/**
 * 
 */
public class TEST {
     public static JFrame fr = new JFrame("Item Menu");
     Container c = new JPanel();
     //public JFileChooser fc;
     JTable table;// = new JTable();
     JScrollPane scroll = new JScrollPane();
     
     public JTable getTable(){
         return table;
     }
     public void setTable(JTable table1){
          table1 = table;
     }
   
     public JScrollPane getScrollPane(){
         return scroll;
     }
     public void setScrollPane(JScrollPane scroll1){
          scroll1 = scroll;
     }
     
  public TEST() {
    JLabel jLabel1= new JLabel("Item Name");
    JLabel jLabel4= new JLabel("File Name");
 
    JLabel jLabel7 = new javax.swing.JLabel();
    JButton jButton3 = new javax.swing.JButton();
    jLabel7.setText("List :");
    jButton3.setText("Browse");
 
    //jButton3.addMouseListener(new FileOpenMouseListener());
    jButton3.addActionListener(
         new ActionListener() {
           public void actionPerformed(ActionEvent e) {
               JFileChooser fileChooser = new JFileChooser(".");
               int status = fileChooser.showOpenDialog(c);
             if (status == JFileChooser.APPROVE_OPTION) {
                File file = fileChooser.getSelectedFile();
                constructTable(file);
                //JTable table = new JTable(); 
                JScrollPane scroll = new JScrollPane(getTable());
                setScrollPane(scroll); …
Web_Sailor 0 Junior Poster

Hi,

I am trying to develop an application that has got a Jbutton and allows to search a file and then loads selected line of that file in the JTable. I am able to do that when I hard code it inside the code but when I try to let the user do it by adding FileChooser I am able getting runtime error like this:-

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
        at Testing.TableCreator$1.actionPerformed(TableCreator.java:69)
        at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
        at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
        at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
        at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
        at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
        at java.awt.Component.processMouseEvent(Component.java:6041)
        at javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
        at java.awt.Component.processEvent(Component.java:5806)
        at java.awt.Container.processEvent(Container.java:2058)
        at java.awt.Component.dispatchEventImpl(Component.java:4413)
        at java.awt.Container.dispatchEventImpl(Container.java:2116)
        at java.awt.Component.dispatchEvent(Component.java:4243)
        at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
        at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
        at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
        at java.awt.Container.dispatchEventImpl(Container.java:2102)
        at java.awt.Window.dispatchEventImpl(Window.java:2440)
        at java.awt.Component.dispatchEvent(Component.java:4243)
        at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
        at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
        at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
        at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)

Here is the line the error report is referring to :-

File file = fc.getSelectedFile();

Can somebody guide me where am I making mistakes ?
Here is my code below:-

public class TableCreator {
     public static JFrame fr = new JFrame("Item Menu");
     Container c = new JPanel();
     public JFileChooser fc;
     public JTable table;
  public TableCreator() {
    JLabel jLabel1= new JLabel("Item Name");
    JLabel jLabel4= new JLabel("File Name");

    JLabel jLabel7 = new javax.swing.JLabel();
    JButton jButton3 = new javax.swing.JButton();
    jLabel7.setText("List :");
    jButton3.setText("Browse");

    //jButton3.addMouseListener(new FileOpenMouseListener());
    jButton3.addActionListener(
         new ActionListener() {
           public void actionPerformed(ActionEvent e) {
               JFileChooser fileChooser = new JFileChooser(".");
               int status = fileChooser.showOpenDialog(c);
             if (status == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                constructTable(file);
                JScrollPane scroll = new JScrollPane(table);
                c.add(scroll);
                //c.pack();
             } else if (status == JFileChooser.CANCEL_OPTION) { …
Web_Sailor 0 Junior Poster

Hi. I am trying to browse a file and use the path variable in my File code. Both the things are in same class. The problem is that I am getting NullPointerException.

Please check if I am doing it correctly

Here the code snippet

I am declaring

public class MyClass extends JFrame {
                public String mypathfile;
  public MyClass() {......}

after my class declaration itself

jButton3.addActionListener(
         new ActionListener() {
           //public String mypathfile;// =  toString();
           public void actionPerformed(ActionEvent e) {
               JFileChooser fileChooser = new JFileChooser(".");
               int status = fileChooser.showOpenDialog(null);

             if (status == JFileChooser.APPROVE_OPTION) {
               File selectedFile = fileChooser.getSelectedFile();
               //System.out.println(selectedFile.getParent());
               //System.out.println(selectedFile.getName());
               //System.out.println(selectedFile.getAbsolutePath());
               mypathfile = selectedFile.getAbsolutePath();
               //System.out.println(mypathfile);
             } else if (status == JFileChooser.CANCEL_OPTION) {
               System.out.println("canceled");
             }
              }
        }
       );

            //File file = new File("inputfile.txt");
             File file = new File(mypathfile);
             System.out.println("The file path is : "+mypathfile);

        try {

            Scanner scan = new Scanner(file);
            if (scan.hasNextLine()) {
                String line = scan.nextLine();
                //System.out.println(line);

............................

         
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

Thanks

Web_Sailor 0 Junior Poster

Why not stick with the ButtonGroup? You can put both radio buttons and check boxes in the button group just fine. CheckboxGroup is for use with AWT Checkbox.

(By the way, you forgot

add(noSelectionButton);

in your code above. You created the button but didn't add it to the panel.)

Hi.. Ok. I am now using only ButtonGroup. Yes I was wrong CheckboxGroup is used in AWT. Now I modified my code and I am now creating jbuttons separately and jcheckbox separately but the problem now that is coming is I am not able to set the width of my column ? I tried out many examples but not able to make it work.

I have 3 columns in JTable Question, Answer and Clown as per my Object[] string. I am keeping my checkbox in Clown. Now the problem is that I am unable control the Clown width.I have set table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF). All the columns are coming of eqaul size. . Howto make it work ? Please check my code below.

Here is my code below:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.JRadioButton;
import javax.swing.JButton;
 
public class MixedButtons extends javax.swing.JFrame {
 
	public MixedButtons() {
		super("JRadioButtonTable Example");
		DefaultTableModel dm = new DefaultTableModel(new Object[][]{
                                 {new String("one")},
				 {new String("two")},
				 {new String("three")},
				 {new String("four")},
			         {new String("five")}},
		    new Object[]{"Question", "Answer","Clown"});
		JTable table = new JTable(dm);
                table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		String[] answer = {"A", "B", "C"};
                String[] Clown = {"Yes"};
	        table.getColumn("Answer").setCellRenderer(new RadioButtonRenderer(answer));
		table.getColumn("Answer").setCellEditor(new RadioButtonEditor(new RadioButtonPanel(answer)));
                
                table.getColumn("Clown").setCellRenderer(new CheckBoxRenderer(Clown));
		table.getColumn("Clown").setCellEditor(new CheckBoxEditor(new CheckBoxPanel(Clown)));
     
		setContentPane(new JScrollPane(table));
	}
 
	// Cell base …
Web_Sailor 0 Junior Poster

Hi,

I am trying to create a button group which can give me both Jcheckboxes as well as Jbuttons. The problem is that I am creating a button group and not able to fit the checkbox criteria into it. Actually I want to create 2 radiobuttons followed by one checkbox

I mean something like like:-

No       Buttons
1         jbutton1      jbutton2   jcheckbox1    
2         jbutton1      jbutton2   jcheckbox1    
3         jbutton1      jbutton2   jcheckbox1

Here is how I am creating my button group:-

private JCheckBox[] buttons;
		private JRadioButton noSelectionButton;
 
		RadioButtonPanel(String[] str) {
			setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
			buttons = new JCheckBox[str.length];
			ButtonGroup group = new ButtonGroup();

			noSelectionButton = new JRadioButton();
			group.add(noSelectionButton);                       
			for (int i = 0; i < buttons.length; i++) {
				buttons[i] = new JCheckBox(str[i]);
				buttons[i].setFocusPainted(false);
				add(buttons[i]);
				group.add(buttons[i]);
			}                         
		}

I was trying to follow this example to fit my requirement but in this case I need to use CheckboxGroup whereas I am using ButtonGroup and since I am filling my buttongroup like this

group.add(buttons[i])

It is creating me problems when I declare CheckboxGroup instead of ButtonGroup.

Here is the example I am talking about :-
http://www.apl.jhu.edu/~hall/CWP-Chapter13/CWP-Chapter13.5.html

Here is my full code

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.JRadioButton;
import javax.swing.JButton;
 
public class MixedButtons extends javax.swing.JFrame {
 
	public MixedButtons() {
		super("JRadioButtonTable Example");
		DefaultTableModel dm = new DefaultTableModel(new Object[][]{
                                 {new String("one")},
				 {new String("two")},
				 {new String("three")},
				 {new String("four")},
			         {new String("five")}},
		    new Object[]{"Question", "Answer"});
		JTable table = new JTable(dm);
		String[] answer = {"A", "B", "C"};
	        table.getColumn("Answer").setCellRenderer(new RadioButtonRenderer(answer)); …
Web_Sailor 0 Junior Poster

Hi,

I am working on creating a jradiobutton group using JTable. Here is a brief definition of the problem.

My program gives an output like this:-

Questions         Answers
1                      radiobtn1     radiobtn2   radiobtn3
2                      radiobtn1     radiobtn2   radiobtn3
3                      radiobtn1     radiobtn2   radiobtn3

I am able to set horizontal control that only 1 radio button can be selected but how do I control vertically ?
As per my requirement I should allow only 1 radiobutton to be selected in a field. Even though horizontally I am doing that.

In short I mean both in rows and columns only 1 radiobutton should be selected.

Below is my code. What changes should I do ?
Also I wanted to use checkbox in for the 3rd button instead of radiobutton how can I do do that ? Since I am making a group of buttons here. Is it possible to do that ?
I mean somthing like this :-

Questions        Answers
1                      radiobtn1     radiobtn2   checkbox3
2                      radiobtn1     radiobtn2   checkbox3
3                      radiobtn1     radiobtn2   checkbox3
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.JRadioButton;
import javax.swing.JButton;
 
public class JRadioButtonTableExample2 extends javax.swing.JFrame {
 
	public JRadioButtonTableExample2() {
		super("JRadioButtonTable Example");
		DefaultTableModel dm = new DefaultTableModel(new Object[][]{
                                 {new String("Andrew")},
				 {new String("Bolon")},
				 {new String("Peter")},
				 {new String("Mathew")},
			         {new String("Austin")}},
		    new Object[]{"Question", "Answer"});
		JTable table = new JTable(dm);
		String[] answer = {"A", "B", "C"};
		table.getColumn("Answer").setCellRenderer(new RadioButtonRenderer(answer));
		table.getColumn("Answer").setCellEditor(new RadioButtonEditor(new RadioButtonPanel(answer)));
                JButton myButton = new JButton("MyQuestion");
     
		setContentPane(new JScrollPane(table));
	}
 
	// Cell base
	class RadioButtonPanel extends JPanel …
Web_Sailor 0 Junior Poster

Hi.. I have 3 JPanels. (one) JPanel contains the scrollpane and the (two) JPanel contains a JButton. I am adding (one) + (two) into (combine) JPanel and then adding to the frame.Now I am really having a hard time align the scrollpane and the Jbutton. scroll pane is coming squeezed in the center and the Jbutton is squeezing it by staying on the right hand side alongwith it. I tried many methods below commented but not able to set the location of JButton and size and position of scrollpane.
I want the scrollpane in the center and button on the buttom.

Can anybody suggest whats going wrong ?

JScrollPane scroll = new JScrollPane(table);
    Container contentPane = getContentPane();
    JButton button1 = new JButton("MyButton");
    JPanel one = new JPanel();
    one.add(scroll,BorderLayout.NORTH);
    JPanel two = new JPanel();
    two.add(button1);
    //two.setSize(new Dimension(800,200));
    //two.setPreferredSize(new Dimension(800, 200));
    //two.setBounds(0, 0, 0, 0);
    //two.setHorizontalAlignment(JButton.LEFT);
    //two.setLocation(0,100);

    one.setVisible(true);
    JPanel combine = new JPanel();
    combine.add(one);
    combine.add(two);
    getContentPane().add(combine);

Thanks

Web_Sailor 0 Junior Poster

Use Scanner, not BufferedReader. Create the Scanner then use scanner.nextLine(). Print out the line that nextLine() returns, and you're done. You could use BufferedReader also and just read in bytes while its not = '\n' also, I suppose.

I did like below but its reading and printing the whole file:--

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;


public class convert {
    public static void main(String[] args) {

        File file = new File("inputfile.txt");

        try {

            Scanner scan = new Scanner(file);
            while (scan.hasNextLine()) {
                String line = scan.nextLine();
                System.out.println(line);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

Thanks

Web_Sailor 0 Junior Poster

Hi... I want to read only the first line of a file and print the line. I don't want to read the whole file. How can I do that ?

Here is how we normally read the file

import java.io.*;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Readfile {
    public void Readfile(){
        
    }
    public static void main(String argv[]) throws Exception {
        try {
            BufferedReader br = new BufferedReader(new FileReader("inputfile.txt"));
            String s=null;

            while((s=br.readLine())!=null && (s = s.trim()).length() > 0){
                 String f[] = s.split("\t");

               System.out.println(s);

            }  br.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Readfile.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}

So what should I do to make it stop reading the whole file and just print the first line of a text file ?

Thanks