Making a calculator in java, how to allow numeric inputs only - java

IM trying to make a calculator using Java/eclipse. How do I make that only numeric values can be typed into the text area? So when i run the application it runs perfectly. All the buttons are functioning perfectly. But I would like to have it only allow number input in the text area.
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import java.awt.TextField;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.text.ParseException;
import java.util.Scanner;
public class calculator_gui<reutrn> implements ActionListener {
JFrame frame = new JFrame("Calculator");
JPanel Panel = new JPanel (new java.awt.FlowLayout());
JTextArea text = new JTextArea(1,20);
JButton but1= new JButton("1");
JButton but2= new JButton("2");
JButton but3= new JButton("3");
JButton but4= new JButton("4");
JButton but5= new JButton("5");
JButton but6= new JButton("6");
JButton but7= new JButton("7");
JButton but8= new JButton("8");
JButton but9= new JButton("9");
JButton but0= new JButton("0");
JButton butadd= new JButton("+");
JButton butsub= new JButton("-");
JButton butmulti= new JButton("*");
JButton butdiv= new JButton("/");
JButton buteq= new JButton("=");
JButton butclear= new JButton("C");
Double number1,number2,result;
int addc=0,subc=0,multic=0,divc=0;
public void gui(){
Panel.setLayout(FlowLayout());
frame.setVisible(true);
frame.setBounds(100, 100, 450, 285);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// frame.setResizable(false);
frame.add(Panel);
Panel.setBackground(Color.green);
Panel.add(text);
text.setBounds(10, 32, 361, 29);
Panel.add(but1);
but1.setBackground(Color.red);
but1.setBounds(10, 81, 89, 23);
Panel.add(but2);
but2.setBounds(126, 81, 89, 23);
Panel.add(but3);
but3.setBounds(225, 81, 89, 23);
Panel.add(but4);
but4.setBounds(10, 115, 89, 23);
Panel.add(but5);
but5.setBounds(126, 115, 89, 23);
Panel.add(but6);
but6.setBounds(225, 115, 89, 23);
Panel.add(but7);
but7.setBounds(10, 149, 89, 23);
Panel.add(but8);
but8.setBounds(126, 149, 89, 23);
Panel.add(but9);
but9.setBounds(225, 149, 89, 23);
Panel.add(but0);
but0.setBounds(126, 183, 89, 23);
Panel.add(butadd);
butadd.setBounds(324, 81, 89, 23);
Panel.add(butsub);
butsub.setBounds(324, 115, 89, 23);
Panel.add(butmulti);
butmulti.setBounds(324, 183, 89, 23);
Panel.add(butdiv);
butdiv.setBounds(324, 149, 89, 23);
Panel.add(buteq);
buteq.setBounds(225, 183, 89, 23);
Panel.add(butclear);
butclear.setBounds(10, 183, 89, 23);
but1.addActionListener(this);
but2.addActionListener(this);
but3.addActionListener(this);
but4.addActionListener(this);
but5.addActionListener(this);
but6.addActionListener(this);
but7.addActionListener(this);
but8.addActionListener(this);
but9.addActionListener(this);
but0.addActionListener(this);
butadd.addActionListener(this);
butsub.addActionListener(this);
butmulti.addActionListener(this);
butdiv.addActionListener(this);
buteq.addActionListener(this);
butclear.addActionListener(this);
}
private LayoutManager FlowLayout() {
// TODO Auto-generated method stub
return null;
}
#Override
public void actionPerformed(ActionEvent e){
Object source = e.getSource();
if(source==butclear){
number1=0.0;
number2=0.0;
text.setText(null);
}
if(source==but1){
text.append("1");
}
if(source==but2){
text.append("2");
}
if(source==but3){
text.append("3");
}
if(source==but4){
text.append("4");
}
if(source==but5){
text.append("5");
}
if(source==but6){
text.append("6");
}
if(source==but7){
text.append("7");
}
if(source==but8){
text.append("8");
}
if(source==but9){
text.append("9");
}
if(source==but0){
text.append("0");
}
if(source==butadd){
number1=number_reader();
text.setText("");
addc=1;
subc=0;
multic=0;
divc=0;
}
if(source==butsub){
number1=number_reader();
text.setText("");
addc=0;
subc=1;
multic=0;
divc=0;
}
if(source==butmulti){
number1=number_reader();
text.setText("");
addc=0;
subc=0;
multic=1;
divc=0;
}
if(source==butdiv){
number1=number_reader();
text.setText("");
addc=0;
subc=0;
multic=0;
divc=1;
}
if(source==buteq){
number2=number_reader();
if(addc>0){
result=number1+number2;
text.setText(Double.toString(result));
}
if(subc>0){
result=number1-number2;
text.setText(Double.toString(result));
}
if(multic>0){
result=number1*number2;
text.setText(Double.toString(result));
}
}
if(divc>0){
result=number1/number2;
text.setText(Double.toString(result));
}
}
public double number_reader(){
Double num1;
String s;
s=text.getText();
num1=Double.valueOf(s);
return num1;
}
}

There are a number of things you can do.
Set an javax.swing.InputVerifier on your text area. This will keep people from tabbing out if they type something illegal. It probably isn't enough.
Set a custom Document for the JTextArea in its constructor. Use a subclass you write of PlainDocument, where you override its insertText method and reject non-numbers. This will take care of both typing and of cut-and-paste.
You will do better in your next attempt if you do not have one giant actionPerformed method for all the number and operation buttons. Instead, give each button a subclass of AbstractAction. The number buttons can share instances of one class.
JComponents, which include JButtons, can have client properties, so you can write code like
JButton but1= new JButton("1");
but1.setClientProperty("digit", "1"); // Why a string?
// Suppose you have a switch to use hexadecimals?
and then the action listener, which has access to the pressed button, can just call getClientProperty("digit") on it to find out what digit the user has chosen. For a small investment, you save a lot of repetitious code.
Finally, learn the model-view-controller architecture, or MVC. Don't do your manipulations directly on the text area. Without RFC, you will have many problems adding more operations, or switching to a RPN calculator.
Create a Model: This has objects for the accumulator and the new operand.
Create a View: The Swing setup.
Create a Controller: The objects that do the work. Your actions should be requests of the controller to do something. The controller should do it to the model, and then the model or the controller should refresh the view.
Also, your calculator class name is a bit weird. The name calculator_gui<reutrn> makes no sense; why a generic? Why violate Java standards? Just call it Calculator.
Added
The poster wants me to show how to turn the button creation coe into a loop. So, replace the ten lines:
JButton but1= new JButton("1");
JButton but2= new JButton("2");
JButton but3= new JButton("3");
JButton but4= new JButton("4");
JButton but5= new JButton("5");
JButton but6= new JButton("6");
JButton but7= new JButton("7");
JButton but8= new JButton("8");
JButton but9= new JButton("9");
JButton but0= new JButton("0");
into:
JButton[] digitButton = new JButton[10]; // digitButton is an arry of JButtons,
// Initialized to nulls.
for(final int i = 0; i < 10; i++) {
digitButton[i] = new JButton(Integer.toString(i)); // Convert 0 to "0", etc.
// Then make a button.
}
Now, give each button its own action listener instead of having the main class have one for all.

Just put a condition:
if ((text.contains("[a-zA-Z]+") == false){
//error
}
else{
//do your computation.
}
or
if ((text.contains("[0-9]*") == true){
//your code
}

Related

JLabel won't update it's new Text

So I am creating a calculator app. When one of the number buttons is clicked, it is supposed to appear on the JLabel. I have added actionListeners to all of my buttons, and when a number button is clicked, the JLabel's text is changed, via the method .setText(). For some reason when i run the program, the JLabel's text doesn't update. So i thought that the text value of the JLbale wasn't being changed, yet when I print the text value of the JLabel on the console, its shows that is has changed. I'm an now stuck. Help would be appreciated
package com.Patel.APSC;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.UIManager;
public class Calculator extends JFrame {
double num1 = 0;
double num2 = 0;
String strNum1;
String strNum2;
String op;
Double answer;
String label = "";
private JButton btnClear;
JLabel lblLabel = new JLabel("");
// constructors
public Calculator() {
// sets up the JFrame
this.setVisible(true);
this.setTitle("Calculator");
this.setResizable(false);
this.setSize(356, 512);
this.getContentPane().setLayout(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.getContentPane().setBackground(new Color(212, 229, 238));
// sets up all the buttons
JButton btn1 = new JButton("1");
JButton btn2 = new JButton("2");
JButton btn3 = new JButton("3");
JButton btn4 = new JButton("4");
JButton btn5 = new JButton("5");
JButton btn6 = new JButton("6");
JButton btn7 = new JButton("7");
JButton btn8 = new JButton("8");
JButton btn9 = new JButton("9");
JButton btn0 = new JButton("0");
JButton btnAdd = new JButton("+");
JButton btnSubtract = new JButton("-");
JButton btnMultiply = new JButton("*");
JButton btnDivide = new JButton("/");
JButton btnEqual = new JButton("=");
JButton btnClear = new JButton("AC");
btnClear.setBorder(null);
btn1.setFont(new Font("Times New Roman", Font.PLAIN, 32));
btn2.setFont(new Font("Times New Roman", Font.PLAIN, 32));
btn3.setFont(new Font("Times New Roman", Font.PLAIN, 32));
btn4.setFont(new Font("Times New Roman", Font.PLAIN, 32));
btn5.setFont(new Font("Times New Roman", Font.PLAIN, 32));
btn6.setFont(new Font("Times New Roman", Font.PLAIN, 32));
btn7.setFont(new Font("Times New Roman", Font.PLAIN, 32));
btn8.setFont(new Font("Times New Roman", Font.PLAIN, 32));
btn9.setFont(new Font("Times New Roman", Font.PLAIN, 32));
btn0.setFont(new Font("Times New Roman", Font.PLAIN, 32));
btnAdd.setFont(new Font("Mongolian Baiti", Font.PLAIN, 32));
btnSubtract.setFont(new Font("Mongolian Baiti", Font.PLAIN, 32));
btnMultiply.setFont(new Font("Mongolian Baiti", Font.PLAIN, 32));
btnDivide.setFont(new Font("Mongolian Baiti", Font.PLAIN, 32));
btnEqual.setFont(new Font("Mongolian Baiti", Font.PLAIN, 32));
btnClear.setFont(new Font("Times New Roman", Font.PLAIN, 32));
btn1.setLocation(28, 159);
btn2.setLocation(98, 159);
btn3.setLocation(168, 159);
btn4.setLocation(28, 229);
btn5.setLocation(98, 229);
btn6.setLocation(168, 229);
btn7.setLocation(28, 299);
btn8.setLocation(98, 299);
btn9.setLocation(168, 299);
btn0.setLocation(98, 369);
btnAdd.setLocation(265, 369);
btnSubtract.setLocation(265, 299);
btnMultiply.setLocation(265, 229);
btnDivide.setLocation(265, 159);
btnEqual.setLocation(265, 93);
btnClear.setBounds(163, 369, 55, 55);
btn1.setSize(55, 55);
btn2.setSize(55, 55);
btn3.setSize(55, 55);
btn4.setSize(55, 55);
btn5.setSize(55, 55);
btn6.setSize(55, 55);
btn7.setSize(55, 55);
btn8.setSize(55, 55);
btn9.setSize(55, 55);
btn0.setSize(55, 55);
btnAdd.setSize(55, 55);
btnSubtract.setSize(55, 55);
btnMultiply.setSize(55, 55);
btnDivide.setSize(55, 55);
btnEqual.setSize(55, 55);
btn0.setActionCommand("0");
btn1.setActionCommand("1");
btn2.setActionCommand("2");
btn3.setActionCommand("3");
btn4.setActionCommand("4");
btn5.setActionCommand("5");
btn6.setActionCommand("6");
btn7.setActionCommand("7");
btn8.setActionCommand("8");
btn9.setActionCommand("9");
btnAdd.setActionCommand("+");
btnSubtract.setActionCommand("-");
btnMultiply.setActionCommand("*");
ButtonListener listener = new ButtonListener();
btn1.addActionListener(listener);
btn2.addActionListener(listener);
btn3.addActionListener(listener);
btn4.addActionListener(listener);
btn5.addActionListener(listener);
btn6.addActionListener(listener);
btn7.addActionListener(listener);
btn8.addActionListener(listener);
btn9.addActionListener(listener);
btn0.addActionListener(listener);
btnAdd.addActionListener(listener);
btnSubtract.addActionListener(listener);
btnMultiply.addActionListener(listener);
btnDivide.addActionListener(listener);
btnClear.addActionListener(listener);
btnEqual.addActionListener(listener);
this.getContentPane().add(btn0);
this.getContentPane().add(btn1);
this.getContentPane().add(btn2);
this.getContentPane().add(btn3);
this.getContentPane().add(btn4);
this.getContentPane().add(btn5);
this.getContentPane().add(btn6);
this.getContentPane().add(btn7);
this.getContentPane().add(btn8);
this.getContentPane().add(btn9);
this.getContentPane().add(btnAdd);
this.getContentPane().add(btnSubtract);
this.getContentPane().add(btnMultiply);
this.getContentPane().add(btnDivide);
this.getContentPane().add(btnEqual);
this.getContentPane().add(btnClear);
JLabel lblLabel = new JLabel("");
lblLabel.setFont(new Font("Times New Roman", Font.PLAIN, 27));
this.getContentPane().add(lblLabel);
lblLabel.setLocation(43, 31);
lblLabel.setSize(277, 51);
lblLabel.setOpaque(true);
}
public static void main(String[] args) {
Calculator gui = new Calculator();
}
public class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("1")
|| e.getActionCommand().equals("2")
|| e.getActionCommand().equals("3")
|| e.getActionCommand().equals("4")
|| e.getActionCommand().equals("5")
|| e.getActionCommand().equals("6")
|| e.getActionCommand().equals("7")
|| e.getActionCommand().equals("8")
|| e.getActionCommand().equals("9")
|| e.getActionCommand().equals("0")) {
// if a number is typed
lblLabel.setText(e.getActionCommand());
System.out.println(lblLabel.getText());
}
}
}
}
You're calling text.setText(e.getActionCommand()) -- but what is this textfield? It's not your JLabel which is called, lblLabel, and in fact, I can't find a text field within your program, and so I'm surprised that the class even compiles.
I believe that you'll be much better off calling setText on the correct JLabel field: lblLabel.setText(e.getActionCommand())
Side recommendations:
Needless repetition often leads to hard to find bugs, and so you'll want to use arrays or collections and for loops to consolidate your code.
Your gut instinct may be to use a null layout and calling setBounds(...) on your components to place them with absolute positioning, but I'm going suggest that you not do this as this makes for very inflexible GUI's that while they might look good on one platform look terrible on most other platforms or screen resolutions and that are very difficult to update and maintain. Instead you will want to study and learn the layout managers and then nest JPanels, each using its own layout manager to create pleasing and complex GUI's that look good on all OS's.
Your last large if block can be compressed to if ("1234567890".contains(e.getActionCommand()) {
Edit
Your question's edit changes everything. Please avoid these types of changes as they can be very frustrating to us volunteers.
Now I see that you're shadowing the lblLbl variable by declaring it twice, once in the class and once in the constructor, meaning that the class's field is not the JLabel that is being displayed. Solution: declare the variable only once.
so change
public class Calculator {
JLabel lblLabel = new JLabel("");
public Calculator() {
JLabel lblLabel = new JLabel("");
// ...
}
}
to:
public class Calculator {
JLabel lblLabel = new JLabel("");
public Calculator() {
// JLabel lblLabel = new JLabel(""); // don't re-declare
// ...
}
}

JList getSelectedValue()

Hello there. I have done a thorough search on google how to get the selectedValue in the JList and use the value to calculate the price of the menu, as shown below in the figure. However, I can't figure out a way to implement the button Calculate feature. Please see the image below for the description of the problem.
import javax.swing.*;
import java.awt.Font;
import java.awt.event.*;
public class JResto extends JFrame implements ActionListener {
private JTextField t1;
private JButton b1;
private JList list;
private String[] values = {"Fried Rice (Rs 150)", "Fried Noodle (Rs 125)", "Chop Soy (Rs 75)", "Wang Tang (Rs 35)"};
public JResto(){
super("Sumen Restaurant");
setBounds(100, 100, 450, 440);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
JLabel lblSumenRestaurant = new JLabel("Sumen Restaurant");
lblSumenRestaurant.setFont(new Font("Tahoma", Font.BOLD, 12));
lblSumenRestaurant.setBounds(156, 11, 127, 29);
add(lblSumenRestaurant);
list = new JList(values);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setBounds(115, 52, 200, 129);
add(list);
JLabel lblQuantity = new JLabel("Quantity");
lblQuantity.setBounds(115, 225, 46, 14);
add(lblQuantity);
t1 = new JTextField();
t1.setBounds(171, 222, 86, 20);
add(t1);
t1.setColumns(10);
JButton b1 = new JButton("Calculate");
b1.setBounds(171, 304, 89, 23);
add(b1);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
}
}
The code now works !
managed to do it with list.isSelectedIndex()
you can use jlist item with the methode add
list = new JList(values); // not used eny more and will dispare soon

How do I write on a JTextField using the JButtons on the JFrame?

I'm currently working in a simple calculator project and I found myself in a small problem.
I'm not able to write on the text field using the buttons. I want to be able to write on the text using the buttons on the frame.
Can someone please help me?
Here's my code:
import javax.swing.*;
import java.awt.*;
public class Calculator extends JFrame{
JPanel NumberPanel = new JPanel();
String [] ButtonString = {"7","8","9","4","5","6","1","2","3","0",".","+/-"};
JButton ButtonArray [] = new JButton[ButtonString.length];
JPanel OperationPanel = new JPanel();
String [] OperationString = {"Erase","Ac","*","/","+","-","Ans","="};
JButton [] OperationArray = new JButton [OperationString.length];
Calculator(){
for (int a = 0 ; a < ButtonArray.length ; a++){
ButtonArray[a]= new JButton (ButtonString[a]);
}
NumberPanel.setLayout(new GridLayout(4,3,5,5));
for (int a = 0 ; a < ButtonArray.length ; a++){
NumberPanel.add(ButtonArray[a]);
}
for (int a = 0 ; a < OperationArray.length ; a++){
OperationArray[a]= new JButton(OperationString[a]);
}
OperationPanel.setLayout(new GridLayout(4,2,5,5));
for (int a = 0 ; a < OperationArray.length ; a++){
OperationPanel.add(OperationArray[a]);
}
JPanel Finalpanel = new JPanel();
Finalpanel.setLayout(new FlowLayout());
Finalpanel.add(NumberPanel);Finalpanel.add(OperationPanel);
JTextField WritingZone = new JTextField(27);
WritingZone.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
WritingZone.setBorder(BorderFactory.createLoweredSoftBevelBorder());
WritingZone.setEditable(false);
JPanel TextPanel = new JPanel();
TextPanel.add(WritingZone);
JPanel AllPanel = new JPanel();
AllPanel.setLayout(new BorderLayout(5,5));
AllPanel.add(BorderLayout.NORTH, TextPanel);
AllPanel.add(BorderLayout.CENTER, Finalpanel);
AllPanel.setBorder(BorderFactory.createTitledBorder("Simple Calculator"));
add(AllPanel);
}
public static void main (String [] arg){
JFrame frame = new Calculator();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setSize(400,250);
frame.setResizable(false);
}
}
First of all, follow Java naming conventions. Variable name should NOT start with an upper case character. I have never seen a tutorial, text book or example posted in the forum that does this, so don't make up your own conventions. Learn by example.
If you want the buttons to do something then you need to add an ActionListener to the button. Or even better is to create an Action that can be shared by the button and by the keyboard so you can use Key Bindings.
Simple example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class CalculatorPanel extends JPanel
{
private JTextField display;
public CalculatorPanel()
{
Action numberAction = new AbstractAction()
{
#Override
public void actionPerformed(ActionEvent e)
{
display.setCaretPosition( display.getDocument().getLength() );
display.replaceSelection(e.getActionCommand());
}
};
setLayout( new BorderLayout() );
display = new JTextField();
display.setEditable( false );
display.setHorizontalAlignment(JTextField.RIGHT);
add(display, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout( new GridLayout(0, 5) );
add(buttonPanel, BorderLayout.CENTER);
for (int i = 0; i < 10; i++)
{
String text = String.valueOf(i);
JButton button = new JButton( text );
button.addActionListener( numberAction );
button.setBorder( new LineBorder(Color.BLACK) );
button.setPreferredSize( new Dimension(50, 50) );
buttonPanel.add( button );
InputMap inputMap = button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
inputMap.put(KeyStroke.getKeyStroke(text), text);
inputMap.put(KeyStroke.getKeyStroke("NUMPAD" + text), text);
button.getActionMap().put(text, numberAction);
}
}
private static void createAndShowUI()
{
// UIManager.put("Button.margin", new Insets(10, 10, 10, 10) );
JFrame frame = new JFrame("Calculator Panel");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.add( new CalculatorPanel() );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
Implement ActionPerformed methode.
#Override
public void ActionPerformed(ActionEvent e){
JButton btn = (JButton)e.getSource();
if(btn == btnName){
String state = WritingZone.getText();
WritingZone.setText(state+btnNum(operation));
} else if(btn==otherButton)...
}
-And then add listener to every button.
btn.addListener(this);
-this is one way to do it.
You need an actionlistener..
I edited your code so that button 1 will work.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Calculator extends JFrame{
JPanel NumberPanel = new JPanel();
ButtonHandler handler = new ButtonHandler();
JButton button;
JTextArea textArea;
Calculator(){
JPanel AllPanel = new JPanel();
AllPanel.setBorder(BorderFactory.createTitledBorder("Simple Calculator"));
getContentPane().add(AllPanel);
AllPanel.setLayout(null);
button = new JButton("1");
button.setBounds(10, 129, 89, 23);
button.addActionListener(handler);
AllPanel.add(button);
JButton button_1 = new JButton("2");
button_1.setBounds(109, 129, 89, 23);
AllPanel.add(button_1);
JButton button_2 = new JButton("3");
button_2.setBounds(208, 129, 89, 23);
AllPanel.add(button_2);
JButton button_3 = new JButton("4");
button_3.setBounds(10, 95, 89, 23);
AllPanel.add(button_3);
JButton button_4 = new JButton("5");
button_4.setBounds(109, 95, 89, 23);
AllPanel.add(button_4);
JButton button_5 = new JButton("6");
button_5.setBounds(208, 95, 89, 23);
AllPanel.add(button_5);
JButton button_6 = new JButton("7");
button_6.setBounds(10, 61, 89, 23);
AllPanel.add(button_6);
JButton button_7 = new JButton("8");
button_7.setBounds(109, 61, 89, 23);
AllPanel.add(button_7);
JButton button_8 = new JButton("9");
button_8.setBounds(208, 61, 89, 23);
AllPanel.add(button_8);
JButton button_9 = new JButton("0");
button_9.setBounds(109, 163, 89, 23);
AllPanel.add(button_9);
JButton btnClear = new JButton("Clear");
btnClear.setBounds(298, 163, 89, 23);
AllPanel.add(btnClear);
JButton btnAdd = new JButton("Add");
btnAdd.setBounds(298, 129, 89, 23);
AllPanel.add(btnAdd);
JButton btnSub = new JButton("Sub");
btnSub.setBounds(298, 95, 89, 23);
AllPanel.add(btnSub);
textArea = new JTextArea();
textArea.setBounds(43, 29, 253, 22);
AllPanel.add(textArea);
}
private class ButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
if (e.getSource() == button)
{
textArea.insert("1",0);
}
}
}
public static void main (String [] arg){
JFrame frame = new Calculator();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setSize(400,250);
frame.setResizable(false);
}
}

Why isn't my JScrollPane working?

I'm trying to make my JPanel scrollable but it's not working. I made a JPanel, added components to it, then added my JPanel to a JScrollPane. This is what you're supposed to do, right? What am I doing wrong?
import java.awt.Dimension;
import java.awt.Font;
import java.awt.SystemColor;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ScrollPaneLayout;
import javax.swing.SwingConstants;
public class RegisterPane extends JPanel {
private JTextField txtJohnDoe;
private JTextField txtExampledomaincom;
private JPasswordField passwordField;
private JPasswordField passwordField_1;
/**
* Create the panel.
*/
public RegisterPane() {
setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(6, 36, 300, 450);
panel.setLayout(null);
JLabel lblFirstName = new JLabel("First Name");
lblFirstName.setBounds(28, 6, 92, 16);
panel.add(lblFirstName);
txtJohnDoe = new JTextField();
txtJohnDoe.setText("John Doe");
txtJohnDoe.setBounds(124, 0, 251, 28);
panel.add(txtJohnDoe);
txtJohnDoe.setColumns(10);
txtExampledomaincom = new JTextField();
txtExampledomaincom.setText("Example#domain.com");
txtExampledomaincom.setColumns(10);
txtExampledomaincom.setBounds(124, 40, 251, 28);
panel.add(txtExampledomaincom);
JLabel lblEmail = new JLabel("Email");
lblEmail.setBounds(28, 46, 92, 16);
panel.add(lblEmail);
JLabel lblGender = new JLabel("Gender");
lblGender.setBounds(28, 89, 55, 16);
panel.add(lblGender);
JRadioButton rdbtnMale = new JRadioButton("Male");
rdbtnMale.setBounds(124, 85, 92, 23);
panel.add(rdbtnMale);
JRadioButton rdbtnFemale = new JRadioButton("Female");
rdbtnFemale.setBounds(283, 85, 92, 23);
panel.add(rdbtnFemale);
JLabel lblPassword = new JLabel("Password");
lblPassword.setBounds(28, 157, 55, 16);
panel.add(lblPassword);
JLabel passDirections = new JLabel();
passDirections.setHorizontalAlignment(SwingConstants.CENTER);
passDirections.setFont(new Font("Lucida Grande", Font.PLAIN, 10));
passDirections.setBackground(SystemColor.window);
passDirections.setText("Password's Must be at Least 6 characters long and contain 1 non letter character");
passDirections.setBounds(29, 117, 346, 28);
panel.add(passDirections);
passwordField = new JPasswordField();
passwordField.setBounds(124, 151, 251, 28);
panel.add(passwordField);
passwordField_1 = new JPasswordField();
passwordField_1.setBounds(124, 195, 251, 28);
panel.add(passwordField_1);
JLabel lblRetypePassword = new JLabel("Password Again");
lblRetypePassword.setBounds(28, 201, 92, 16);
panel.add(lblRetypePassword);
JCheckBox chckbxSubscribeToNews = new JCheckBox("Subscribe to News Letter");
chckbxSubscribeToNews.setSelected(true);
chckbxSubscribeToNews.setHorizontalAlignment(SwingConstants.CENTER);
chckbxSubscribeToNews.setBounds(29, 244, 346, 23);
panel.add(chckbxSubscribeToNews);
JLabel lblNewLabel = new JLabel("New label");
lblNewLabel.setBounds(28, 280, 55, 16);
panel.add(lblNewLabel);
JScrollPane scroll = new JScrollPane(panel);
scroll.setSize(new Dimension(450,300));
panel.setAutoscrolls(true);
add(scroll);
}
}
Here's my JFrame class
import java.awt.BorderLayout;
public class MainFrame extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainFrame frame = new MainFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MainFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(0, 0));
setResizable(false);
setContentPane(new RegisterPane());
//RegisterPane isn't scrolling ^
}
}
Thanks in Advance for your help!
I'm seeing setLayout(null) alot in your code.
The JViewport uses the component's/view's preferred size as a bases for determining if the view expands beyond the visible bounds of the JScrollPane, because you've seen fit to ignore this feature, the components have begun to break down.
Swing is designed to work layout managers and it makes it much easier to develop complex user interfaces that can work across a multitude of platforms and environments

Add to JLabel method?

Is there a method that will add a string to JLabel without editing what was already there? I know about the setText method but in my program, a calculator, I want to add the button clicked to the JLabel with out overriding what is already there. Im I doing this right? Here's my code (if you need it):
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.border.EmptyBorder;
public class calc extends JFrame implements ActionListener {
private JPanel contentPane;
public JLabel results;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
calc frame = new calc();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public calc() {
setTitle("Calculator");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 255, 179);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
JPanel panel = new JPanel();
panel.setToolTipText("Numbers will appear here once clicked!");
panel.setBackground(Color.WHITE);
contentPane.add(panel, BorderLayout.NORTH);
results = new JLabel("");
panel.add(results);
JPanel panel_1 = new JPanel();
contentPane.add(panel_1, BorderLayout.CENTER);
panel_1.setLayout(null);
JButton one = new JButton("1");
one.addActionListener(this);
one.setBounds(6, 19, 61, 29);
panel_1.add(one);
JButton two = new JButton("2");
two.addActionListener(this);
two.setBounds(67, 19, 61, 29);
panel_1.add(two);
JButton three = new JButton("3");
three.addActionListener(this);
three.setBounds(127, 19, 61, 29);
panel_1.add(three);
JButton four = new JButton("4");
four.addActionListener(this);
four.setBounds(6, 48, 61, 29);
panel_1.add(four);
JButton five = new JButton("5");
five.addActionListener(this);
five.setBounds(67, 48, 61, 29);
panel_1.add(five);
JButton six = new JButton("6");
six.addActionListener(this);
six.setBounds(127, 48, 61, 29);
panel_1.add(six);
JButton seven = new JButton("7");
seven.addActionListener(this);
seven.setBounds(6, 75, 61, 29);
panel_1.add(seven);
JButton eight = new JButton("8");
eight.addActionListener(this);
eight.setBounds(67, 75, 61, 29);
panel_1.add(eight);
JButton nine = new JButton("9");
nine.addActionListener(this);
nine.setBounds(127, 75, 61, 29);
panel_1.add(nine);
JButton zero = new JButton("0");
zero.addActionListener(this);
zero.setBounds(6, 102, 122, 29);
panel_1.add(zero);
JButton decimal = new JButton(".");
decimal.addActionListener(this);
decimal.setBounds(127, 102, 61, 29);
panel_1.add(decimal);
JButton add = new JButton("+");
add.addActionListener(this);
add.setBounds(184, 19, 61, 29);
panel_1.add(add);
JButton sub = new JButton("-");
sub.addActionListener(this);
sub.setBounds(184, 48, 61, 29);
panel_1.add(sub);
JButton times = new JButton("x");
times.addActionListener(this);
times.setBounds(184, 75, 61, 29);
panel_1.add(times);
JButton div = new JButton("\u00F7");
div.addActionListener(this);
div.setBounds(184, 102, 61, 29);
panel_1.add(div);
JSeparator separator = new JSeparator();
separator.setBounds(6, 6, 239, 12);
panel_1.add(separator);
}
public void actionPerformed(ActionEvent al) {
String name = al.getActionCommand();
}
}
Just get the orginal text, add "blah" (or anything else), and set it back.
results.setText(results.getText() + "blah");
Don't use a JLabel which is really designed to just display text. Instead you can use a non-editable JTextField which is designed to be updated. Then you can just use:
String name = al.getActionCommand();
textField.replaceSelection(name);
and the character will be appended to the end of the text field.
Also, don't use a null layout and the setBounds() method. Swing was designed to be used with layout managers.

Categories

Resources