How to get text from JTextField? [duplicate] - java

This question already has answers here:
Retrieving JTextField Contents Like Scanner
(2 answers)
Closed 8 years ago.
I'm trying to understand the Scanner function, but I can't seem to understand it.
I'm making a program to calculate the BMI (body mass index) and it's practically done, except that I can't make the calculation! Everything works fine except for when I click the "ok" button.
Had to take away my code so my collegues won't copy my code, like they've made in the past, will be posting again after friday.

first thing there is no poblem with Scanner things and its not required when we use GUI.
its useful only for console input/output.
so when you get text it will be in string format so parse it to double like
String val = txt1.getText();
double valueDouble = Double.parseDouble(val);
and handle the parse exception using try/catch
so replace the piece of code below
Scanner dado1 = new Scanner(txt1.getText());
System.out.println(dado1);
if(dado1.hasNextDouble()){
tamanho = dado1.nextDouble();
}
Scanner dado2 = new Scanner(txt2.getText());
if(dado2.hasNextDouble()){
peso = dado2.nextDouble();
}
to
String t1 = txt1.getText();
if(!"".equals(t1))
tamanho = Double.parseDouble(t1);
String t2 = txt2.getText();
if(!"".equals(t2))
peso = Double.parseDouble(t2);
i tried to run your program but i got the exception saying -> container does not have parent attribute.
so what i did is i have added a parent container inside your ok button action listener
and it works well.
container to be added is
final JDesktopPane desk = new JDesktopPane();
setContentPane(desk);
to your
JOptionPane.showInternalMessageDialog(desk,"Seu IMC é:"+ (result/ peso));
but you have passed null as the first argement.
so it should become like below
ok.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
String t1 = txt1.getText();
if(!"".equals(t1))
tamanho = Double.parseDouble(t1);
String t2 = txt2.getText();
if(!"".equals(t2))
peso = Double.parseDouble(t2);
result = tamanho*tamanho;
if (ok != null){
System.out.println(result);
System.out.println(peso);
final JDesktopPane desk = new JDesktopPane();
setContentPane(desk);
JOptionPane.showInternalMessageDialog(desk,"Seu IMC é:"+ (result/ peso));
}
}
});

you may simply parse instead of Scanner:
tamanho = Double.parseDouble(txt1.getText());

Related

Local Notification NOT SHOWING CodeNameOne

I'm a CodeNameOne beginner. I'm trying to make a local notification, it doesn't seem to work,I don't get anything displayed. here's the start function.
Is there anything missing? Should I add variables in the build settings?
public void start() {
if(current != null){
current.show();
return;
}
Form hi = new Form("Hi World", BoxLayout.y());
hi.add(new Label("Hi World"));
hi.show();
LocalNotification n = new LocalNotification();
n.setId("demo-notification");
n.setAlertBody("It's time to take a break and look at me");
n.setAlertTitle("Break Time!");
//n.setAlertSound("/notification_sound_beep-01a.mp3");
// alert sound file name must begin with notification_sound
Display.getInstance().scheduleLocalNotification(
n,
System.currentTimeMillis() + 10 * 1000, // fire date/time
LocalNotification.REPEAT_MINUTE // Whether to repeat and what frequency
);
}

Text Highlighting with PDFClown without using PDF Annotations

I've started using PDFClown some weeks ago. My purpose is multi-word highlighting, mainly on newspapers. Starting from the org.pdfclown.samples.cli.TextHighlightSample example, I succeeded in extracting multi-word positions and highlighting them. I even solved some problems due to text ordering and matching in most cases.
Unfortunately my framework includes FPDI and it does not consider PDFAnnotations. So, all the content outside of a page content stream, like text annotations and other so called markup annotations, get lost.
So any suggestion on creating "Text Highlighting" with PdfClown and without using PDF annotations?
To not have the highlight in an annotation but instead in the actual page content stream, one has to put the graphic commandos into the page content stream which in case of the org.pdfclown.samples.cli.TextHighlightSample example are implicitly put into the normal annotation appearance stream.
This can be implemented like this:
org.pdfclown.files.File file = new org.pdfclown.files.File(resource);
Pattern pattern = Pattern.compile("S", Pattern.CASE_INSENSITIVE);
TextExtractor textExtractor = new TextExtractor(true, true);
for (final Page page : file.getDocument().getPages())
{
final List<Quad> highlightQuads = new ArrayList<Quad>();
Map<Rectangle2D, List<ITextString>> textStrings = textExtractor.extract(page);
final Matcher matcher = pattern.matcher(TextExtractor.toString(textStrings));
textExtractor.filter(textStrings, new TextExtractor.IIntervalFilter()
{
#Override
public boolean hasNext()
{
return matcher.find();
}
#Override
public Interval<Integer> next()
{
return new Interval<Integer>(matcher.start(), matcher.end());
}
#Override
public void process(Interval<Integer> interval, ITextString match)
{
{
Rectangle2D textBox = null;
for (TextChar textChar : match.getTextChars())
{
Rectangle2D textCharBox = textChar.getBox();
if (textBox == null)
{
textBox = (Rectangle2D) textCharBox.clone();
}
else
{
if (textCharBox.getY() > textBox.getMaxY())
{
highlightQuads.add(Quad.get(textBox));
textBox = (Rectangle2D) textCharBox.clone();
}
else
{
textBox.add(textCharBox);
}
}
}
highlightQuads.add(Quad.get(textBox));
}
}
#Override
public void remove()
{
throw new UnsupportedOperationException();
}
});
// Highlight the text pattern match!
ExtGState defaultExtGState = new ExtGState(file.getDocument());
defaultExtGState.setAlphaShape(false);
defaultExtGState.setBlendMode(Arrays.asList(BlendModeEnum.Multiply));
PrimitiveComposer composer = new PrimitiveComposer(page);
composer.getScanner().moveEnd();
// TODO: reset graphics state here.
composer.applyState(defaultExtGState);
composer.setFillColor(new DeviceRGBColor(1, 1, 0));
{
for (Quad markupBox : highlightQuads)
{
Point2D[] points = markupBox.getPoints();
double markupBoxHeight = points[3].getY() - points[0].getY();
double markupBoxMargin = markupBoxHeight * .25;
composer.drawCurve(new Point2D.Double(points[3].getX(), points[3].getY()),
new Point2D.Double(points[0].getX(), points[0].getY()),
new Point2D.Double(points[3].getX() - markupBoxMargin, points[3].getY() - markupBoxMargin),
new Point2D.Double(points[0].getX() - markupBoxMargin, points[0].getY() + markupBoxMargin));
composer.drawLine(new Point2D.Double(points[1].getX(), points[1].getY()));
composer.drawCurve(new Point2D.Double(points[2].getX(), points[2].getY()),
new Point2D.Double(points[1].getX() + markupBoxMargin, points[1].getY() + markupBoxMargin),
new Point2D.Double(points[2].getX() + markupBoxMargin, points[2].getY() - markupBoxMargin));
composer.fill();
}
}
composer.flush();
}
file.save(new File(RESULT_FOLDER, "multiPage-highlight-content.pdf"), SerializationModeEnum.Incremental);
(HighlightInContent.java method testHighlightInContent)
You will recognize the text extraction frame from the original example. Merely now the quads from a whole page are collected before they are processed, and the processing code (which mostly has been borrowed from TextMarkup.refreshAppearance()) draws forms representing the quads into the page content.
Beware, to make this work generically, the graphics state has to be reset before inserting the new instructions (the position is marked with a TODO comment). This can be done either by applying save/restore state or by actually counteracting unwanted changed state entries. Unfortunately I did not see how to do the former in PDF Clown and have not yet had the time to do the latter.

Libgdx scrollpane issue for a chatwindow class

I am having an issue with using a scrollpane in libgdx. It is going to be used for a chatwindow class. When you press enter the message will be added to the window and you will scroll to the latest posted message..However it doesn't. It misses one message and scrolls to the one before the latest message. Below I've posted the chatwindow class and the method that adds input to it. The textAreaholder is a table that holds everything. The chatField is where you input what you want to post to the chat. The chatarea is the textfield that then becomes added to the table. But as stated..it doesn't scroll properly, the error properly lies somewhere in the keyTyped method.
public ChatWindow(final Pipe<String> chatPipe) {
this.chatPipe = chatPipe;
messageFieldCounter = 0;
white = new BitmapFont(Gdx.files.internal("fonts/ChatWindowText.fnt"), false);
fontSize = white.getLineHeight();
white.scale(TEXT_SCALE);
final TextFilter filter = new TextFilter();
/* Making a textfield style */
textFieldStyle = new TextFieldStyle();
textFieldStyle.fontColor = Color.WHITE;
textFieldStyle.font = white;
textFieldStyle.focusedFontColor = Color.CYAN;
/*Area where all chat appears*/
textAreaHolder = new Table();
textAreaHolder.debug();
/*Applies the scrollpane to the chat area*/
scrollPane = new ScrollPane(textAreaHolder);
scrollPane.setForceScroll(false, true);
scrollPane.setFlickScroll(true);
scrollPane.setOverscroll(false, false);
/*Input chat*/
chatField = new TextField("", textFieldStyle);
chatField.setTextFieldFilter(filter);
/*Tries to make the textField react on enter?*/
chatField.setTextFieldListener(new TextFieldListener() {
#Override
public void keyTyped(final TextField textField, final char key) {
if (key == '\n' || key == '\r') {
if (messageFieldCounter <= 50) {
textAreaHolder.row();
StringBuilder message = new StringBuilder(); //Creates the message
message.append(chatField.getText()); //Appends the chatfield entry
TextArea chatArea = new TextArea(message.toString(), textFieldStyle); //Creates a chatArea with the message
chatArea.setHeight(fontSize + 1);
chatArea.setDisabled(true);
chatArea.setTextFieldFilter(filter);
textAreaHolder.add(chatArea).height(CHAT_INPUT_HEIGHT).width(CHAT_WIDTH);
scrollPane.scrollToCenter(0, 0, 0, 0);
//Scrolls to latest input
chatField.setText("");
//InputDecider.inputDecision(message.toString(), chatPipe); //TODO: Change the filter
//chatPipe.put(message.toString()); //TODO: testing
}
}
}
});
Problems could occur, because you're using scrollPane.scrollToCenter(float x, float y, float width, float height) with zero parameters:
scrollPane.scrollToCenter(0, 0, 0, 0);
scrollToCenter method requires that parameters to be correctly supplied. So, try to supply message bounds.
The second reason could be because you call scrollToCenter before table do layout itself. So, try overwrite table's layout method and call scrollToCenter after:
#Override
public void layout()
{
super.layout();
if (new_messages_added)
{
scrollPane.scrollToCenter(...)
}
}

jsoup how to reach dropdownlist

Hello everybody I want to get the data from
http://sansoyunlari.hurriyet.com.tr/SayisalLoto/SayisalLotoSonuclari.aspx this adress by using jsoup ı can get them but only the latest results . There is a dropdownlist on the website which consists dates how can I reach other dates ? by the way I will move these codes to the android these are codes which is written in netbeans for now. ı will put a dropdownlist to my android program which get the data from this adress and also the results.
these are my java codes I wrote until now
public static void main(String[] args) {
String adres = "http://sansoyunlari.hurriyet.com.tr/SayisalLoto/SayisalLotoSonuclari.aspx";
ArrayList sayi = new ArrayList<>();
sayi.add("six");
sayi.add("five");
sayi.add("four");
sayi.add("three");
sayi.add("two");
sayi.add("one");
//Sayısal Loto
try {
Document doc = Jsoup.connect(adres).get();
Elements sonuclar = doc.select("div.hurriyet2010_so_sanstopu_no_bg");
//1. yi manuel almak gerek ilk yoldan çünkü resut diye kodlanmış
Elements sonuclar1 = doc.select("span#_ctl0_ContentPlaceHolder1_lblresut"+sayi.get(sayi.size()-1));
Element numaralar = sonuclar1.first();
System.out.println(numaralar.text());
//yol 1 numaraları almak için
for (int i = sonuclar.size();i>1;i--)
{
sonuclar1 = doc.select("span#_ctl0_ContentPlaceHolder1_lblresult"+sayi.get(i-2));
Element numaralar1 = sonuclar1.first();
System.out.println(numaralar1.text());
}
//yol 2 numaraları almak için
// for(Element el : sonuclar)
// {
// System.out.println(el.text());
// }
//kazanan kişi sayısı ve ikramiye tutarı için
for(int i = 0;i<4;i++)
{
int b = 6 -i;
System.out.println(b + " bilen kişi sayısı :");
sonuclar = doc.select("span#_ctl0_ContentPlaceHolder1_lblluckycount"+sayi.get(i));
Element el = sonuclar.first();
System.out.println(el.text());
System.out.println("Kişi başına düşen ikramiye :");
sonuclar = doc.select("span#_ctl0_ContentPlaceHolder1_lblluckyamount"+sayi.get(i));
el = sonuclar.first();
System.out.println(el.text());
}
}
catch(Exception e){
}
}
To get the select item you should do:
Element select = doc.select("#_ctl0_ContentPlaceHolder1_ddlSayisalLotoDates").first();
Now the children of this elements are the "option" items you want:
for (Element e : select) {
String date = e.text();
}
edit
I looked at the html source. In order to get the right page you need to do a post request at the URL "http://sansoyunlari.hurriyet.com.tr/SayisalLoto/SayisalLotoSonuclari.aspx" with following params:
__EVENTARGUMENT = empty
__EVENTTARGET = _ctl0$ContentPlaceHolder1$ddlSayisalLotoDates
__EVENTVALIDATION = a random value that you get from the html page
__LASTFOCUS = empty
__VIEWSTATE = another random value
_ctl0:ContentPlaceHolder1:ddlSayisalLotoDates = The ID of the date you want to search (i.e. 884 for 19 Ekim 2013)
txtSearch = can be empty
As you can see, it's quite annoying scraping an ASP.NET webpage..
Use an application like Fiddler (or another one) to find the params you need to post (hidden inputs, session cookies, your selected input). Probably you're missing some of them.
Hope it helps.

How to display frame only when required & set frame to appear on top all the time?

My program will alert users when data (stock name & price) in the database matches with the data (stock name and price) from Yahoo Finance. With the help of HarryJoy i'm able to implement a pop up notification.
Problem is the pop up location on the screen is based on the database loop (int db). The frame will pop even if data doesn't match.
How can I set a counter or some method to pop up the frame only when database data = Yahoo Finance data? Also, my notification panels appears to be behind the main frame. How can make the panels appear on top of my main frame?
I hope I've given enough information, please ask if still unclear. Any guidance will be appreciated! Thanks!
In the database (using code sample only to display my explanation in order, source code below).
Object 1 = match
Object 2 = doesn't match (hence there's a gap)
Object 3 = match
Object 4 = match
Screenshot:
Code:
for (int db=0; db<= rowCount; db++)
{
Object popSymbol = table.getModel().getValueAt(db, 0);
String popupSymbol = popSymbol.toString();
Object popValue = table.getModel().getValueAt(db, 1);
String str = popValue.toString();
double popStockValue = Double.valueOf(str).doubleValue();
String stockNameDB = popupSymbol;
StockPara stock = YahooStock.getInstance().getStockPrice(stockNameDB);
double stockPriceDB = Math.round(stock.getPrice());
final JFrame popUpFrame;
final JPanel popupPanel;
if (stockPriceDB == popStockValue)
{
String header = "Stock: " + stock.getTicker() + " is now # " + stock.getPrice();
String message = "";
popUpFrame = new JFrame();
popUpFrame.setSize(320,90);
popUpFrame.setUndecorated(true);
popUpFrame.getContentPane().setLayout(null);
popupPanel = new JPanel();
popupPanel.setBorder(new LineBorder(new Color(0, 0, 0)));
popupPanel.setBounds(0, 0, 320, 90);
getContentPane().add(popupPanel);
popupPanel.setBackground(new Color(255, 255, 224));
popupPanel.setLayout(null);
popUpFrame.add(popupPanel);
// Other labels, images, etc.
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Insets toolHeight = Toolkit.getDefaultToolkit().getScreenInsets(popUpFrame.getGraphicsConfiguration());
popUpFrame.setLocation(screenSize.width - popUpFrame.getWidth(), screenSize.height - toolHeight.bottom - (popUpFrame.getHeight() * (db+1)));
}
}
To solve your issue quickly, simply create an additional counter (int counter = 0;). Then use that counter instead of db to position your popUpFrame and right after that increment counter.
int counter = 0; // Initiate outside de loop
...
for(int db=0; db<= rowCount; db++) {
...
if (stockPriceDB == popStockValue) {
...
popUpFrame.setLocation(screenSize.width - popUpFrame.getWidth(),
screenSize.height - toolHeight.bottom - (popUpFrame.getHeight() * (counter+1)));
counter++;
}
}
To bring your frame to the front use:
popUpFrame.toFront()
and to force it to be always on top (although I would really not recommend that because it is more annoying for the user than anything else):
popUpFrame.setAlwaysOnTop(true);
This is not necessarily supported by all platforms.
for on top issue, use
notificationPanel.requestFocus();

Categories