User Input in Dos Programs
Hi, sorry for such as newbie type question but iv just started programming in Java (so im used to the simpleness of vb). I have a simple Java Dos program, and i understand the system. functions but was wondering how i could get the > user input prompt. any help would be greatly appreciated. thanks!
WC
See if this isn't what you want:
import java.io.*;
// This program displays the user's input
public class GetInput {
public static void main(String[] args) throws IOException {
// This is how we set things up to read lines of text from the user.
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
// Loop forever
for(;;) {
// Display a prompt to the user
System.out.print("Type something> ");
// Read a line from the user
String line = in.readLine();
// If the input is null or if the user types �quit�, then quit
if (line.equals("") || line.equals("quit"))
break;
try {
System.out.println(line);
// If anything goes wrong, display a generic error message
catch(Exception e) {
System.out.println("Invalid Input");
}
Similar Messages
-
Exe running from java fails to get user input .Help me...
I have an DOS based exe.It just asks for input for a number from the user and prints the number it gtes.
When I try to execute this program from Java with the following code
import java.lang.Runtime;
import java.lang.Process;
import java.io.*;
public class runtimetest {
public static void main(String[] args) throws Exception {
Runtime rt = Runtime.getRuntime();
Process p = rt.exec("myExe");
nothing happens.Thatis It doesnot ask for the input .and I am just unable to know whether its running or not.
What could be wrong?
What is the other means to tun the DOS based exe that accepts user inputs , from Java.
Plz help me as I am in urgent need.
Aathitry this
Runtime r = Runtime.getRuntime();
Process p = null;
try
System.out.println("Exe will be called");
p = r.exec("cmd.exe /c start c:/ur exe path ");
p.waitFor();
catch (Exception e)
e.printStackTrace();
} -
DOS Programs Fail To Start in Full Screen
HP 4600 WorkstationWindows XP SP3 all latest driversQuadro FX 580 Display CardDOS command line starts and works fine in Full ScreenHowever when I try to start any DOS program, either from the start menu or the command line I get an error: "ntvdm.exe has encountered a problem and needs to be closed." Error SignatureAppName: ntvdm.exe v5.1.2600.5512ModName: kernel32.dll v5.1.2600.6532Offset: 00012fd3 Exception InfoCode: 0xC0000005Flags: 0x00000001Record: 0x00000000Address: 0x000000007C812FD3 My research indicates it's an access memory violation, probably by the nVidia driver.The ntvdm creates a 16-bit virtual environment for these programs.Iv'e tried everything I can think of:-HotFixes from Microsoft-BIOS settings-turn off DEP-Google searches-different driver versions-modify PIF settings-etc, etc.-tried nVidia support with no luck Has anyone got a DOS program to start in full screen?If so then at least I will know it can be done.Any suggestions, setting changes, etc?Maybe change display card to GeForce and those drivers. I know... why use a DOS program. Well because I need to,I wouldn't be going through this hassle if I didn't. If I can'tget the DOS program to run in this computer then its onlygood as a door stop for me. Thanks
reindeer4,
> How can I make my flash site load in Full Screen mode
> by default (using Actionscript 3 in Flash CS4)?
The security features of Flash Player are specifically
configured to
keep this from happening. The idea is to avoid someone being
able to trick
the end user into thinking s/he is using a fullscreen app, or
something
other than Flash. Note, for example, that unless you're
developing for AIR,
full screen mode disables keyboard input:
http://help.adobe.com/en_US/AS3LCR/Flash_10.0/flash/display/StageDisplayState.html#FULL_SC REEN
Additional details available here:
http://help.adobe.com/en_US/AS3LCR/Flash_10.0/flash/display/Stage.html#displayState
David Stiller
Co-author, ActionScript 3.0 Quick Reference Guide
http://tinyurl.com/dpsAS3QuickReferenceGuide
"Luck is the residue of good design." -
User Authorisations in Dialog Programming.
Hi Friends,
I have a small requirement, I want to create user authorisations in dialog programming.
Actually client requirement is he want to enter absence details of each and every branch.
For that i have created a cusom table and i also i have developed a dialog program inorder to update the details
and to retrive all the data i have created a report program also.
Now the client requirement is he want user authorisations while updating the data through dialog programming, that means if a user loging in that particular branch he want to enter the absence details pertaining to that branch only, when he tries to enter the details of other employee pertaining to another branch an error should be raised.
Actually in the client place they are using authrisation object as 'Z_WERKS'. The basis person has created this and provided for me.
Actually i have created an Authority check in module pool program.Here iam attaching my prog,
Pls provide me the sample code if at all available.
*& Include ZEMPTOP Module pool
PROGRAM ZEMP.
TABLES : ZABS,PA0001.
DATA : WA_PA0001 LIKE PA0001,
V_ANS.
DATA: BEGIN OF Z_WERKS OCCURS 0,
PERSA LIKE T500P-PERSA,
NAME1 LIKE T500P-NAME1,
END OF Z_WERKS.
*& Include ZEMPI01
*& Module USER_COMMAND_0100 INPUT
text
MODULE USER_COMMAND_0100 INPUT.
CASE SY-UCOMM.
WHEN 'DISP'.
SELECT SINGLE * FROM ZABS WHERE PERNR = ZABS-PERNR.
IF SY-DBCNT <> 0.
*MESSAGE I000(Z00) WITH 'Details of' ZABS-PERNR .
else.
MESSAGE I000(Z00) WITH 'No Details Available to Display'.
ENDIF.
WHEN 'EXIT'.
LEAVE PROGRAM.
WHEN 'BACK' OR 'EXIT' OR 'CANCEL'.
LEAVE TO SCREEN 0.
WHEN 'CLS'.
CLEAR ZABS.
WHEN 'INS'.
INSERT ZABS .
ZABS-ABWTG = ZABS-ENDDA - ZABS-BEGDA + 1.
IF SY-DBCNT <> 0.
MESSAGE I000(Z00) WITH 'Personnel No' ZABS-PERNR
'inserted successfully'.
ENDIF.
CLEAR ZABS.
WHEN 'MOD'.
UPDATE ZABS.
ZABS-ABWTG = ZABS-ENDDA - ZABS-BEGDA + 1.
IF SY-DBCNT <> 0.
MESSAGE I000(Z00) WITH 'Personnel No' ZABS-PERNR
'Modified Successfully'.
ENDIF.
CLEAR ZABS.
*WHEN 'DEL'.
*CALL FUNCTION 'POPUP_TO_CONFIRM_LOSS_OF_DATA'
EXPORTING
TEXTLINE1 = 'ARE YOU SURE'
TEXTLINE2 = 'YOU WANT TO DELETE'
TITEL = 'CONFIRMATION'
START_COLUMN = 25
START_ROW = 6
DEFAULTOPTION = 'N'
IMPORTING
ANSWER = V_ANS.
*IF V_ANS = 'J'.
*DELETE ZABS.
*IF SY-DBCNT <> 0.
*MESSAGE I000(Z00) WITH 'Personnel No' ZABS-PERNR
*'Deleted Successuflly'.
*ELSE.
*MESSAGE I000(Z00) with 'No Record to Delete'.
ENDIF.
*ENDIF.
ENDCASE.
ENDMODULE. " USER_COMMAND_0100 INPUT
*& Module GET_REC INPUT
text
MODULE GET_REC INPUT.
SELECT SINGLE * FROM PA0001 INTO WA_PA0001
WHERE PERNR = ZABS-PERNR.
MOVE: WA_PA0001-PERNR TO ZABS-PERNR,
WA_PA0001-ENAME TO ZABS-ENAME,
WA_PA0001-GSBER TO ZABS-GSBER,
WA_PA0001-WERKS TO ZABS-WERKS.
ZABS-ABWTG = ZABS-ENDDA - ZABS-BEGDA + 1.
ENDMODULE. " GET_REC INPUT
*& Module CHECK_AUTH_WERKS INPUT
text
MODULE CHECK_AUTH_WERKS INPUT.
*SELECT PERSA INTO TABLE _WERKS FROM T500P
WHERE PERSA = ZABS-WERKS.
AUTHORITY-CHECK OBJECT 'Z_WERKS'
ID 'PERSA' FIELD Z_WERKS-PERSA.You need to test the sy-subrc after the authority check - that will indicate whether the user has the authorisation or not.. you also often include the activity being tested e.g. generally 03 = Display, 02 = Update etc
AUTHORITY-CHECK OBJECT 'S_TRVL_BKS'
ID 'ACTVT' FIELD '03'
ID 'CUSTTYPE' FIELD 'B'.
IF not SY-SUBRC is initial.
MESSAGE E... "put your exception here...
ENDIF.
see [Programming Authorization Checks |http://help.sap.com/saphelp_nw04/helpdata/en/52/6712ac439b11d1896f0000e8322d00/content.htm] for more info.
Jonathan -
Unable to Give Input for my Program in JDEV 11g(11.1.1.3.0)
I'm using Windows 7_Ultimate -32 Bit OS with Administrator Priviliges
I'm trying to Run The Following Program
package appln;
import java.util.Scanner;
public class arr {
public static void main(String[] args) {
Scanner so = new Scanner(System.in);
System.out.println("Enter a value into variableID");
int id = so.nextInt();
System.out.println("Variable ="+id);
I'm getting the following errors in "Extensions" Sub window of Output window
oracle.BC4J:
Warning: Classpath entry D:\Oracle\Middleware\jdeveloper\jdev\extensions\oracle.jdeveloper.junit\junit4.5\junit-4.5.jar not found.
oracle.xsqldt-ide:
Warning: Classpath entry D:\Oracle\Middleware\jdeveloper\jdev\extensions\oracle.jdeveloper.junit\junit4.5\junit-4.5.jar not found.
Unknown Source: "Error: Field {0} of analyzer {1} references undefined bean {2}
The MAIN purpose of the program is to Accept input into variable named id and display to output.
Program Compiled Successfully but while the program is running,
Out put is "Enter a value into variableID"
And i'm unable to give input i.e unable to place cursor to give input
Also i've configured the Input Settings as Mentioned in the BLOG at "http://blogs.oracle.com/shay/2008/02/enabling_user_input_when_runni.html"
Even though the same thing thing is being repeated
But when i've run the program in NET BEANS IDE 6.9.1, the program is compiled and runned well.John Stegeman WROTE: " Any way to avoid what, exactly?"
I mean that every time we need to insert the cursor into INPUT field using mouse then input the value and press enter.
But for large input's it becomes tedious to each time place the cursor in Input field.
SO i meant to avoid this.
How can i avoid this.
Also you've mentioned me to run program's out of JDEV, if i do so i will be mising the Beauty and Advanced Capabilities of "ORACLE JDEV 11G".
So i can't use any other IDE Than JDEV.
Also can we Modify the way JDEV prompts for input's rather than this INPUT Field i.e by enabling the user input field for every program.
If there any, please mention.
Thanks for help in advance :)
Edited by: Tejaswi.B on Jan 22, 2011 11:30 PM -
Asking for user input in the middle of a function
Here's my issue.
I need to launch and input window in the middle of a function for user input. Before I can continue through the function I need a response back from the user first. Psuedo code below:
function
function begins
pop up window is launched to ask for user input
function continues after users submits input
user input from pop up window is used in function return value
Let me know if you need more clarification but this is essentially what I'm attempting to do.The way actionScript works it isn’t really designed to work that way
Is there any reason why you have to only use one function as you have written
I think you really do need to split up your code into sections that a, set up the pop-up with event listeners waiting for the input to be completed, trigger the pop up with user input, then have a handler function that then interprets the results of the user action.
Trying to force the system into a closed loop while waiting will be a bad idea.
By using a pop-up or an alert window that is set to be modal, you are effectively stopping your application doing anything else until the user input has been completed, but still not locking the app into a closed loop. Imagine what would happen if you did put the system into a closed loop, the mouse movement wouldn’t be updated, the screen wouldn’t refresh and the system wouldn’t be able to handle your user input. the reason for using async model is you are able to let the system still do all its background task (move the mouse, give inputs focus, keep the screen drawn etc) but still tell a part of your app to ‘wait for input’ before carrying on it execution of your logic
Do you come from another programming language? Maybe one that uses less of an OOP approach? I only ask, as the method you are describing is much more like how I had to program when I worked on computers years ago as an assembly programmer.
In actionscript and most other modern languages and Oss you don’t have total control of the system and cant lock it into an action as you describe.
You need to have an asynchronous approach to situations like you describe and let the system run in the back ground while you are waiting for input (or date from a server for that matter)
Please excuse me if I am telling you things you already know.
What exactly is your use case for this? Maybe if we knew exactly what you are working on I might be able to offer a solution that would make sense for your particular situation.
Hope all is going well and please feel free to contact me if you are stuck -
Help needed, Createing Dynamic User input
Hello,
I am attempting to create some dynamic user input by "predicting" what the user requires in a text box.
For example if the user enters "Smi" I have a select list pop up which gives the user all options that begin with "Smi".
I am able to achieve the popups but the interface is quite jerky and not terribly responsive I am trying to solve this by using a thread which starts and stops when new input is received but it is still not quite right.
The program uses a Sorted TreeSet to hold the data (I thought this would give me a quick search time) and a simple interface at this stage.
Any help would be fantastic
Thanks in advance :P
import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
import java.text.*;
import java.util.*;
/** This program represents part of a larger user interface for allowing the
user to select data from a file or database.
<p>
When the program starts up, it will read in data from a given file, and hold
it in some type of container allowing rapid access.
<p>
The user may then type in the first few letters of the surname of a person,
and this program should immediately present in a popup dialog the names which
match. The user will be able to click on one of the names in the popup and
that will cause all data about that person to be displayed in the JTextArea
at the bottom of the window.
<p>
This program requires the FormLayout.class, FormLayout$Placement.class, and
FormLayout$Constraint.class files in the same directory
(folder) or in its classpath. These is provided separately.
class PartMatch extends JFrame implements Runnable
/** Close down the program. */
JButton quitbtn;
/** Field for the surname. */
JTextField namefld;
/** Full details of the person(s). */
JTextArea results;
/** Popup dialog to display the names and addresses which
match the leading characters given in namefld. */
Chooser matches;
/** Default background color for a window. */
final static Color defBackground = new Color(0xD0C0C0);
/** Default foreground color for a window. */
final static Color defForeground = new Color(0x000000);
/** Default background color for a field */
final static Color fldBackground = new Color(0xFFFFFF);
/** Default background color for a button */
final static Color btnBackground = new Color(0xF0E0E0);
final static Color dkBackground = new Color(0xB0A0A0);
/** Larger font */
final static Font bold = new Font("Helvetica", Font.BOLD, 30);
TreeSet members;
String input;
String[] found;
public static void main(String arg[])
UIManager.put("TextField.background",fldBackground);
UIManager.put("TextField.foreground",defForeground);
UIManager.put("TextField.selectionBackground",btnBackground);
UIManager.put("TextArea.background",fldBackground);
UIManager.put("TextArea.foreground",defForeground);
UIManager.put("TextArea.selectionBackground",btnBackground);
UIManager.put("Panel.background",defBackground);
UIManager.put("Label.background",defBackground);
UIManager.put("Label.foreground",defForeground);
UIManager.put("Button.background",btnBackground);
UIManager.put("Button.foreground",defForeground);
UIManager.put("CheckBox.background",defBackground);
UIManager.put("ScrollBar.background",defBackground);
UIManager.put("ScrollBar.thumb",btnBackground);
UIManager.put("ComboBox.background",btnBackground);
UIManager.put("ComboBox.selectionBackground",dkBackground);
PartMatch trial = new PartMatch(arg);
public PartMatch( String [] arg )
super("Part Match");
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container cpane = getContentPane();
FormLayout form = new FormLayout(cpane);
JLabel lab1 = new JLabel("Fetch details") ;
lab1.setFont( bold );
form.setTopAnchor( lab1, 4 );
form.setLeftAnchor( lab1, 4 );
JLabel lab2 = new JLabel("Surname: ") ;
form.setTopRelative( lab2, lab1, 4 );
form.setLeftAlign( lab2, lab1 );
namefld = new JTextField( 30 );
form.setBottomAlign( namefld, lab2 );
form.setLeftRelative( namefld, lab2, 4 );
namefld.addCaretListener( new CaretListener()
public void caretUpdate(CaretEvent e)
showMatches();
quitbtn = new JButton( "Quit" );
quitbtn.addActionListener( new ActionListener()
public void actionPerformed(ActionEvent e)
quitProcessing();
form.setBottomAlign( quitbtn, namefld );
form.setLeftRelative( quitbtn, namefld, 15 );
results = new JTextArea( 10,50 );
results.setEditable(false);
JScrollPane jsp = new JScrollPane( results,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED );
form.setTopRelative( jsp, lab2, 6 );
form.setLeftAlign( jsp, lab2 );
form.setBottomAnchor( jsp, 5 );
form.setRightAnchor( jsp, 5 );
form.setRightAnchor( quitbtn, 5 );
matches = new Chooser( this );
//matches.setUndecorated(true);
pack();
setVisible(true);
namefld.requestFocus();
if (arg.length > 0) init(arg[0]);
else init("triathlon.txt"); //<<<<<<<<<<<<<<<< Place the default filename here
/** Called once only, at the end of the constructor, to read the data
* from the membership file.
public void init( String fname )
members = new TreeSet();
try {
FileReader fr = new FileReader(new File (fname));
Scanner scan = new Scanner(fr);
trimember cmem;
String cLine, eTag, memberNo, first, last, gender, yob, tel ,addr,
club;
while(scan.hasNextLine())
cLine = scan.nextLine();
Scanner scan2 = new Scanner(cLine);
scan2.useDelimiter(";");
eTag = scan2.next().trim();
memberNo = scan2.next().trim();
first = scan2.next().trim();
last = scan2.next().trim();
gender = scan2.next().trim();
yob = scan2.next().trim();
tel = scan2.next().trim();
addr = scan2.next().trim();
club = scan2.next().trim();
cmem = new trimember(eTag, memberNo, first, last, gender, yob,
tel, addr, club);
members.add(cmem);
catch (FileNotFoundException ex)
results.append("Sorry can't find the input file\n");
results.append("Please check file name and location and try again");
ex.printStackTrace();
/** Called every time there is a change in the contents of the text field
* namefld. It will first clear the text area. It then needs to search
* through the container of data to find all records where the surname
* starts with the characters that have been typed. The names and
* addresses need to be set up as strings and placed in
* an array of Strings. This can be placed in the "matches" window and
* displayed for the user, inviting one to be selected.
* <p>
* The performance of this is very important. If necessary, it may be
* necessary to run as a separate thread so that the user interface is
* not delayed. It is essential that the user be able to type letters at a
* reasonable speed and not have the keystroke processing held up by
* previous text.
public void showMatches( )
run();
// First clear the text area
//results.setText("");
// Determine the leading characters of the surname that is wanted
input = namefld.getText();
// Locate the data for this name, and display each matching item
// in the JTextArea ...
// Example of how to set the data in the popup dialog
matches.list.setListData(found);
matches.pack(); // resize the popup
// set the location of the popup if it is not currently visible
if ( ! matches.isVisible())
Dimension sz = matches.getSize();
Point mouse = getMousePosition();
Point framepos = getLocation();
int x=0, y=0;
if (mouse == null)
Point pt = results.getLocation();
x = pt.x + 20 + framepos.x;
y = pt.y + 20 + framepos.y;
else
x = mouse.x - 2 + framepos.x;
y = mouse.y - 2 + framepos.y;
matches.setLocation(x,y);
matches.setVisible(true);
namefld.requestFocus();
/** Perform any final processing before closing down.
public void quitProcessing( )
// Any closing work. Then
System.exit(0);
public void run()
ArrayList<String> foundit = new ArrayList<String>();
System.out.println(input);
if(input != null)
Iterator it = members.iterator();
while(it.hasNext())
trimember test = (trimember) it.next();
if (test.last.startsWith(input))
foundit.add(test.last +", "+ test.first);
found = new String[foundit.size()];
for(int i=0; i<foundit.size();i++)
found[i] = foundit.get(i);
/** A window for displaying names and addresses from the data set which
match the leading characters in namefld.
<p>
This will automatically pop down if the user moves the mouse out of the
window.
<p>
It needs code added to it to respond to the user clicking on an item in
the displayed list. */
class Chooser extends JWindow
/** To display a set of names and addresses that match the leading
characters of the namefld text field. */
public JList list = new JList();
Chooser( JFrame parent )
super( parent );
Container cpane = getContentPane();
cpane.addMouseListener( new MouseAdapter()
public void mouseExited(MouseEvent e)
Chooser.this.setVisible(false);
cpane.add("Center",list);
list.addListSelectionListener( new ListSelectionListener()
public void valueChanged(ListSelectionEvent e)
Chooser.this.setVisible(false);
System.out.println("ValueChanged");
// First clear the text area
results.setText("");
String in = (String) list.getSelectedValue();
System.out.println("Selected Value was : "+in);
String[] inlf = in.split(", ");
System.out.println("inlf[0]:"+inlf[0]+" inlf[1]:"+inlf[1]);
results.append("Surname \tFirst \teTag \tMemberNo \tSex \tYOB " +
"\tTel \tAddress \t\t\tClub\n");
Iterator it = members.iterator();
while(it.hasNext())
trimember test = (trimember) it.next();
if (test.last.equals(inlf[0])&&test.first.equals(inlf[1]))
results.append(test.toString()+"\n");
namefld.requestFocus();
public class trimember implements Comparable
String eTag;
public String memberNo;
public String first;
public String last;
String gender;
String yob;
String tel;
String addr;
String club;
public trimember(String eT, String me, String fi, String la,
String ge, String yo, String te, String ad, String cl)
eTag = eT;
memberNo = me;
first = fi;
last = la;
gender = ge;
yob = yo;
tel = te;
addr = ad;
club = cl;
//To String method to output string of details
public String toString()
return last + "\t" + first + "\t" + eTag + "\t" +
memberNo + "\t" + gender + "\t" + yob + "\t"+ tel + "\t" +
addr + "\t" + club;
//Compare and sort on Last name
public int compareTo(Object o)
trimember com = (trimember) o;
int lastCmp = last.compareTo(com.last);
int firstCmp = first.compareTo(com.first);
int memCmp = memberNo.compareTo(com.memberNo);
if (lastCmp == 0 && firstCmp !=0)return firstCmp;
else if (lastCmp==0&&firstCmp==0)return memCmp;
else return lastCmp;
}Please don't cross-post. It is considered very rude to do that here:
http://forum.java.sun.com/thread.jspa?messageID=9953193 -
Help needed, Providing Dynamic User input
Hello,
I am attempting to create some dynamic user input by "predicting" what the user requires in a text box.
For example if the user enters "Smi" I have a select list pop up which gives the user all options that begin with "Smi".
I am able to achieve the popups but the interface is quite jerky and not terribly responsive I am trying to solve this by using a thread which starts and stops when new input is received but it is still not quite right.
The program uses a Sorted TreeSet to hold the data (I thought this would give me a quick search time) and a simple interface at this stage.
Any help would be fantastic
Thanks in advance :P
import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
import java.text.*;
import java.util.*;
/** This program represents part of a larger user interface for allowing the
user to select data from a file or database.
<p>
When the program starts up, it will read in data from a given file, and hold
it in some type of container allowing rapid access.
<p>
The user may then type in the first few letters of the surname of a person,
and this program should immediately present in a popup dialog the names which
match. The user will be able to click on one of the names in the popup and
that will cause all data about that person to be displayed in the JTextArea
at the bottom of the window.
<p>
This program requires the FormLayout.class, FormLayout$Placement.class, and
FormLayout$Constraint.class files in the same directory
(folder) or in its classpath. These is provided separately.
class PartMatch extends JFrame implements Runnable
/** Close down the program. */
JButton quitbtn;
/** Field for the surname. */
JTextField namefld;
/** Full details of the person(s). */
JTextArea results;
/** Popup dialog to display the names and addresses which
match the leading characters given in namefld. */
Chooser matches;
/** Default background color for a window. */
final static Color defBackground = new Color(0xD0C0C0);
/** Default foreground color for a window. */
final static Color defForeground = new Color(0x000000);
/** Default background color for a field */
final static Color fldBackground = new Color(0xFFFFFF);
/** Default background color for a button */
final static Color btnBackground = new Color(0xF0E0E0);
final static Color dkBackground = new Color(0xB0A0A0);
/** Larger font */
final static Font bold = new Font("Helvetica", Font.BOLD, 30);
TreeSet members;
String input;
String[] found;
public static void main(String arg[])
UIManager.put("TextField.background",fldBackground);
UIManager.put("TextField.foreground",defForeground);
UIManager.put("TextField.selectionBackground",btnBackground);
UIManager.put("TextArea.background",fldBackground);
UIManager.put("TextArea.foreground",defForeground);
UIManager.put("TextArea.selectionBackground",btnBackground);
UIManager.put("Panel.background",defBackground);
UIManager.put("Label.background",defBackground);
UIManager.put("Label.foreground",defForeground);
UIManager.put("Button.background",btnBackground);
UIManager.put("Button.foreground",defForeground);
UIManager.put("CheckBox.background",defBackground);
UIManager.put("ScrollBar.background",defBackground);
UIManager.put("ScrollBar.thumb",btnBackground);
UIManager.put("ComboBox.background",btnBackground);
UIManager.put("ComboBox.selectionBackground",dkBackground);
PartMatch trial = new PartMatch(arg);
public PartMatch( String [] arg )
super("Part Match");
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container cpane = getContentPane();
FormLayout form = new FormLayout(cpane);
JLabel lab1 = new JLabel("Fetch details") ;
lab1.setFont( bold );
form.setTopAnchor( lab1, 4 );
form.setLeftAnchor( lab1, 4 );
JLabel lab2 = new JLabel("Surname: ") ;
form.setTopRelative( lab2, lab1, 4 );
form.setLeftAlign( lab2, lab1 );
namefld = new JTextField( 30 );
form.setBottomAlign( namefld, lab2 );
form.setLeftRelative( namefld, lab2, 4 );
namefld.addCaretListener( new CaretListener()
public void caretUpdate(CaretEvent e)
showMatches();
quitbtn = new JButton( "Quit" );
quitbtn.addActionListener( new ActionListener()
public void actionPerformed(ActionEvent e)
quitProcessing();
form.setBottomAlign( quitbtn, namefld );
form.setLeftRelative( quitbtn, namefld, 15 );
results = new JTextArea( 10,50 );
results.setEditable(false);
JScrollPane jsp = new JScrollPane( results,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED );
form.setTopRelative( jsp, lab2, 6 );
form.setLeftAlign( jsp, lab2 );
form.setBottomAnchor( jsp, 5 );
form.setRightAnchor( jsp, 5 );
form.setRightAnchor( quitbtn, 5 );
matches = new Chooser( this );
//matches.setUndecorated(true);
pack();
setVisible(true);
namefld.requestFocus();
if (arg.length > 0) init(arg[0]);
else init("triathlon.txt"); //<<<<<<<<<<<<<<<< Place the default filename here
/** Called once only, at the end of the constructor, to read the data
* from the membership file.
public void init( String fname )
members = new TreeSet();
try {
FileReader fr = new FileReader(new File (fname));
Scanner scan = new Scanner(fr);
trimember cmem;
String cLine, eTag, memberNo, first, last, gender, yob, tel ,addr,
club;
while(scan.hasNextLine())
cLine = scan.nextLine();
Scanner scan2 = new Scanner(cLine);
scan2.useDelimiter(";");
eTag = scan2.next().trim();
memberNo = scan2.next().trim();
first = scan2.next().trim();
last = scan2.next().trim();
gender = scan2.next().trim();
yob = scan2.next().trim();
tel = scan2.next().trim();
addr = scan2.next().trim();
club = scan2.next().trim();
cmem = new trimember(eTag, memberNo, first, last, gender, yob,
tel, addr, club);
members.add(cmem);
catch (FileNotFoundException ex)
results.append("Sorry can't find the input file\n");
results.append("Please check file name and location and try again");
ex.printStackTrace();
/** Called every time there is a change in the contents of the text field
* namefld. It will first clear the text area. It then needs to search
* through the container of data to find all records where the surname
* starts with the characters that have been typed. The names and
* addresses need to be set up as strings and placed in
* an array of Strings. This can be placed in the "matches" window and
* displayed for the user, inviting one to be selected.
* <p>
* The performance of this is very important. If necessary, it may be
* necessary to run as a separate thread so that the user interface is
* not delayed. It is essential that the user be able to type letters at a
* reasonable speed and not have the keystroke processing held up by
* previous text.
public void showMatches( )
run();
// First clear the text area
//results.setText("");
// Determine the leading characters of the surname that is wanted
input = namefld.getText();
// Locate the data for this name, and display each matching item
// in the JTextArea ...
// Example of how to set the data in the popup dialog
matches.list.setListData(found);
matches.pack(); // resize the popup
// set the location of the popup if it is not currently visible
if ( ! matches.isVisible())
Dimension sz = matches.getSize();
Point mouse = getMousePosition();
Point framepos = getLocation();
int x=0, y=0;
if (mouse == null)
Point pt = results.getLocation();
x = pt.x + 20 + framepos.x;
y = pt.y + 20 + framepos.y;
else
x = mouse.x - 2 + framepos.x;
y = mouse.y - 2 + framepos.y;
matches.setLocation(x,y);
matches.setVisible(true);
namefld.requestFocus();
/** Perform any final processing before closing down.
public void quitProcessing( )
// Any closing work. Then
System.exit(0);
public void run()
ArrayList<String> foundit = new ArrayList<String>();
System.out.println(input);
if(input != null)
Iterator it = members.iterator();
while(it.hasNext())
trimember test = (trimember) it.next();
if (test.last.startsWith(input))
foundit.add(test.last +", "+ test.first);
found = new String[foundit.size()];
for(int i=0; i<foundit.size();i++)
found[i] = foundit.get(i);
/** A window for displaying names and addresses from the data set which
match the leading characters in namefld.
<p>
This will automatically pop down if the user moves the mouse out of the
window.
<p>
It needs code added to it to respond to the user clicking on an item in
the displayed list. */
class Chooser extends JWindow
/** To display a set of names and addresses that match the leading
characters of the namefld text field. */
public JList list = new JList();
Chooser( JFrame parent )
super( parent );
Container cpane = getContentPane();
cpane.addMouseListener( new MouseAdapter()
public void mouseExited(MouseEvent e)
Chooser.this.setVisible(false);
cpane.add("Center",list);
list.addListSelectionListener( new ListSelectionListener()
public void valueChanged(ListSelectionEvent e)
Chooser.this.setVisible(false);
System.out.println("ValueChanged");
// First clear the text area
results.setText("");
String in = (String) list.getSelectedValue();
System.out.println("Selected Value was : "+in);
String[] inlf = in.split(", ");
System.out.println("inlf[0]:"+inlf[0]+" inlf[1]:"+inlf[1]);
results.append("Surname \tFirst \teTag \tMemberNo \tSex \tYOB " +
"\tTel \tAddress \t\t\tClub\n");
Iterator it = members.iterator();
while(it.hasNext())
trimember test = (trimember) it.next();
if (test.last.equals(inlf[0])&&test.first.equals(inlf[1]))
results.append(test.toString()+"\n");
namefld.requestFocus();
public class trimember implements Comparable
String eTag;
public String memberNo;
public String first;
public String last;
String gender;
String yob;
String tel;
String addr;
String club;
public trimember(String eT, String me, String fi, String la,
String ge, String yo, String te, String ad, String cl)
eTag = eT;
memberNo = me;
first = fi;
last = la;
gender = ge;
yob = yo;
tel = te;
addr = ad;
club = cl;
//To String method to output string of details
public String toString()
return last + "\t" + first + "\t" + eTag + "\t" +
memberNo + "\t" + gender + "\t" + yob + "\t"+ tel + "\t" +
addr + "\t" + club;
//Compare and sort on Last name
public int compareTo(Object o)
trimember com = (trimember) o;
int lastCmp = last.compareTo(com.last);
int firstCmp = first.compareTo(com.first);
int memCmp = memberNo.compareTo(com.memberNo);
if (lastCmp == 0 && firstCmp !=0)return firstCmp;
else if (lastCmp==0&&firstCmp==0)return memCmp;
else return lastCmp;
}Edited by: Roger on Nov 3, 2007 11:50 AMPlease don't cross-post. It is considered very rude to do that here:
http://forum.java.sun.com/thread.jspa?threadID=5233033&messageID=9953169#9953169 -
Acrobat Batch Plug-in and accessing user input parameters
I have written a plug-in for acrobat 9 and need to retreive the value stored in the "select output location" field from the default "edit batch sequence" dialog.
How can I get a handle to the "edit batch sequence" dialog and the dialog's user input fields and their respective values?I don't know if this will help you out, but remember that a batch sequence (.sequ) is finally just a plain-text file.
If you know the name of the batch and the location of the sequences folder, you can probably write a small tool to read it in, parse it and figure out the output folder yourself.
For example, here's a very basic batch sequence I've created. It just calls a JS method on each file:
<</Commands [/c << /0 [/c << /Config [/c << /UIPolicy [/i 3]
>>]
/HandlerName [/a /JavaScript]
/Params [/c << /ScriptCode [/t (collectFilePaths\(this\);)]
/ScriptName [/t ()]
>>]
/Title [/t (Execute JavaScript)]
>>]
>>]
/Input [/c << /FileVariation [/i 1]
/PreselectedFolderPath [/c << /DI [/s (/C/Batch In)]
/DIText [/t (/C/Batch In)]
/FS [/a /DOS]
>>]
/SourceFileOptions [/c << /Formats [/c <<>>]
>>]
>>]
/Output [/c << /AddToBaseName [/b false]
/DontOverwrite [/b false]
/FileVariation [/i 2]
/InsertAfterBaseName [/t ()]
/InsertBeforeBaseName [/t ()]
/OptimizePDF [/b true]
/PreselectedFolderPath [/c << /DI [/s (/C/Batch Out)]
/DIText [/t (/C/Batch Out)]
/FS [/a /DOS]
>>]
/PresetName [/t (Standard)]
/RunPDFOptimizer [/b false]
>>]
>>
The input and output folders ("C:\Batch In" and "C:\Batch Out\") are plainly visible in the code. -
How to check the value from user input in database or not?
Hello;
I want to check the value of user input from JtextFiled in my database or not.
If it is in database, then i will pop up a window to tell us, otherwise, it will tell us it is not in database.
My problem is my code do not work properly, sometimes, it tell me correct information, sometime it tell wrong information.
Could anyone help,please.Thanks
The following code is for check whether the value in database or not, and pop up a window to tell us.
while( rs.next()) {
System.out.println("i am testing");
bInt=new Integer(rs.getInt("id"));
if(aInt.equals(bInt)){ // If i find the value in data base, set flag to 1.
flag=1; //I set a flag to check whether the id in database or not
break;
System.out.println("falg" + flag);
if(flag==1){ //?????????????????????
String remove1 = "DELETE FROM Rental WHERE CustomerID=" + a;
String remove2 = "DELETE FROM Revenus WHERE CustomerID=" +a;
String remove3 = "DELETE FROM Customer WHERE id=" +a;
s.executeUpdate(remove1);
s.executeUpdate(remove2);
s.executeUpdate(remove3);
JOptionPane.showMessageDialog(null,"you have success delete the value");
s.close();
else//???????????????????????????????
JOptionPane.showMessageDialog(null,"I could not found the value"); -------------------------------------------------------------------
My whole program
import java.sql.*;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JOptionPane;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class DeleteC extends JFrame
public static int index=0;
public static ResultSet rs;
public static Statement s;
public static Connection c;
public static Object cols[][];
private static JTable table;
private static JScrollPane scroller;
private static int flag=0;
public DeleteC()
//information of our connection
//the url of the database: protocol:subprotocol:subname:computer_name:port:database_name
String strUrl = "jdbc:oracle:thin:@augur.scms.waikato.ac.nz:1521:teaching";
//user name and password
String strUser = "xbl1";
String strPass = "19681978";
//try to load the driver
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
catch (ClassNotFoundException e) {
System.out.println( "Cannot load the Oracle driver. Include it in your classpath.");
System.exit( -1);
//a null reference to a Connection object
c = null;
try {
//open a connection to the database
c = DriverManager.getConnection( strUrl, strUser, strPass);
catch (SQLException e) {
System.out.println("Cannot connect to the database. Here is the error:");
e.printStackTrace();
System.exit( -1);
//create a statement object to execute sql statements
public void getData(String a){
try {
//create a statement object to execute sql statements
s = c.createStatement();
int index=0;
Integer aInt= Integer.valueOf(a);
Integer bInt;
//our example query
String strQuery = "select id from customer";
//execute the query
ResultSet rs = s.executeQuery( strQuery);
//while there are rows in the result set
while( rs.next()) {
System.out.println("i am testing");
bInt=new Integer(rs.getInt("id"));
if(aInt.equals(bInt)){
//JOptionPane.showMessageDialog(null,"I found the value");
flag=1;
break;
System.out.println("falg" + flag);
if(flag==1){
String remove1 = "DELETE FROM Rental WHERE CustomerID=" + a;
String remove2 = "DELETE FROM Revenus WHERE CustomerID=" +a;
String remove3 = "DELETE FROM Customer WHERE id=" +a;
s.executeUpdate(remove1);
s.executeUpdate(remove2);
s.executeUpdate(remove3);
JOptionPane.showMessageDialog(null,"you have success delete the value");
s.close();
else
JOptionPane.showMessageDialog(null,"I could not found the value");
catch (SQLException e) {
JOptionPane.showMessageDialog(null,"You may enter wrong id");
My main program for user input from JTextField.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JOptionPane;
import java.util.*;
public class EnterID extends JFrame{
public JTextField tF1;
public EnterID enID;
public String tF1Value;
private JLabel label1, label2, label3;
private static JButton button;
private static ButtonHandler handler;
private static String aString;
private static Integer aInteger;
private static Integer checkV=0;
public static void main(String args[]){
EnterID eId= new EnterID();
public EnterID(){
handler=new ButtonHandler();
Container c= getContentPane();
c.setLayout(new GridLayout(3,1));
button= new JButton("ok");
button.addActionListener(handler);
label1 = new JLabel(" CustomerID, Please");
label2 = new JLabel("Label2");
label3 = new JLabel();
label3.setLayout(new GridLayout(1,1));
label3.add(button);
label2.setLayout(new GridLayout(1,1));
aString = "Enter Id Here";
tF1 = new JTextField(aString);
label2.add(tF1);
c.add(label1);
c.add(label2);
c.add(label3);
setSize(150,100);
setVisible(true);
private class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent event){
tF1Value=tF1.getText();
// CheckData cData = new CheckData();
// aInteger = Integer.valueOf(tF1Value);
if(tF1Value.equals(aString)){
JOptionPane.showMessageDialog(null,"You didn't type value into box");
setVisible(false);
else {
DeleteC dC= new DeleteC();
dC.getData(tF1Value);
setVisible(false);
}You may have working code now, but the code you posted is horrible and I'm going to tell you a much much much better approach for the JDBC part. (You should probably isolate your database code from your user interface code as well, but I'm skipping over that structural problem...)
Do this instead:
public void getData(String a){
PreparedStatement p;
String strQuery = "select count(*) the_count from customer where id = ?";
try {
//create a prepared statement object to execute sql statements, it's better, faster, safer
p = c.prepareStatement(strQuery);
// bind the parameter value to the "?"
p.setInt(1, Integer.parseInt(a) );
//execute the query
ResultSet rs = p.executeQuery( );
// if the query doesn't throw an exception, it will have exactly one row
rs.next();
System.out.println("i am testing");
if (rs.getInt("the_count") > 0 ) {
// it's there, do what you need to...
else
JOptionPane.showMessageDialog(null,"I could not find the value");
catch (SQLException e) {
// JOptionPane.showMessageDialog(null,"You may enter wrong id");
// if you get an exception, something is really wrong, and it's NOT user error
// always, always, ALWAYS close JDBC resources in a finally block
finally
p.close();
}First, this is simpler and easier to read.
Second, this retrieves just the needed information, whether or not the id is in the database. Your way will get much much slower as more data goes into the database. My way, if there is an index on the id column, more data doesn;t slow it down very much.
I've also left some important points in comments.
No guarantees that there isn't a dumb typo in there; I didn't actually compile it, much less test it. It's at least close though... -
Taking user input in a PL/SQL block
Can someone tell me if it is possible to to take user input from within a PL/SQL loop? I mean I want that for each iteration in the loop, the program first take user input, and then based on that input, it perform specific operations. Then it repeats this process for each subsequent iteration of loop.
If it is not possible in PL/SQL, is there any other alternative?
Thanks.> I'm afraid I have no idea how to get the server to ask questions of the user,
especially when it essentially operates in a kind of batch mode.
Yep. To expand a tad on what Hans mentioned here.
To accept input, the process needs to be able to read from this input device. Let's make it a keyboard. The PL/SQL process needs to read keyboard input.
The keyboard is attached to a PC 1000km away in a branch office. The Oracle server process, running on a server in the data centre, executes this PL/SQL code.
So now this PL/SQL process has to automagically hack its way across the network. It needs to remove the keyboard plug from that client PC. It somehow must get that keyboard rewired, across that 1000km, into the server platform at the data centre. And only then can the Oracle server process running that PL/SQL code read from that keyboard input device and accept user input.
It is important, when developing in Oracle, to grasp just what client-server is and how it works. And not to confuse something like a SQL*Plus Client Process (submitting PL/SQL code) with the Oracle Server Process (parsing and executing that submitted PL/SQL code). -
Adobe form not saving user-input data into saved pdf file
Hi forumers,
I'm a new abap developer and I'm tasked to create an interactive adobe form that will require the user to input data in the form.
No data is passed and received from PDF, but PDF has to be u2018Fillableu2019. I am able to fill out the form but when I actually save the form, it will be saved as a blank form again. I've seen the relevance of the LS_DOCPARAMS-FILLABLE = 'X' on this forum and I have incorporated it in my code. But how should I code the abap program to enable to save the user input as well into the form.
DATA: GV_FMNAME TYPE FPNAME,
LS_DOCPARAMS TYPE SFPDOCPARAMS,
LS_OUTPUTPARAMS TYPE SFPOUTPUTPARAMS.
CALL FUNCTION 'FP_FUNCTION_MODULE_NAME'
EXPORTING
I_NAME = 'ZSC_ZRUFORREP'
IMPORTING
E_FUNCNAME = GV_FMNAME
* E_INTERFACE_TYPE =
* EV_FUNCNAME_INBOUND =
CALL FUNCTION 'FP_JOB_OPEN'
CHANGING
IE_OUTPUTPARAMS = LS_OUTPUTPARAMS
EXCEPTIONS
CANCEL = 1
USAGE_ERROR = 2
SYSTEM_ERROR = 3
INTERNAL_ERROR = 4
OTHERS = 5
IF SY-SUBRC <> 0.
* MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
* WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
ENDIF.
LS_DOCPARAMS-FILLABLE = 'X'.
LS_DOCPARAMS-DYNAMIC = 'X'.
CALL FUNCTION GV_FMNAME
EXPORTING
/1BCDWB/DOCPARAMS = LS_DOCPARAMS
* IMPORTING
* /1BCDWB/FORMOUTPUT =
EXCEPTIONS
USAGE_ERROR = 1
SYSTEM_ERROR = 2
INTERNAL_ERROR = 3
OTHERS = 4
IF SY-SUBRC <> 0.
* MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
* WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
ENDIF.
CALL FUNCTION 'FP_JOB_CLOSE'
* IMPORTING
* E_RESULT =
EXCEPTIONS
USAGE_ERROR = 1
SYSTEM_ERROR = 2
INTERNAL_ERROR = 3
OTHERS = 4
IF SY-SUBRC <> 0.
* MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
* WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
ENDIF.
Thanks,
dgracheeNot quite yet, I have to say...
If you check the domain "FPINTERACTIVE", you'll see these values:
Print Form
X Interactive Form with Additional Usage Rights
N Interactive Form Without Additional Usage Rights
F
So, you are not providing "additional usage rights" (Adobe Form Credentials), meaning there could be a problem when you want to use those forms in a Production environment. -
Auto populate a textfield based on users input
Hi All,
Working with Designer ES ver. 8.2, and I am looking to see if it is possible to auto fill another field based on an end users input.
Example: End-user enters a 6 digit departmentCode for a program; in turn the field opposite to the departmentCode auto fills with a corresponding programCode; if they do not input the correct 6 digit departmentCode the field will return a null value.
I am trying to move away from my current auto fill drop-down option, so end-user is less likely to select incorrect departmentCode from drop-down
Best Regards
Jeffradzmar,
Thank you for your response, I assumed there was a simple script to accomplish my task. I had assumed that the .rawValue property would have come into play and was unaware of the xfa.event.fullText property.
Thanks Again -
User input in JDeveloper IDE not working?
We just started to use JDeveloper. so the problem may be very basic, I could not figure it out what is wrong:
I have a java class which is calling a third part application (Lotus Notes, domino server). The task of the class is to open a database on domino server(or local machine). When calling domino, there is a user(calling) authorization. So I must input the password for the domino server for authorization. When I input the password in input panel and hit return, nothing happened. It looks the Domino still wait for the password. It waited and waited and the process can not be stopped itself.
when I copied the same code and ran in other IDE or Sun's JDK. It worked fine.
So it looks that my JDeveloper could not pass user' input to the process?
Any helps are highly appreciated.
GeorgeHi George,
Let me make sure I understand what you are saying.
You want to run (or debug) your program which reads input from System.in?
If so...
Have you checked the checkbox in the Project Settings Dialog - Runner - Options panel "Allow Program Input"? Then when you ran (or debugged) your program, did you see a text field labeled "Input:" in the Log window for your running process?
Did you enter the password in that text field and press Enter on your keyboard?
If that wasn't the problem, can you give us step by step what you are doing?
Thanks,
Liz -
Showing user input in a JFrame
i need to be able to take user-given values and display them in a JFrame. i'm testing the input of a sudoku puzzle. i have a sudokuComponent and a sudokuViewer.
i'm confused as to where to place my code that will do the process of taking user input (via Scanner class) and testing it for certain conditions.
i dont think figuring out the testing conditions should be hard, i'm just having trouble with getting the input read in correctly and a way of getting it displayed on the JFrame which displays the sudoku puzzle with the values so far.
i was given a tip that said i needed to use the method repaint() of JFrame to see the updates.
SUDOKUCOMPONENT
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Line2D;
import javax.swing.JPanel;
import javax.swing.JComponent;
import java.util.Scanner;
public class SudokuComponent extends JComponent
public void paintComponent(Graphics g)
//recover graphics2s
Graphics2D g2 = (Graphics2D) g;
//Construct the Sudoku square
Rectangle box = new Rectangle(20, 20, 270, 270);
g2.draw(box);
g2.draw(new Line2D.Double(20, 110, 290, 110)); //horizontal
g2.draw(new Line2D.Double(20, 200, 290, 200));
g2.draw(new Line2D.Double(110, 20, 110, 290)); //vertical
g2.draw(new Line2D.Double(200, 20, 200, 290));
}SUDOKUVIEWER
import javax.swing.JFrame;
import java.util.Scanner;
public class SudokuViewer
public static void main(String[] args)
JFrame frame = new JFrame();
final int FRAME_WIDTH = 350;
final int FRAME_HEIGHT = 350;
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setTitle("Sudoku Viewer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SudokuComponent component = new SudokuComponent();
frame.add(component);
frame.setVisible(true);
}I have improved your application to show how it can be programmed.
For more information you can see about
KeyListener:
http://java.sun.com/docs/books/tutorial/uiswing/events/keylistener.html
MouseListener:
http://java.sun.com/docs/books/tutorial/uiswing/events/mouselistener.html
and of course use repaint() when you want to update your component
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Line2D;
import java.util.LinkedList;
import java.util.List;
import javax.swing.JComponent;
public class SudokuComponent extends JComponent {
SudokuElement currentElement = new SudokuElement();
List<SudokuElement> elementList = new LinkedList<SudokuElement>();
public SudokuComponent(){
addMouseListener(new MyMouseListener());
setFocusable(true);
addKeyListener(new MyKeyListener());
public void paintComponent(Graphics g) {
//public void paint(Graphics g) {
//recover graphics2s
Graphics2D g2 = (Graphics2D) g;
//Construct the Sudoku square
Rectangle box = new Rectangle(20, 20, 270, 270);
g2.draw(box);
g2.draw(new Line2D.Double(20, 110, 290, 110)); //horizontal
g2.draw(new Line2D.Double(20, 200, 290, 200));
g2.draw(new Line2D.Double(110, 20, 110, 290)); //vertical
g2.draw(new Line2D.Double(200, 20, 200, 290));
// show place where user can type a digit
g2.draw(new Line2D.Double(currentElement.x - 10, currentElement.y, currentElement.x + 10, currentElement.y));
// show all typed digits
for(SudokuElement elem : elementList ){
g2.drawString(elem.digit + "", elem.x, elem.y);
class SudokuElement {
int digit;
int x;
int y;
SudokuElement getCopy(){
SudokuElement elem = new SudokuElement();
elem.x = x;
elem.y = y;
elem.digit= digit;
return elem;
class MyMouseListener extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
System.out.println("mouse clicked: x = " + e.getX() + " y = " + e.getY());
currentElement.x = e.getX(); // It is better to use local coordinats 0 .. 9
currentElement.y = e.getY();
repaint();
class MyKeyListener extends KeyAdapter {
public void keyTyped(KeyEvent e) {
char ch = e.getKeyChar();
System.out.println("char typed= " + ch);
if( Character.isDigit(ch) ){ // Filter only digits
currentElement.digit = Character.digit(ch, 10);
elementList.add(currentElement.getCopy());
repaint();
}
Maybe you are looking for
-
LOCKED OUT OF MY MAC BOOK PRO! Help!!!
My Mac book pro is locked and do not know the password?? I never set a password up on my notebook so I'm not understanding how it just locked out of no wear?? Please help I need to access my files and can not get in.. Should I bring it to an Apple st
-
October 13, 2014 After reading the 10 pages of the Apple link and trying almost everything except adding a new account in the System Preferences, I went to Staples and bought a new box of Staples brand DVD+Rs and came home and tried them and they wor
-
Trying to download itunes keeps saying I don't have apple application support
I am trying to download Itunes to a new computer error message that there is no apple application support!! Any ideas??
-
Hy all! I'm having a problem to insert a WebService on a Page of a J2EE Web Application.Nowdays i have many webservices working in many pages of this project. But now i've developed webservices using complex type on java When i try do drop the webser
-
Since updating to 8.0 I have the frequent problem that title (not alt) tooltips do not display on sites where they used to work, e.g. xkcd but also others. Occasionally they do appear, but most of the time they do not. Rebooting doesn't consistently