Runtime error - JLabel.setText() - java

String [] texts= new String[26];
for(int a=0; a<26; a++){
String te=money[a].getText();
texts[a] = te;
box[a].setText(te);
}
In this code I want to set Text boxs and box is a JLabel. I created moneys which are also JLabel and has texts. I want that if I click on a box I wan to remove that box and money which has the same text with that box. For this I wrote this code:
for(clickLoop=0; clickLoop<26; clickLoop++){
box[clickLoop].addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
clickCount++;
if(clickCount == 0){
box[26].setVisible(false);
JLabel labelReference=(JLabel)e.getSource();
ortaPanel.remove(welcome);
ortaPanel.revalidate();
ortaPanel.repaint();
ortaPanel.add(labelReference).setBounds(390,480,im.getIconWidth(),im.getIconHeight());
System.out.println("a");
ortaPanel.add(six).setBounds(305, 465, s.getIconWidth(), s.getIconHeight());
labelReference.removeMouseListener(this);
}else if(clickCount == 6){
e.getComponent().setVisible(false);
JLabel labelReference=(JLabel)e.getSource();
ortaPanel.remove(six);
ortaPanel.revalidate();
ortaPanel.repaint();
//ortaPanel.add(labelReference).setBounds(390,480,im.getIconWidth(),im.getIconHeight());
ortaPanel.add(five).setBounds(305, 465, s.getIconWidth(), s.getIconHeight());
labelReference.removeMouseListener(this);
}else {
e.getComponent().setVisible(false);
String esles=((JLabel) e.getComponent()).getText();
for(int i=0; i<money.length; i++){
if(esles.equals(money[i].getText()) ){
sagPanel.remove(money[i]);
}
}
}
System.out.println(clickCount);
}
});
}
}
Some labels are working truely but most of them didnt work. I dont know why? There is one more question I want to ask: As you can see the code above I created text of box[i] same as text of money[i]. Instead of doing like that I want to make it randomly. I tried but did not achive. Do you know how can I do that? Thanx in advance.

Related

Display Array in a JTextArea with ability to scroll

I am creating a GUI that will allow the user to input Lake information for the state of Florida and then has the ability to display that lake information. I want the display information to be in a JOptionPane.showMessageDialog that has the ability to scroll through the ArrayList of all the lake names. I am able to add the lakes into the ArrayList but they will not display in my JOptionPane and it is blank. I know it is reading something in the ArrayList since it is opening that window. Here is the code below in snippets as the whole thing would be cra.
public static ArrayList<Lakes> lake = new ArrayList<Lakes>();
private JTextArea textAreaDisplay;
private JScrollPane spDisplay;
// this is called in my initComponent method to create both
textAreaDisplay = new JTextArea();
for (Object obj : lake)
{
textAreaDisplay.append(obj.toString() + " ");
}
spDisplay = new JScrollPane(textAreaDisplay);
textAreaDisplay.setLineWrap(true);
textAreaDisplay.setWrapStyleWord(true);
spDisplay.setPreferredSize(new Dimension(500, 500));
// this is called in my createEvents method. After creating lakes in the database
// it will display the else statement but it is empty
btnDisplayLake.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try
{
if (lake.size() == 0)
{
JOptionPane.showMessageDialog(null, "No Lakes in database!");
}
else
JOptionPane.showMessageDialog(null, spDisplay, "Display Lakes", JOptionPane.YES_NO_OPTION);
}
catch (Exception e1)
{
}
}
});
Thank you for any help you can provide. I have been racking my brain for a few days on this. Been able to get other stuff accomplished but coming back to this issue.
Some obvious issues:
textAreaDisplay = new JTextArea();
A JTextArea should be created with code like:
textAreaDisplay = new JTextArea(5, 20);
By specifying the row/column the text area will be able to calculate its own preferred size. Scrollbars should appear when the preferred size of the text area is greater than the size of the scroll pane.
spDisplay.setPreferredSize(new Dimension(500, 500));
Don't use setPreferredSize(). The scroll area will calculate its preferred size based on the preferred size of the text area.
textAreaDisplay.append(obj.toString() + " ");
I would think you want each Lake to show on a different line, so I would append "\n" instead of the space.
I was setting textAreaDisplay before anything was entered into the ArrayList and it would not run again after anything was entered. I moved the for loop down and into the actionPerformed event and works well now.
btnDisplayLake.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try
{
for (Object obj : lake)
{
textAreaDisplay.append(obj.toString() + "\n");
}
if (lake.size() == 0)
{
JOptionPane.showMessageDialog(null, "No Lakes in database!");
}
else
JOptionPane.showMessageDialog(null, spDisplay, "Display Lakes", JOptionPane.YES_NO_OPTION);
}
catch (Exception e1)
{

Java - Validation of TextField

(SOLVED) Issue 1: I am trying to add a simple verification to my 2 TextFields by checking its values. However, with this code below, I think whats happening is that the try/catch is called as the program starts up (which I tested with the System.out.println() code), therefore always resulting in an error. How can I make it such that this is called only after button 'Finish' is pressed?
(UNSOLVED) Issue 2: Following on from my first issue, how can I make it such that if either my if or my try/catch returns an 'error', then pressing the 'Finish' button doesn't end the code?
Code:
Dialog<Pair<String, Integer>> dialog = new Dialog();
dialog.setTitle("Add new values");
dialog.setHeaderText("Please input name and number");
ButtonType finishButton = new ButtonType("Finish", ButtonData.OK_DONE);
dialog.getDialogPane().getButtonTypes().addAll(finishButton, ButtonType.CANCEL);
GridPane grid = new GridPane();
grid.setHgap(10);
grid.setVgap(10);
TextField name = new TextField();
name.setPromptText("Name");
TextField size = new TextField();
number.setPromptText("Number");
grid.add(new Label("Name:"), 0, 1);
grid.add(eventName, 1, 1);
grid.add(new Label("Number:"), 0, 3);
grid.add(eventSize, 1, 3);
dialog.getDialogPane().setContent(grid);
//verification code below
if (eventName.getText() == null || eventName.getText() == "") {
grid.add(new Label("Name is required!"), 0, 0);
}
try {
int size = Integer.parseInt(eventSize.getText());
} catch (NumberFormatException e) {
grid.add(new Label("Size is required!"), 0, 1);
System.out.println("Test failed");
}
This is the code I am trying to learn off from: Here
Firstly, you must compare Strings using the .equals() method. I believe, but am not 100% certain, that the check for null is unnecessary. So, change:
if (eventName.getText() == null || eventName.getText() == "")
to
if (eventName.getText().equals(""))
I am unfamiliar with the Dialog class. However, when I need to implement something like this I like to use JDialog, and put it in a while loop:
JPanel p = new JPanel(new GridLayout(2,2));
JTextField nameField = new JTextField(5);
JTextField numberField = new JTextField(5);
JLabel nameLabel = new JLabel("Name");
JLabel numberLabel = new JLabel("Number");
p.add(nameLabel);
p.add(nameField);
p.add(numberLabel);
p.add(numberField);
while(true){
int result = JOptionPane.showConfirmDialog(null, p, "Please enter Name and Number.", JOptionPane.OK_CANCEL_OPTION);
if(result == JOptionPane.OK_OPTION){
if(nameField.getText().equals("")){
JOptionPane.showConfirmDialog(null, "Invalid input!");
}
else break;
}
}
This code should guide you on how you might be able to check for different inputs, and validate them accordingly. See JOptionPane for more details on the different dialogs you can open.
Hope this helps you.
Dont know if this will help but i made a button that sounds like what your trying to do
//taking input from pop up box
JTextField InputPosX = new JTextField(5);
JTextField InputNegX = new JTextField(5);
JTextField InputY = new JTextField(5);
JPanel ChangeAxisPanel = new JPanel();
ChangeAxisPanel.add(new JLabel("Max X:"));
ChangeAxisPanel.add(InputPosX);
ChangeAxisPanel.add(Box.createHorizontalStrut(15)); // a spacer
ChangeAxisPanel.add(new JLabel("Min X:"));
ChangeAxisPanel.add(InputNegX);
ChangeAxisPanel.add(Box.createHorizontalStrut(15)); // a spacer
ChangeAxisPanel.add(new JLabel("Y:"));
ChangeAxisPanel.add(InputY);
int result = JOptionPane.showConfirmDialog(null, ChangeAxisPanel,
"Please Enter X and Y Values", JOptionPane.OK_CANCEL_OPTION);
//if ok is pressed
if (result == JOptionPane.OK_OPTION) {
if(!(InputPosX.getText().isEmpty())){
defaultPosX=Integer.parseInt(InputPosX.getText());
}
if(!(InputNegX.getText().isEmpty())){
defaultNegX=Integer.parseInt(InputNegX.getText());
}
if(!(InputY.getText().isEmpty())){
defaultY=Integer.parseInt(InputY.getText());
}
}
}
});
most of this was gathered from
Here its a good link for gui input windows. also if you are looking for a simpler method you may want to look into jbutton's you can use it to call this window
Jbutton
anyways hope this helped

Wait until text is not present in textbox selenium

Below is the scenario I am trying to automate:
1) Some text is already present in Textbox.
2) Click on Radio button.
3) Processing popup is displayed for few seconds. After popup disappears the textbox
becomes blank
4) After textbox is blank then I have to enter different value in text box.
Please help me, how to wait till textbox value is blank.
I am automating with IE driver.
Thanks In advance
I would try:
int timeout = 10; // depends on your needs
WebDriverWait myWait= new WebDriverWait(driver,timeout);
myWait.until(ExpectedCondition.textToBePresentInElementValue(By locator, String text))
-- with empty string passed as text argument
You can try something like this :-
public void waitUntilTextNotToBeInWebElement(WebElement element, String textValue) {
int timer = 0;
final int pollInterval = 500;
while (timer < MAX_TIME*1000) {
if (element.getText().equalsIgnoreCase(textValue)) {
sleep(500);
timer += pollInterval;
} else {
return;
}
}
throw new TimeoutException("Maximum time exceeded.");
}
Hi there is two possible way through which you can do this
1.Use Expected condition
// after you have clicked on radio button and it does some processing
WebDriverWait wait = new WebDriverWait(driver,30);
wait.until(ExpectedConditions.invisibilityOfElementWithText(locator, "your text"));
// now perform your operation
use if else
// get the text of input box like below
String myInitialText = driver.findElement(By.xpath("")).getAttribute("value");
// click on radio button
// now apply the logic
if(myInitialText == null){
System.out.println("Input box is blank");
// perform next operation
}else{
Thread.sleep(5000);
}
// now fill the input box
Below code worked for me.
WebElement element=driver.findElement(By.id("ctl00_cphClaimFlow_tabcontainerClaimFlow_tabFulfillment_Shipping_ctl33_txtStreeAddress1"));
String myInitialText=element.getAttribute("value");
//click on radio btn
driver.findElement(By.id("ctl00_cphClaimFlow_tabcontainerClaimFlow_tabFulfillment_Shipping_ctl33_radNewAddress")).click();
logger.info("New Address radio button clicked");
System.out.println("1 "+myInitialText);
while(!myInitialText.equals("")){
try {
Thread.sleep(5000);
logger.info("Thread is sleeping");
//System.out.println("2 "+myInitialText);
myInitialText=driver.findElement(By.id("ctl00_cphClaimFlow_tabcontainerClaimFlow_tabFulfillment_Shipping_ctl33_txtStreeAddress1")).getAttribute("value");
//System.out.println("3 "+myInitialText);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
driver.findElement(By.id("ctl00_cphClaimFlow_tabcontainerClaimFlow_tabFulfillment_Shipping_ctl33_txtStreeAddress1")).sendKeys(td.getAddressLine1().get(0));
logger.info("Address Line1 entered");

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(...)
}
}

Creating Dialog from JOptionPane and working on OK_CANCEL_OPTION [duplicate]

This question already has answers here:
Java Dialog - Find out if OK is clicked?
(4 answers)
Closed 6 years ago.
I have a custom dialog box that collects two strings from the user. I use OK_CANCEL_OPTION for the option type when creating the dialog. Evertyhings works except when a user clicks cancel or closes the dialog it has the same effect has clicking the OK button.
How can i handle the cancel and close events?
Heres the code I'm talking about:
JTextField topicTitle = new JTextField();
JTextField topicDesc = new JTextField();
Object[] message = {"Title: ", topicTitle, "Description: ", topicDesc};
JOptionPane pane = new JOptionPane(message, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
JDialog getTopicDialog = pane.createDialog(null, "New Topic");
getTopicDialog.setVisible(true);
// Do something here when OK is pressed but just dispose when cancel is pressed.
/Note: Please Don't Suggest me the way of JOptionPane.ShowOptionDialog(*****);** for this issue because i know that way but i need above mentioned way of doing and setting actions for "OK" and "CANCEL" buttons.*/
This works for me:
...
JOptionPane pane = new JOptionPane(message, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
JDialog getTopicDialog = pane.createDialog(null, "New Topic");
getTopicDialog.setVisible(true);
if(null == pane.getValue()) {
System.out.println("User closed dialog");
}
else {
switch(((Integer)pane.getValue()).intValue()) {
case JOptionPane.OK_OPTION:
System.out.println("User selected OK");
break;
case JOptionPane.CANCEL_OPTION:
System.out.println("User selected Cancel");
break;
default:
System.out.println("User selected " + pane.getValue());
}
}
According to the documentation you can use pane.getValue() to know which button was clicked.
From documentation:
Direct Use: To create and use an JOptionPane directly, the standard pattern is roughly as follows:
JOptionPane pane = new JOptionPane(arguments);
pane.set.Xxxx(...); // Configure
JDialog dialog = pane.createDialog(parentComponent, title);
dialog.show();
Object selectedValue = pane.getValue();
if(selectedValue == null)
return CLOSED_OPTION;
//If there is not an array of option buttons:
if(options == null) {
if(selectedValue instanceof Integer)
return ((Integer)selectedValue).intValue();
return CLOSED_OPTION;
}
//If there is an array of option buttons:
for(int counter = 0, maxCounter = options.length;
counter < maxCounter; counter++) {
if(options[counter].equals(selectedValue))
return counter;
}
return CLOSED_OPTION;
Hope it helps,

Categories