Having trouble giving my JPanel functionality - java

*This is my first time using GUI, I seem to miss something my eye can't catch. The code looks fine to me however when i submit it to autoLab I get this error, which I cannot figure out where I went wrong.
{"correct":false,"feedback":"(class java.lang.NumberFormatException)
Error while attempting to call static method q2() on input [1]}
The problem question is q5:
Write a public static method named q5 that takes no parameters and returns a JPanel.
The panel will contain 1 JTextField with any number of columns, 1 JButton with any label,
and 1 JLabel. The panel will have functionality such that when a user enters a number into
the text field (we'll call this value x) and presses the button the label will display the
y-value of a parabola in standard form (https://www.desmos.com/calculator/zukjgk9iry)
where a=5.37, b=-6.07, and c=2.0 at the x-value from the text field
Hint: If you store y in the wrapper class Double instead of the primitive double you can
call toString on it to convert it to a string that can be used as the text for the label
Tip: After clicking the button you may have to resize your window to see the result since
the frame will not automatically resize to fit the new text
Do not create any JFrames in your problem set questions. Doing so will crash the
auto-grader since the grading server does not have a screen to display the JFrame.
Instead, only return the required JPanel in the problem set methods and test with a JFrame
in your main method, or other helper methods that are not graded
This is the code I wrote
public static JPanel q5() {
JPanel panel = new JPanel();
JTextField textField = new JTextField(5);
panel.add(textField);
JLabel label = new JLabel("hello!");
panel.add(label);
JButton button = new JButton("Click Me!");
panel.add(button);
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
int x = Integer.parseInt(textField.getText());
double a=5.37*Math.pow(x, 2);
double b=-6.07*x;
double c=2.0;
String answer= ("y = " + a+ b +c);
label.setText(answer);
}
});
return panel;
}
can you explain where I went wrong , thank you.

So, a NumberFormatException can occur when trying to parse a String, when the String does not contain a number. You did not give enough information to be sure, but I am going to presume that it is this line that causes the problem:
int x = Integer.parseInt(textField.getText());
One thing that strikes me as odd, is that you initialize the JTextField with 5 columns:
JTextField textField = new JTextField(5);
Is that what you want? If you wanted to pre-initialize the text field with a value of 5, you would have to do it like this:
JTextField textField = new JTextField("5");

Related

Struggling with BoxLayout in Java Swing

Whats up guys I'm struggling to understand how to implement BoxLayout or any layout in java swing. I have been looking at tutorials on oracle and others but i just can't get it to work. This is for an assignment in college so I would appreciate not giving me the solution straight up but maybe just point me in the right direction. I think the problem is my code is different to what is in the tutorials so I'm not sure what goes where.
import javax.swing.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.BoxLayout;
class Window extends JFrame implements ActionListener
{
JPanel panel = new JPanel();
JTextField input = new JTextField(10);
JButton but1 = new JButton ("Convert");
JLabel label = new JLabel();
JTextArea output = new JTextArea(1, 20);
public static void main(String[] args)
{
Window gui = new Window();
String[] days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
}
public Window()
{
super("Swing Window");
setSize(500, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel.add(input);
but1.addActionListener(this);
add(panel);
panel.add(output);
label.setText ("please enter celsius to be converted to Fahrenheit");
panel.add(but1);
panel.add(label);
setVisible(true);
}
public void actionPerformed(ActionEvent event)
{
String inputStr = input.getText();
inputStr = inputStr.trim();
double input = Double.parseDouble(inputStr);
double fahrenheit = input * 1.8 + 32;
if (event.getSource() == but1)
{
output.setText("Here is degrees celsius " + input + " converted `to Fahrenheit: " + fahrenheit);`
}
}
}
There is the executable code.
I skimmed your code, but did not execute it. As others already mentioned in the comments, it is helpful for you to describe what the program does and to describe what you expect/want it to do. Otherwise we are just guessing as to what is wrong and what would be correct.
From my reading of your code, I think you see nothing displayed. Correction: you did call add(); as indicated in one of your more recent comments Here are some notes/explanations:
Your method addComponentsToPane() is never called, thus you never create any BoxLayout objects
Recommendation: variable names begin with lowercase, and don't name a variable the same as a class; it easily creates confusion when reading the code. Thus don't name the argument Window.
Your method addComponentsToPane(), if it were called, creates a Layout object and sets it on the component passed to it but does not actually add any components. The name is thus misleading.
A JFrame's content pane has a BorderLayout by default. When components are added without any additional constraints, the BorderLayout chooses to place the components in a certain order (starting with BorderLayout.CENTER). See documentation of the JFrame class where it says the default is BorderLayout.
A JPanel, when created with the default constructor has a FlowLayout by default.
Since your program never changed the panel's layout manager, this is what gives you the left-to-right flow that you observed.
You want to set the panel's layout to a vertical BoxLayout before you add components to it

Adding 2 Integers using AWT

I'm trying to create a Java AWT program with these codes:
import javax.swing.*;
import java.awt.*;
public class Exer1 extends JFrame {
public Exer1(){
super ("Addition");
JLabel add1 = new JLabel("Enter 1st Integer: ");
JTextField jtf1 = new JTextField(10);
JLabel add2 = new JLabel("Enter 2nd Integer: ");
JTextField jtf2 = new JTextField(10);
JButton calculate = new JButton("Calculate");
FlowLayout flo = new FlowLayout();
setLayout(flo);
add(add1);
add(jtf1);
add(add2);
add(jtf2);
add(calculate);
setSize(200,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] a){
Exer1 ex1 = new Exer1();
}
}
My problem is HOW to add these 2 integers using JTextField. Can someone help me? Thank you so much. :)
You need to use ActionListener on your JButton.
Then you need to get int's from JTextField's and sum them like next:
calculate.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
int i1 = Integer.valueOf(jtf1.getText());
int i2 = Integer.valueOf(jtf2.getText());
System.out.println("sum=" + (i1 + i2));
} catch (Exception e1){
e1.printStackTrace();
}
}
});
Generally, you should create an event listener for click events on your button: Lesson: Writing Event Listeners. In that handler, you would take contents of your two text fields, convert them to integers:
Integer i1 = Integer.valueOf(jtf1.getText());
Then you can add those two integers and display them in another control or do anything else with them.
Start with How to Use Buttons, Check Boxes, and Radio Buttons and
How to Write an Action Listeners
This will provide you with the information you need to be able to tell when the user presses the button.
JTextField#getText then return's String. The problem then becomes a problem of converting a String to a int, which if you take the time, there are thousands of examples demonstrating how to achieve that
Once you've played around with oddities of converting String to a int, you could take a look at How to Use Spinners and How to Use Formatted Text Fields which perform there own validation on the values been entered

JFrame blinking when change its contents and pack()

I have a display that just shows a score on a page:
for example:
JIMBOB
Total Score: 22
When a point is scored an event is triggered that updates the score and redraws the new score on the page:
public void showScore(String username, int score)
{
contentPane.remove(layout.getLayoutComponent(BorderLayout.CENTER));
score.setText("<html>" + username + "<br/>Total Hits: " + totalHits + "</html>");
contentPane.add(score, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
Every time a point is scored this function is called, it removes the old score message adds an new one then packs and redraws.
The problem is that the window flickers when drawing the updated frame. And it seems for a split second to be displaying the info unformatted
contentPane is a Container
and frame is a JFrame
Invoking pack() will completely re-render the JFrame, a top-level, heavyweight container owned by the host platform. Instead, update the JComponent used to display the revised score. A complete example is cited here. Excerpted form RCStatus,
public class RCStatus extends JPanel implements Observer {
/** Update the game's status display. */
public void update(Observable model, Object arg) {
// invoke setText() here
}
}
See this answer for more on the observer pattern.
First of all, I would recommend to take a look at how to use JPanels and other GUI components in Swing. You could use a JPanel to be added to the contentPane of your JFrame. Add a desired LayoutManager that is fitting for your need and use it to position a JLabel according to your wishes.
When you call your showScore() method, use setText(String text) on a JLabel instead of the int score that you supply as parameter.
In order to set the text using a String, you need to transform your int score. You can do either of the following two things (but use the first option):
label.setText(String.valueOf(score));
label.setText("" + score);
If you want the score label to appear or disappear, add/ remove it from the JPanel that you added to the JFrame. After adding it, call setText() on the label to display the score. Then, since you reset the text of the label, you should call repaint() on the JPanel. If you choose to add/ remove the JLabel instead of just changing its text you should also call revalidate() on the JPanel.
So all in all the function should look something like this (this is incomplete), assuming totalHits is actually your score.
// declare instance fields before constructor
// both variables are reachable by showScore()
private JPanel scorePanel;
private JLabel scoreLabel;
// in constructor of your class
scorePanel = new JPanel(); // initialize the JPanel
scorePanel.setLayout(new BorderLayout()); // give it a layout
scoreLabel = new JLabel(); // initialize the label
frame.add(scorePanel); // add JPanel to your JFrame
// method obviously outside constructor
public void showScore(String username, int score)
{
// clear the JPanel that contains the JLabel to remove it
scorePanel.removeAll();
scoreLabel.setText("<html>" + username + "<br/>Total Hits: " + String.valueOf(score) + "</html>");
scorePanel.add(label, BorderLayout.CENTER);
scorePanel.revalidate();
scorePanel.repaint();
}
You could also declare and initialize the JPanel and JLabel in the showScore() method, making it more local. But then you would also need to call pack() on the JFrame and clear the previous JPanel from it every time you call the function.
.

Adding text next to a textfield to describe what data the user is expected to enter into it

I am trying to create a simple GUI that simulates a record store. I am still in the beginning stages.
I am running into trouble when I try to add text to describe what the user is expected to enter in the text field.
In addition, I am also having trouble positioning every textfield on its own line. In other words if there is space for two textfields in one line, then it displays in one line, and I am trying to display every text field on its own line.
This is what I tried so far:
item2 = new JTextField("sample text");
However the code above just adds default text within the text field, which is not what I need :/
I appreciate all the help in advance.
public class MyClass extends JFrame{
private JTextField item1;
private JTextField item2;
public MyClass(){
super("Matt's World of Music");
setLayout(new FlowLayout());
item1 = new JTextField();
item2 = new JTextField();
add(item1);
add(item2);
thehandler handler = new thehandler();
item1.addActionListener(handler);
item2.addActionListener(handler);
}
}
For your first problem, you need to use a JLabel to display your text. The constructor is like this:
JLabel label = new JLabel("Your text here");
Works really well in GUI.
As for getting things on their own lines, I recommend a GridLayout. Easy to use.
In your constructor, before adding anything, you do:
setLayout(new GridLayout(rows,columns,x_spacing,y_spacing));
x_spacing and y_spacing are both integers that determine the space between elements horizontally and vertically.
Then add like you have done. Fiddle around with it and you'll get it worked out.
So your final would look like:
setLayout(new GridLayout(2,2,10,10));
add(new JLabel("Text 1"));
add(text1);
add(new JLabel("text 2"));
add(text2);
You could just use a JLabel to label your textfields.
JLabel label1 = new JLabel("Item 1: ");
add(label1);
add(item1);
If you really want text inside the fields, you could set the text in the field with the constructor, and then add a MouseListener to clear the text on click:
item1 = new JTextField("Text");
item1.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (item1.getText().equals("Text")) // User has not entered text yet
item1.setText("");
}
});
Or, (probably better) use a FocusListener:
item1 = new JTextField("Text");
item1.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
if (item1.getText().equals("Text")) // User has not entered text yet
item1.setText("");
}
public void focusLost(FocusEvent e) {
if (item1.getText().equals("")) // User did not enter text
item1.setText("Text");
}
});
As for layout, to force a separate line, you use use a Box.
Box itemBox = Box.createVerticalBox();
itemBox.add(item1);
itemBox.add(item2);
add(itemBox);
Make:
item1 = new JTextField(10);
item2 = new JTextField(10);
that should solve problem with width of JTextField.
For beginning use GridLayout to display JTextField in one line. After that I strongly recomend using of MIG Layout http://www.migcalendar.com/miglayout/whitepaper.html.
put JLabel next to JTextField to describe what the user is expected to enter in the text field.
JLabel lbl = new JLabel("Description");
or you could also consider using of toolTipText:
item1.setToolTipText("This is description");
For making a form in Java Swing, I always recommend the FormLayout of JGoodies, which is designed to ... create forms. The links contains an example code snippet, which I just copy-pasted here to illustrate how easy it is:
public JComponent buildContent() {
FormLayout layout = new FormLayout(
"$label, $label-component-gap, [100dlu, pref]",
"p, $lg, p, $lg, p");
PanelBuilder builder = new PanelBuilder(layout);
builder.addLabel("&Title:", CC.xy(1, 1));
builder.add(titleField, CC.xy(3, 1));
builder.addLabel("&Author:", CC.xy(1, 3));
builder.add(auhtorField, CC.xy(3, 3));
builder.addLabel("&Price:", CC.xy(1, 5));
builder.add(priceField, CC.xy(3, 5));
return builder.getPanel();
}
Now for the description:
Use a label in front of the textfield to give a very short description
You can put a longer description in the textfield as suggested by #Alden. However, if the textfield is for short input, nobody will be able to read the description
You can use a tooltip (JComponent#setTooltipText) to put a longer description. Those tooltips also accept basic html which allows some formatting. Drawback of the tooltips is that the user of your application has to 'discover' that feature as there is no clear indication those are available
You can put a "help-icon" (like e.g. a question mark) after each text field (use a JButton with only an icon) where on click you show a dialog with a description (e.g. by using the JOptionPane class)
You can put one "help-icon" on each form which shows a dialog with a description for all fields.
Note for the dialog suggestion: I wouldn't make it a model one, allowing users to open the dialog and leave it open until they are finished filling in the form

Overriding the paint method in JTextField to draw text

I am wishing to draw a number onto a JTextField by overwriting the paint method. So that when the user edits the text field the number doesn't disappear. However, at the moment, the number isn't appearing at all, I have tried:
public void paintComponent(Graphics g) {
super.paintComponent(g);
if(number != 0){
g.setColor(Color.RED);
g.drawString(String.valueOf(number),0,0);
}
}
Any ideas, is this even possible?
Try to play with Y position in the g.drawString(String.valueOf(number),0,0); call. E.g. use getHeight()/2
..when the user edits the text field the number doesn't disappear.
As pointed out by #mKorbel, there is no need to override a JTextField in order to get red numbers, simply configure it using the public methods. OTOH..
g.drawString(String.valueOf(number),0,0);
If this is really all about numbers, perhaps the best approach is to use a JSpinner with a SpinnerNumberModel, and set a custom SpinnerUI.
Why don't you just add a small JLabel to the front of the JTextField? The JLabel could contain the number, and because it isn't editable it will always be there no matter what the user changes in the JTextField. You could also format the JLabel to make it red by calling setForeground(Color.RED);. This might be a much simpler solution?
For example, instead of doing this...
JPanel panel = new JPanel(new BorderLayout());
JTextField textfield = new JTextField("Hello");
panel.add(textfield,BorderLayout.CENTER);
You might do something like this...
JPanel panel = new JPanel(new BorderLayout());
JTextField textfield = new JTextField("Hello");
panel.add(textfield,BorderLayout.CENTER);
JLabel label = new JLabel("1.");
label.setForeground(Color.RED);
panel.add(label,BorderLayout.WEST);
Which adds a red JLabel to the left of the JTextField, and because you're using BorderLayout for the JPanel then it automatically makes the JLabel the smallest it can possibly be.
maybe there no reason override paintComponent() for JTextField, instead of use
JTextField.setBackground()
JTextField.setForeground()
JTextField.setFont()
JTextField.setHorizontalAlignment(javax.swing.SwingConstants.LEFT)
some hacks are possible by put there Html colored or special formatted text
EDIT
maybe this question is about
filtering KeyEvents in the Document / DocumentListener
or
JFormattedTextField with Number Formatter

Categories

Resources