How to get a decimal point from a virtual number pad? - java

I am trying to get the Decimal point to display with the click of an GUI button. I using the method below, which works fine for the numbers but not the decimal point. Any advise would be great. thanks
private void displayWeightedquantity(ActionEvent event){
JButton currentButton = null;
JButton[] numberButtonsarray = {bnDecimal,bnZero,bnOne, bnTwo, bnThree, bnFour, bnFive,bnSix,bnSeven,
bnEight,bnNine};
currentButton = (JButton)event.getSource();
for (int i = 0; i <numberButtonsarray.length; i++){
if (currentButton == numberButtonsarray[i]){
lbDisplayitemQty.setText(lbDisplayitemQty.getText() + currentButton.getText());
break;
}
}
}
My virtual numberpad :

I suspect the problem is else where in your code.
The test I set up works find.
You need to provide a functional example the shows the problem, not just a code snippet.
Also, make sure that the decimal button has it's action listener attached

Related

Is there a better/shorter syntax for this?

I want to make it shorter, making them all true in one line, I don't know if this is possible
bckBtn.setEnabled(true);
cBtn.setEnabled(true);
addBtn.setEnabled(true);
btn7.setEnabled(true);
someone gave me this line but I couldn't understand it
Streams.of(obj1, obj2).forEach(obj -> obj.setEnable(true));
sorry if the question was easy, I'm new to java.
thanks again.
Here’s the simplest, pre-java 8 and conceptually easiest, code I could come up with.
for (Button button : Arrays.asList(bckBtn, cBtn, addBtn, etc)) {
button.setEnabled(true);
}
Try this:
Button[] buttons = {bckBtn, cBtn, addBtn, ...};
for (int i = 0; i < buttons.length; i++)
{
Button temp = buttons[i]; // seconds reference to the buttons[i] object
temp.setEnabled(true);
}

How can I solve Java JLabel issues in application? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am quite new to Java. I decided to code tic-tac-toe as practice (from scratch).
Anyway, I am trying to have the 'JLabel label' change when I click; going from 1, then 2, etc. Eventually, it will change to something other than numbers. But, for now, it works for a test.
The 'System.out.println("Number of clicks: " + mouseIn);' works fine, and produces the output I want. A picture of the console and JFrame/JPanel/JLabel can be seen here:
(The little 1 in the JFrame is the JLabel. I want to match what is output in the console.
I have googled, and searched, and tried everything I know (which ain't much!) and I can't get the dang thing to work...I'm just asking for some guidance. Main method just includes building of JFrame/Panel.
Code below:
From the main class, called (namone.java [named it this for my own reasons]):
public void run(JPanel p) //Takes panel from main method {
for(int i = 0; i < ticList.length; i++){
ticList[i] = new JButton(buttonText); //For every position in
//ticList[], create a JButton object
p.add(ticList[i]);
ticList[i].setPreferredSize(new Dimension(140,140));
ticList[i].addMouseListener(mouse); //Load mouseListner
}
//Set mouseIn to click value in MouseEvents Class
int mouseIn = mouse.getClicks();
//Set text value to text value in MouseEvents class
text = mouse.getText();
//Output...
System.out.println("Number of clicks: " + mouseIn); //For testing
String mouse = Integer.toString(mouseIn); //Convert mouseIn value (from MouseEvents.java) to mouse
JLabel label = new JLabel(); //New JLabel
p.add(label); //Add label to screen
label.setText(mouse); //Set the text of the label to value of mouse
System.out.println(mouse); //For testing
//So I can see if it's working (clicks wise)
}
And then the code from my MouseEvents.java class:
public class MouseEvents extends namone implements MouseListener {
int clicks = 1;
String text = "first"; //For testing purposes
public namone game = new namone();
public int getClicks(){
return clicks;
}
public String getText(){
return text;
}
public int intToString(){
Integer.toString(clicks);
return clicks;
}
#Override
public void mouseClicked(MouseEvent e) {
clicks++;
intToString();
JPanel p = new JPanel();
text = "" + clicks;
game.run(p);
}
As I said. I am very new to Java and I'm trying to learn how to develop applications with it. I'm sure it's caused by my own ignorance.
Thanks.
Assuming that mouse is of type MouseEvents that you write, one possibility is that you need to pass mouse.getText() to your call to label.setText(.).
Regardless, the way you set up your game is a bit strange to me. What is the reason to create a brand new JPanel every time someone clicks? Why not maintain the original JPanel and update it instead. I personally would attach a custom ActionListener to each JButton that runs some code everytime the button is clicked. If this ActionListener is an inner class, it can also view variables in the scope that the JButton is defined.

Changing label text when button is clicked

I am trying to create a swing app that is a quiz. I need the jLabel to change on a button click but when I click the button, the app locks up. Can someone point me in the right direction?
My button click code is below:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String[] questions = {"test0","test1","test2","test3","test4","test5","test6"};
String[] answers = {"","","","","","",""};
int i = 0;
do {
jLabel2.setText(questions[i]);
index.setText(String.valueOf(i));
if (txtAnswer.getText().toLowerCase().equals(answers[i].toLowerCase())) {
i++;
jLabel2.setText(questions[i]);
}
else {
add(lblWrong);
}
}
while(i < 7);
}
I am getting a warning that the evt parameter has not been used, could this be a problem?
Thank you
You don't want the do while loop. It's trapping you in the button press method as if you get an answer wrong you keep entering the else and can't leave it, stopping the app from working. Replace it with an if statement checking if i < 7.
In the else condition of your loop, you don't add 1 to i at all - therefore you can potentially end up in the situation where it's never incremented, thus it will be an infinite loop (locking your program up.)

How to find out which textfield was typed into by the user in a Java JtextField?

I have the following code:
int[] matrix = new int[9][9];
(for int x = 0; x <= 8; x++){
(for int y = 0; y <= 8; x++){
JtextField matrix[x][y] = new JtextField(“Matrix" x + y)
int[] coords = new int[2];
coords[0] = x;
coords[1] = y;
matrix[x][y].putClientProperty("coords", coords);
matrix[x][y].setText(game[x][y]);
}
}
After the loops end, I need a way of finding out which textfield the user typed into (the user also hits enter). So:
1. How do I check if a JtextField has been edited without knowing which one it is or its name?
2. How do I check which "coords" the textfield is positioned at? I have an idea of how to do it, but for some reason I cannot code it.
I feel like the answer is staring me right in the face, but its late, I'm tired, and I'm getting flustered. Thanks!
The answer depends on what you want to achieve.
If you're only interested in the end result, you could use an ActionListener (for when the user hits Enter) and a FocusListener for when they don't and leave the field any way (assuming you want to know this)
When the respective event occurs, you can inspect the source of the event by using getSource. Now this returns Object, but you can use instanceof to determine if the object can be cast to a JTextField...
For example...
Object source = evt.getSource();
if (source instanceof JTextField) {
JTextField field = (JTextField)source;
int[] coords = field.getClientProperty("coords");
}
Take a look at How to write an Action Listener and How to write a Focus Listener for more details.
Depending on your needs, you could also take a look at Validating Input

Java ClipBoard Problem

I am writing a GUI for animation in Java. I am completely stumped on one element. I have a 2 JTextAreas that are called InputText, and OutputText where the input is copied to the output area with the use of a copy Jbutton. I then have a Next and Previous Button that should switch through frames on the OutputText area. I used a JLabel as a counter in between these two buttons.
What I am trying to do is use the clipboard to hold each "frame" if you will, on the Output JTextArea as I flip through the counter. As well as return the text once I flip backwards through the counter. Is this even possible? I have looked through multiple links online that describe Clipboard usage, but none of the examples that I have come across give a solid understanding how to do this.
Please see code below:
*Note I have left out unimportant elements that I already know work! Thanks!
This is called at the top of my Java file:
private Clipboard clipbd = getToolkit().getSystemClipboard();
public static final int MAX_COUNT = 10;
//sets maximum for count
public static final int MIN_COUNT = 1;
//sets minimum for count
private int count = 1;
//sets up integer for counter
This is called in the ActionListener:
public void actionPerformed ( ActionEvent event ) {
boolean status = false;
String OutputText1;
if(event.getSource()== CopyButton){
//get text from InputText
OutputText1 = InputText.getText();
//put text into OutputText field
OutputText.setText(OutputText1);
}//end if for CopyButton
if(event.getSource() == NextButton){
//LabelOutPut.setText("Next");
if (count < MAX_COUNT) {
count++;
}//end if
LabelCounter.setText("" + count);
OutputText.setText("");
}//end if for NextButton
if(event.getSource() == PreviousButton){
//LabelOutPut.setText("Previous");
if(count > MIN_COUNT){
count--;
}//end if
LabelCounter.setText("" + count);
}//end if for PreviousButton
Why would you use a Clipboard to hold text. Just use a String and the data is in the control of your program. I don't see any reason to complicate your processing.
Also, follow standard Java naming conventions. Varible names should NOT start with an upper cased character.
LabelCounter ==> labelCounter
You only need the SystemClipboard if you want to get copied/pasted data from places outside your program. If you just have to copy between 2 places in your own program, and you need history etc... just use a variable in your code (string, or list of strings, or whatever) and just update this when they click the button. Camickr mentions the same as well...

Categories

Resources