Making calculator using Swing - java

I have developed the calc using swing but i have a problem in equal to button.
I have written the code for addition,subtraction,multiplication and division in the equal to button but the problem is that when i subtract two numbers I get the o/p but when I add or multiply or divide I don't get the o/p. So help me in
the code of equal to button:
package com.dss;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JEditorPane;
import javax.swing.SwingConstants;
import javax.swing.border.SoftBevelBorder;
import javax.swing.border.BevelBorder;
public class JCalcEx extends JFrame {
private JPanel contentPane;
private JTextField value1;
private JTextField value2;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JCalcEx frame = new JCalcEx();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public JCalcEx() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 395, 680);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
value1 = new JTextField();
value1.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null,
null, null));
value1.setHorizontalAlignment(SwingConstants.RIGHT);
value1.setFont(new Font("Tahoma", Font.PLAIN, 20));
value1.setBounds(12, 69, 350, 41);
contentPane.add(value1);
value1.setColumns(10);
JTextField value3 = new JTextField();
value3.setHorizontalAlignment(SwingConstants.RIGHT);
value3.setFont(new Font("Tahoma", Font.PLAIN, 20));
value3.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null,
null, null));
value3.setBounds(12, 111, 353, 41);
contentPane.add(value3);
value3.setColumns(10);
JButton button9 = new JButton("9");
button9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
value1.setText(value1.getText()+9);
}
});
button9.setFont(new Font("Tahoma", Font.PLAIN, 20));
button9.setBounds(12, 192, 69, 70);
contentPane.add(button9);
JButton button8 = new JButton("8");
button8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0){
value1.setText(value1.getText()+8);
}
});
button8.setFont(new Font("Tahoma", Font.PLAIN, 20));
button8.setBounds(105, 192, 69, 70);
contentPane.add(button8);
JButton button7 = new JButton("7");
button7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
value1.setText(value1.getText()+7);
}
});
button7.setFont(new Font("Tahoma", Font.PLAIN, 20));
button7.setBounds(199, 192, 69, 70);
contentPane.add(button7);
JButton button6 = new JButton("6");
button6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
value1.setText(value1.getText()+6);
}
});
button6.setFont(new Font("Tahoma", Font.PLAIN, 20));
button6.setBounds(293, 192, 69, 70);
contentPane.add(button6);
JButton button5 = new JButton("5");
button5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
value1.setText(value1.getText()+5);
}
});
button5.setFont(new Font("Tahoma", Font.PLAIN, 20));
button5.setBounds(12, 293, 69, 70);
contentPane.add(button5);
JButton button4 = new JButton("4");
button4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
value1.setText(value1.getText()+4);
}
});
button4.setFont(new Font("Tahoma", Font.PLAIN, 20));
button4.setBounds(105, 293, 69, 70);
contentPane.add(button4);
JButton button3 = new JButton("3");
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
value1.setText(value1.getText()+3);
}
});
button3.setFont(new Font("Tahoma", Font.PLAIN, 20));
button3.setBounds(199, 293, 69, 70);
contentPane.add(button3);
JButton button2 = new JButton("2");
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
value1.setText(value1.getText()+2);
}
});
button2.setFont(new Font("Tahoma", Font.PLAIN, 20));
button2.setBounds(293, 293, 69, 70);
contentPane.add(button2);
JButton button1 = new JButton("1");
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
value1.setText(value1.getText()+1);
}
});
button1.setFont(new Font("Tahoma", Font.PLAIN, 20));
button1.setBounds(12, 392, 69, 70);
contentPane.add(button1);
JButton buttonc = new JButton("C");
buttonc.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
value2.setText("");
value1.setText("");
actionRecieved.setText("");
value3.setText("");
}
});
buttonc.setFont(new Font("Tahoma", Font.PLAIN, 20));
buttonc.setBounds(293, 392, 69, 70);
contentPane.add(buttonc);
JButton button0 = new JButton("0");
button0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
value1.setText(value1.getText()+0);
}
});
button0.setFont(new Font("Tahoma", Font.PLAIN, 20));
button0.setBounds(105, 392, 69, 70);
contentPane.add(button0);
JButton buttoneql = new JButton("=");
buttoneql.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int one = Integer.parseInt(value2.getText());
int two = Integer.parseInt(value1.getText());
if(actionRecieved.getText().equals("sub"))
{
int sub = one - two;
value3.setText(String.valueOf(sub));
}
if(actionRecieved.getText().equals("add"))
{
int add = one + two;
value3.setText(String.valueOf(add));
}
if(actionRecieved.getText().equals("mul"))
{
int mul = one * two;
value1.setText(String.valueOf(mul));
}
if(actionRecieved.getText().equals("div"))
{
int div = one / two;
value1.setText(String.valueOf(div));
}
}
});
buttoneql.setFont(new Font("Tahoma", Font.PLAIN, 20));
buttoneql.setBounds(199, 392, 69, 70);
contentPane.add(buttoneql);
JButton buttonplus = new JButton("+");
buttonplus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
value2.setText(value1.getText());
actionRecieved.setText("plus");
value1.setText(null);
}
});
buttonplus.setFont(new Font("Tahoma", Font.PLAIN, 20));
buttonplus.setBounds(12, 489, 69, 70);
contentPane.add(buttonplus);
JButton buttonminus = new JButton("-");
buttonminus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
value2.setText(value1.getText());
actionRecieved.setText("sub");
value1.setText(null);
}
});
buttonminus.setFont(new Font("Tahoma", Font.PLAIN, 20));
buttonminus.setBounds(105, 489, 69, 70);
contentPane.add(buttonminus);
JButton buttonmultiply = new JButton("x");
buttonmultiply.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
value2.setText(value1.getText());
actionRecieved.setText("mul");
value1.setText(null);
}
});
buttonmultiply.setFont(new Font("Tahoma", Font.PLAIN, 20));
buttonmultiply.setBounds(199, 489, 69, 70);
contentPane.add(buttonmultiply);
JButton buttondivide = new JButton("/");
buttondivide.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
value2.setText(value1.getText());
actionRecieved.setText("div");
value1.setText(null);
}
});
buttondivide.setFont(new Font("Tahoma", Font.PLAIN, 20));
buttondivide.setBounds(293, 489, 69, 70);
contentPane.add(buttondivide);
value2 = new JTextField();
value2.setFont(new Font("Tahoma", Font.PLAIN, 20));
value2.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null,
null, null));
value2.setHorizontalAlignment(SwingConstants.RIGHT);
value2.setBounds(229, 29, 133, 41);
contentPane.add(value2);
value2.setColumns(10);
JEditorPane editorPane = new JEditorPane();
editorPane.setEditable(false);
editorPane.setBounds(12, 29, 350, 81);
contentPane.add(editorPane);
actionRecieved = new JLabel("");
actionRecieved.setBounds(12, 572, 118, 48);
contentPane.add(actionRecieved);
}
private JLabel actionRecieved;
}

You have the following problems
For div int div = one - two; - should be /
For 1. you will have problem with Integer division
Add will never be entered into because you do actionRecieved.setText("plus"); but expect add
Not sure why in some cases you are setting value1 and in others value3
???

Related

Java - Call Method from sub class By pressing a JButton in the base class

Can I call a method from an extended class by pressing a JButton?
I know how to display messages etc when pressing a JButton, but I want to know if it is possible to do this?
I want to call methods from Activate_and_Deactivate class to use as action performed by pressing radiobuttons ON and OF. I can directly place the statements in the actionevent argument but the teacher said I have to use inheritance atleast for something.
this is my code.
package Calculators;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Font;
import java.awt.Button;
import java.awt.Color;
import javax.swing.JLabel;
import com.jgoodies.forms.factories.DefaultComponentFactory;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.border.EtchedBorder;
import javax.swing.border.CompoundBorder;
import javax.swing.JRadioButton;
public class UIFrame {
Activate_and_Deactivate act = new Activate_and_Deactivate();
JButton button0 = new JButton("0");
JButton button2 = new JButton("2");
JButton button1 = new JButton("1");
JButton button3 = new JButton("3");
JButton button4 = new JButton("4");
JButton button5 = new JButton("5");
JButton button6 = new JButton("6");
JButton button7 = new JButton("7");
JButton button8 = new JButton("8");
JButton button9 = new JButton("9");
JButton button_Div = new JButton("/");
JButton button_C = new JButton("C");
JButton button_Mul = new JButton("*");
JButton button_Add = new JButton("+");
JButton button_Sub = new JButton("-");
JButton button_Dot = new JButton(".");
JButton button_rec = new JButton("1/x");
JButton button_Sqr = new JButton("\u221A");
JButton button_neg = new JButton("±");
JButton button_per = new JButton("%");
JButton button_equal = new JButton("=");
JButton button_undo = new JButton("\u2190");
JButton btnExit = new JButton("exit");
JRadioButton rdbtnOn = new JRadioButton("On");
JRadioButton rdbtnOff = new JRadioButton("Off");
private JFrame frmCalculator;
private JTextField screen;
private JTextField value1;
private JTextField value2;
private JLabel operation;
double fNumber = 0;
double sNumber = 0;
double result = 0;
String ope;
String answer;
public static void main(String[] args) {
try
{
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); //Motif, and Windows packages that it requires are shipped with the Java SDK this way
}
catch(Exception e){}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UIFrame window = new UIFrame();
window.frmCalculator.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public UIFrame() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmCalculator = new JFrame();
frmCalculator.setTitle("Java calculator ver 3.1.6 by Muhammad Haroon");
frmCalculator.getContentPane().setBackground(new Color(0, 0, 0));
frmCalculator.getContentPane().setForeground(Color.DARK_GRAY);
frmCalculator.setBounds(100, 100, 326, 422);
frmCalculator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmCalculator.getContentPane().setLayout(null);
value1 = new JTextField();
value1.setForeground(Color.DARK_GRAY);
value1.setFont(new Font("Tahoma", Font.PLAIN, 19));
value1.setHorizontalAlignment(SwingConstants.RIGHT);
value1.setBorder(null);
value1.setBounds(151, 52, 141, 31);
frmCalculator.getContentPane().add(value1);
value1.setColumns(10);
value2 = new JTextField();
value2.setFont(new Font("Tahoma", Font.PLAIN, 24));
value2.setHorizontalAlignment(SwingConstants.RIGHT);
value2.setBorder(null);
value2.setBounds(71, 90, 218, 37);
frmCalculator.getContentPane().add(value2);
value2.setColumns(10);
operation = new JLabel("");
operation.setForeground(new Color(144, 238, 144));
operation.setHorizontalAlignment(SwingConstants.LEFT);
operation.setFont(new Font("Tahoma", Font.PLAIN, 20));
operation.setBounds(20, 97, 50, 31);
frmCalculator.getContentPane().add(operation);
screen = new JTextField();
screen.setBorder(new CompoundBorder(new EtchedBorder(EtchedBorder.RAISED, null, null), new EtchedBorder(EtchedBorder.LOWERED, null, null)));
screen.setEditable(false);
screen.setHorizontalAlignment(SwingConstants.RIGHT);
screen.setBounds(10, 48, 289, 82);
frmCalculator.getContentPane().add(screen);
screen.setColumns(10);
rdbtnOn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
act.activate();
}
});
rdbtnOn.setFont(new Font("Cambria Math", Font.PLAIN, 12));
rdbtnOn.setForeground(new Color(255, 255, 255));
rdbtnOn.setBounds(11, 18, 38, 23);
frmCalculator.getContentPane().add(rdbtnOn);
rdbtnOff.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
act.deactivate();
}
});
rdbtnOff.setFont(new Font("Cambria Math", Font.PLAIN, 12));
rdbtnOff.setForeground(new Color(255, 255, 255));
rdbtnOff.setBounds(51, 18, 38, 23);
frmCalculator.getContentPane().add(rdbtnOff);
button0.setBackground(new Color(135, 206, 250));
button0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String num = value2.getText() + button0.getText(); //value.setText(value.getText()+Button)
value2.setText(num);
}
});
button0.setFont(new Font("Cambria Math", Font.PLAIN, 18));
button0.setBounds(11, 306, 110, 31);
frmCalculator.getContentPane().add(button0);
button2.setBackground(new Color(135, 206, 250));
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String num = value2.getText() + button2.getText(); //value.setText(value.getText()+Button)
value2.setText(num);
}
});
button1.setBackground(new Color(135, 206, 250));
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String num = value2.getText() + button1.getText(); //value.setText(value.getText()+Button)
value2.setText(num);
}
});
button1.setFont(new Font("Cambria Math", Font.PLAIN, 18));
button1.setBounds(11, 264, 50, 31);
frmCalculator.getContentPane().add(button1);
button2.setFont(new Font("Cambria Math", Font.PLAIN, 18));
button2.setBounds(71, 264, 50, 31);
frmCalculator.getContentPane().add(button2);
button3.setBackground(new Color(135, 206, 250));
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String num = value2.getText() + button3.getText(); //value.setText(value.getText()+Button)
value2.setText(num);
}
});
button3.setFont(new Font("Cambria Math", Font.PLAIN, 18));
button3.setBounds(131, 264, 50, 31);
frmCalculator.getContentPane().add(button3);
button4.setBackground(new Color(135, 206, 250));
button4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String num = value2.getText() + button4.getText(); //value.setText(value.getText()+Button)
value2.setText(num);
}
});
button4.setFont(new Font("Cambria Math", Font.PLAIN, 18));
button4.setBounds(11, 222, 50, 31);
frmCalculator.getContentPane().add(button4);
button5.setBackground(new Color(135, 206, 250));
button5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String num = value2.getText() + button5.getText(); //value.setText(value.getText()+Button)
value2.setText(num);
}
});
button5.setFont(new Font("Cambria Math", Font.PLAIN, 18));
button5.setBounds(71, 222, 50, 31);
frmCalculator.getContentPane().add(button5);
button6.setBackground(new Color(135, 206, 250));
button6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String num = value2.getText() + button6.getText(); //value.setText(value.getText()+Button)
value2.setText(num);
}
});
button6.setFont(new Font("Cambria Math", Font.PLAIN, 18));
button6.setBounds(131, 222, 50, 31);
frmCalculator.getContentPane().add(button6);
button7.setBackground(new Color(135, 206, 250));
button7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String num = value2.getText() + button7.getText(); //value.setText(value.getText()+Button)
value2.setText(num);
}
});
button7.setFont(new Font("Cambria Math", Font.PLAIN, 18));
button7.setBounds(11, 180, 50, 31);
frmCalculator.getContentPane().add(button7);
button8.setBackground(new Color(135, 206, 250));
button8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String num = value2.getText() + button8.getText(); //value.setText(value.getText()+Button)
value2.setText(num);
}
});
button8.setFont(new Font("Cambria Math", Font.PLAIN, 18));
button8.setBounds(71, 180, 50, 31);
frmCalculator.getContentPane().add(button8);
button9.setBackground(new Color(135, 206, 250));
button9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String num = value2.getText() + button9.getText(); //value.setText(value.getText()+Button)
value2.setText(num);
}
});
button9.setFont(new Font("Cambria Math", Font.PLAIN, 18));
button9.setBounds(131, 180, 50, 31);
frmCalculator.getContentPane().add(button9);
button_Div.setBackground(new Color(192, 192, 192));
button_Div.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
value1.setText(value2.getText());
operation.setText("/");
value2.setText(null);
}
});
button_C.setBackground(new Color(60, 179, 113));
button_C.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
value2.setText(null);
value1.setText(null);
operation.setText(null);
}
});
button_C.setFont(new Font("Cambria Math", Font.PLAIN, 18));
button_C.setBounds(71, 138, 50, 31);
frmCalculator.getContentPane().add(button_C);
button_Div.setFont(new Font("Cambria Math", Font.PLAIN, 18));
button_Div.setBounds(191, 180, 50, 31);
frmCalculator.getContentPane().add(button_Div);
button_Mul.setBackground(new Color(192, 192, 192));
button_Mul.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
value1.setText(value2.getText());
operation.setText("*");
value2.setText(null);
}
});
button_Mul.setFont(new Font("Cambria Math", Font.PLAIN, 18));
button_Mul.setBounds(191, 222, 50, 31);
frmCalculator.getContentPane().add(button_Mul);
button_Add.setBackground(new Color(192, 192, 192));
button_Add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
value1.setText(value2.getText());
operation.setText("+");
ope = "+";
value2.setText(null);
}
});
button_Add.setFont(new Font("Cambria Math", Font.PLAIN, 18));
button_Add.setBounds(191, 306, 50, 31);
frmCalculator.getContentPane().add(button_Add);
button_Sub.setBackground(new Color(192, 192, 192));
button_Sub.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
value1.setText(value2.getText());
operation.setText("-");
value2.setText(null);
}
});
button_Sub.setFont(new Font("Cambria Math", Font.PLAIN, 18));
button_Sub.setBounds(191, 264, 50, 31);
frmCalculator.getContentPane().add(button_Sub);
button_Dot.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String num = value2.getText() + button_Dot.getText(); //value.setText(value.getText()+Button)
value2.setText(num);
}
});
button_Dot.setFont(new Font("Cambria Math", Font.PLAIN, 18));
button_Dot.setBounds(131, 306, 50, 31);
frmCalculator.getContentPane().add(button_Dot);
button_rec.setBackground(new Color(192, 192, 192));
button_rec.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double ops1 = Double.parseDouble(String.valueOf(value2.getText()));
double ops2 = Double.parseDouble(String.valueOf(value2.getText()));
ops1 = 1/ops2;
value2.setText(String.valueOf(ops1));
value1.setText("reciproc("+String.valueOf(ops2)+")");
}
});
//ALT+251
button_Sqr.setBackground(new Color(192, 192, 192));
button_Sqr.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
double ops = Double.parseDouble(String.valueOf(value2.getText()));
ops = Math.sqrt(ops);
value2.setText(String.valueOf(ops));
value1.setText("sqrt("+String.valueOf(ops*ops)+")");
}
});
button_Sqr.setFont(new Font("Cambria Math", Font.PLAIN, 13));
button_Sqr.setBounds(131, 138, 50, 31);
frmCalculator.getContentPane().add(button_Sqr);
button_rec.setFont(new Font("Cambria Math", Font.PLAIN, 11));
button_rec.setBounds(249, 222, 50, 31);
frmCalculator.getContentPane().add(button_rec);
//ALT+0177
button_neg.setBackground(new Color(192, 192, 192));
button_neg.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double ops = Double.parseDouble(String.valueOf(value2.getText()));
ops = ops * (-1);
value2.setText(String.valueOf(ops));
value1.setText("negate("+String.valueOf(ops*-1)+")");
}
});
button_neg.setFont(new Font("Cambria Math", Font.PLAIN, 18));
button_neg.setBounds(191, 138, 50, 31);
frmCalculator.getContentPane().add(button_neg);
button_per.setBackground(new Color(192, 192, 192));
button_per.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
double ops = Double.parseDouble(String.valueOf(value2.getText()));
ops = ops * (100);
value2.setText(String.valueOf(ops));
value1.setText(String.valueOf(ops));
}
});
button_per.setBounds(249, 180, 50, 31);
frmCalculator.getContentPane().add(button_per);
button_equal.setBackground(new Color(60, 179, 113));
button_equal.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fNumber = Double.parseDouble(value1.getText());
sNumber = Double.parseDouble(value2.getText());
if(operation.getText().equals("+"))
{
result = fNumber + sNumber ;
value1.setText(null);
value2.setText(String.valueOf(result));
}
else if(operation.getText().equals("-"))
{
result = fNumber - sNumber ;
value1.setText(null);
value2.setText(String.valueOf(result));
}
else if(operation.getText().equals("*"))
{
result = fNumber * sNumber ;
value1.setText(null);
value2.setText(String.valueOf(result));
}
else if(operation.getText().equals("/"))
{
result = fNumber / sNumber ;
value1.setText(null);
value2.setText(String.valueOf(result));
}
}
});
//ALT+8592
button_undo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String bkspace = null;
if(value2.getText().length() > 0)
{
StringBuilder strB = new StringBuilder(value2.getText());
strB.deleteCharAt(value2.getText().length() - 1);
bkspace = strB.toString();
value2.setText(bkspace);
}
}
});
button_undo.setFont(new Font("Cambria Math", Font.PLAIN, 19));
button_undo.setBounds(10, 138, 50, 31);
frmCalculator.getContentPane().add(button_undo);
button_equal.setFont(new Font("Cambria Math", Font.PLAIN, 18));
button_equal.setBounds(249, 264, 50, 73);
frmCalculator.getContentPane().add(button_equal);
btnExit.setBackground(new Color(255, 99, 71));
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
btnExit.setFont(new Font("Cambria Math", Font.PLAIN, 12));
btnExit.setBounds(11, 348, 51, 23);
frmCalculator.getContentPane().add(btnExit);
}
/**
* #return the activate_and_Deactivate
*/
public Object getActivate_and_Deactivate() {
return Activate_and_Deactivate;
}
/**
* #param activate_and_Deactivate the activate_and_Deactivate to set
*/
public void setActivate_and_Deactivate(Object activate_and_Deactivate) {
Activate_and_Deactivate = activate_and_Deactivate;
}
}
package Calculators;
import javax.swing.JButton;
import javax.swing.JRadioButton;
public class Activate_and_Deactivate extends UIFrame
{
public void activate()
{
button0.setEnabled(true);
button1.setEnabled(true);
button2.setEnabled(true);
button3.setEnabled(true);
button4.setEnabled(true);
button5.setEnabled(true);
button6.setEnabled(true);
button7.setEnabled(true);
button8.setEnabled(true);
button9.setEnabled(true);
button_Div .setEnabled(true);
button_C .setEnabled(true);
button_Mul.setEnabled(true);
button_Add.setEnabled(true);
button_Sub.setEnabled(true);
button_Dot.setEnabled(true);
button_rec.setEnabled(true);
button_Sqr.setEnabled(true);
button_neg.setEnabled(true);
button_per .setEnabled(true);
button_equal.setEnabled(true);
button_undo .setEnabled(true);
btnExit .setEnabled(true);
rdbtnOff.setEnabled(true);
rdbtnOn.setEnabled(false);
}
public void deactivate()
{
button0.setEnabled(false);
button1.setEnabled(false);
button2.setEnabled(false);
button3.setEnabled(false);
button4.setEnabled(false);
button5.setEnabled(false);
button6.setEnabled(false);
button7.setEnabled(false);
button8.setEnabled(false);
button9.setEnabled(false);
button_Div .setEnabled(false);
button_C .setEnabled(false);
button_Mul.setEnabled(false);
button_Add.setEnabled(false);
button_Sub.setEnabled(false);
button_Dot.setEnabled(false);
button_rec.setEnabled(false);
button_Sqr.setEnabled(false);
button_neg.setEnabled(false);
button_per .setEnabled(false);
button_equal.setEnabled(false);
button_undo .setEnabled(false);
btnExit .setEnabled(false);
rdbtnOn.setEnabled(true);
rdbtnOff.setEnabled(false);
}
}
Its not working. Can someone help me.
Many thanks.
As far as I know, you can not use your base class as an instance of your derived class.
However, you can store an instance of the derived class in your base class and then cast it back to the derived class when you need to. See the ActionListener on the button for an example
Base
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class SimpleClass extends JFrame {
public SimpleClass(String title) {
super(title);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout());
setUp();
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public SimpleClass() {
}
public void setUp() {
JPanel panel = new JPanel();
ExtendedClass e = new ExtendedClass();
SimpleClass s = new ExtendedClass();
SimpleClass thisInstance = this;
JButton button = new JButton("Press Me");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
System.out.println(e instanceof ExtendedClass);
e.printLn();
System.out.println(s instanceof ExtendedClass);
((ExtendedClass)s).printLn();
System.out.println(thisInstance instanceof ExtendedClass);
//Returns an exception as it is not an instance of ExtendedClass
((ExtendedClass)thisInstance).printLn();
}
});
panel.add(button);
getContentPane().add(panel);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new SimpleClass("Title"));
}
}
Extended
#SuppressWarnings("serial")
public class ExtendedClass extends SimpleClass {
public void printLn() {
System.out.println("Printed A Line To The Console :)");
}
}

can not refer a value to a radiobutton

i write a convert temperature code using radiobutton, but when i use actionListener to print the value to a label, it show "Cannot refer to the non-final local variable valueto defined in an enclosing scope"
can some one show me the problem and how to fix it? (also sorry for my English)
the Radiobutton
JRadioButton Cbutton = new JRadioButton("Celsius");
Fbutton.setFont(new Font("Tahoma", Font.PLAIN, 12));
Fbutton.setBounds(10, 40, 109, 23);
contentPane.add(Cbutton);
JRadioButton Fbutton2 = new JRadioButton("Fahrenheit");
Fbutton2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
label.setText(String.valueOf(valueto));
}
});
i use this to convert
if(Fbutton.isSelected()&&Cbutton2.isSelected()){
value=F;
valueto=(F-32)/1.8;
}else if(Fbutton.isSelected()&&Kbutton2.isSelected()){
value=F;
valueto=(F+459.67)*5/9;
}else if(Cbutton.isSelected()&&Fbutton2.isSelected()){
value=C;
valueto=C*1.8+32;
}else if(Cbutton.isSelected()&&Kbutton2.isSelected()){
value=C;
valueto=C+273.15;
}else if(Kbutton.isSelected()&&Cbutton2.isSelected()){
value=K;
valueto=K-273.15;
}else if(Kbutton.isSelected()&&Fbutton2.isSelected()){
value=K;
valueto=K*9.5-459.67;
}
Edit : i declare valueto at the bottom of the class
double value = 0;
double valueto = 0;
double F = 0, C = 0, K = 0;
it ask me to add final to "double valueto", but when i add it the valueto in "if" become error
The Whole code
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class CtoKtoF extends JFrame {
private JPanel contentPane;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
CtoKtoF frame = new CtoKtoF();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
* #return
*/
public CtoKtoF() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 303);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
double value = 0 ;
double valueto = 0;
double F = 0, C = 0, K = 0;
Border border = LineBorder.createGrayLineBorder();//make border for Jlabel
final JLabel label = new JLabel("New label");
label.setFont(new Font("Tahoma", Font.PLAIN, 12));
label.setBounds(10, 228, 220, 22);
label.setBorder(border);
contentPane.add(label);
JLabel lblNewLabel = new JLabel("Convert from");
lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 12));
lblNewLabel.setBounds(10, 11, 92, 22);
contentPane.add(lblNewLabel);
JRadioButton Fbutton = new JRadioButton("Fahrenheit");
Fbutton.setFont(new Font("Tahoma", Font.PLAIN, 12));
Fbutton.setBounds(10, 40, 109, 23);
//Fbutton.setActionCommand("F");
contentPane.add(Fbutton);
JRadioButton Cbutton = new JRadioButton("Celcius");
Cbutton.setFont(new Font("Tahoma", Font.PLAIN, 12));
Cbutton.setBounds(121, 40, 109, 23);
//Cbutton.setActionCommand("C");
contentPane.add(Cbutton);
JRadioButton Kbutton = new JRadioButton("Kelvin");
Kbutton.setFont(new Font("Tahoma", Font.PLAIN, 12));
Kbutton.setBounds(232, 40, 109, 23);
//Kbutton.setActionCommand("K");
contentPane.add(Kbutton);
JLabel lblEnterNumericTemperature = new JLabel("Enter Numeric Temperature");
lblEnterNumericTemperature.setFont(new Font("Tahoma", Font.PLAIN, 12));
lblEnterNumericTemperature.setBounds(10, 70, 238, 22);
contentPane.add(lblEnterNumericTemperature);
textField = new JTextField();
textField.setFont(new Font("Tahoma", Font.PLAIN, 12));
textField.setBounds(10, 103, 220, 22);
textField.setText(String.valueOf(value));
contentPane.add(textField);
textField.setColumns(10);
JRadioButton Fbutton2 = new JRadioButton("Fahrenheit");
Fbutton2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
label.setText(String.valueOf(valueto));
}
});
Fbutton2.setFont(new Font("Tahoma", Font.PLAIN, 12));
Fbutton2.setBounds(10, 165, 109, 23);
//Fbutton2.setActionCommand("F2");
contentPane.add(Fbutton2);
JRadioButton Cbutton2 = new JRadioButton("Celcius");
Cbutton2.setFont(new Font("Tahoma", Font.PLAIN, 12));
Cbutton2.setBounds(121, 165, 109, 23);
//Cbutton2.setActionCommand("C2");
contentPane.add(Cbutton2);
JRadioButton Kbutton2 = new JRadioButton("Kelvin");
Kbutton2.setFont(new Font("Tahoma", Font.PLAIN, 12));
Kbutton2.setBounds(232, 165, 109, 23);
//Kbutton2.setActionCommand("K2");
contentPane.add(Kbutton2);
ButtonGroup group1 = new ButtonGroup();
group1.add(Fbutton);
group1.add(Kbutton);
group1.add(Cbutton);
ButtonGroup group2 = new ButtonGroup();
group2.add(Fbutton2);
group2.add(Cbutton2);
group2.add(Kbutton2);
/*Fbutton.addActionListener(this);
Cbutton.addActionListener(this);
Kbutton.addActionListener(this);
Fbutton2.addActionListener(this);
Cbutton2.addActionListener(this);
Kbutton2.addActionListener(this);*/
//boolean checked = Fbutton.getState();
JLabel lblConvertTo = new JLabel("Convert to");
lblConvertTo.setFont(new Font("Tahoma", Font.PLAIN, 12));
lblConvertTo.setBounds(10, 136, 92, 22);
contentPane.add(lblConvertTo);
JLabel lblComparableTemperatureIs = new JLabel("Comparable Temperature is");
lblComparableTemperatureIs.setFont(new Font("Tahoma", Font.PLAIN, 12));
lblComparableTemperatureIs.setBounds(10, 195, 238, 22);
contentPane.add(lblComparableTemperatureIs);
if(Fbutton.isSelected()&&Cbutton2.isSelected()){
value=F;
valueto=(F-32)/1.8;
}else if(Fbutton.isSelected()&&Kbutton2.isSelected()){
value=F;
valueto=(F+459.67)*5/9;
}else if(Cbutton.isSelected()&&Fbutton2.isSelected()){
value=C;
valueto=C*1.8+32;
}else if(Cbutton.isSelected()&&Kbutton2.isSelected()){
value=C;
valueto=C+273.15;
}else if(Kbutton.isSelected()&&Cbutton2.isSelected()){
value=K;
valueto=K-273.15;
}else if(Kbutton.isSelected()&&Fbutton2.isSelected()){
value=K;
valueto=K*9.5-459.67;
}
}
}

Toggle Java JPanels - each panel deifferent class

I'm a beginer in Java GUI, and i have an issue with trying to toggle between panel in other class.
My main Class "MyBoxGUI" has 2 Panels, "Login" and "UserMenu"
The default is "Login" panel, when pressing "OK" the window moved to "UserMenu" Panel.
So far so good while in the same class.
The issue is, when i set a new panel in new class and setvisibe that panel, i can't go back to "UserMenu" panel - (The actionlistener is working fine).
Can someone help me please?
MyBoxGUI Class
package main;
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.CardLayout;
import java.awt.Component;
//import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.Color;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import java.awt.Toolkit;
import GUIs.*;
//import ocsf.client.*;
public class MyBoxGUI extends JPanel
{
private Mtds mtd;
public JFrame frmMybox;
private static JTextField UserName;
private static JTextField port;
private static JTextField IP;
private static JPasswordField passwordField;
public final JPanel Login = new JPanel();
public final JPanel UserMenu = new JPanel();
/**
* Launch the application.
*/
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
MyBoxGUI window = new MyBoxGUI();
window.frmMybox.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MyBoxGUI()
{
mtd = new Mtds();
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize()
{
frmMybox = new JFrame();
frmMybox.setFont(new Font("Tempus Sans ITC", Font.BOLD, 15));
// frmMybox.setIconImage(Toolkit.getDefaultToolkit().getImage(MyBoxGUI.class.getResource("/images/gift-ideas-gift-card-bridal-gift-baby-shower-gift-gift-box-groom-gift-christmas-gift-party-gift-gift-for-wedding-friend-gift-birthday-gift-baby-gift-good-gift-box-ideas-for-friend-necklace-gift-box.jpg")));
frmMybox.setBounds(100, 100, 800, 500);
frmMybox.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmMybox.getContentPane().setLayout(new CardLayout(0, 0));
frmMybox.setTitle("MyBox");
frmMybox.getContentPane().add(Login);
Login.setLayout(null);
JButton btnNewButton = new JButton("OK");
btnNewButton.addActionListener(new ActionListener()
{
#SuppressWarnings("deprecation")
public void actionPerformed(ActionEvent arg0)
{
Boolean ok = false;
String UName, Pass, Prt, SIP;
UName = UserName.getText();
Pass = passwordField.getText();
Prt = port.getText();
SIP = IP.getText();
if( ( mtd.isUserValid(UName) && mtd.isPasswordValid(Pass) && mtd.isPortValid(Prt) && mtd.isIPValid(SIP))
&& ( !UName.equals("") && !Pass.equals("") && !Prt.equals("") && !SIP.equals("") ) )
ok = true;
else
{
if(!mtd.isUserValid(UName) || UName.equals(""))
JOptionPane.showMessageDialog(frmMybox,"User Name Can Contain Only The Following Characters: ( 0-9 , a-z , A-Z , _ )"
+ " ","Invalid characters",JOptionPane.WARNING_MESSAGE);
else if(!mtd.isPasswordValid(Pass) || Pass.equals(""))
JOptionPane.showMessageDialog(frmMybox,"Invalid characters","Error Message",JOptionPane.WARNING_MESSAGE);
else if(!mtd.isPortValid(Prt) || Prt.equals(""))
JOptionPane.showMessageDialog(frmMybox,"Port Can Contain Only Numbers","Invalid characters",JOptionPane.WARNING_MESSAGE);
else if(!mtd.isIPValid(SIP) || SIP.equals(""))
JOptionPane.showMessageDialog(frmMybox,"IP Address Can Contain Only Numbers seperated By Dots '.' ","Invalid characters",JOptionPane.WARNING_MESSAGE);
}
if(ok)
{
//LoginController user = new LoginController();
//chat= new ClientGUI(IP.getText(),port.getText());
//client = ClientGUI.getClient();
//msg=new Msg("login",user);
//client.handleMessageFromClientUI(msg);
setScreen(Login,UserMenu);
// frmMybox.getContentPane().add(UserMenu, "UserMenu");
// UserMenu.setVisible(true);
// Login.setVisible(false);
}
}
});
btnNewButton.setBounds(344, 313, 82, 48);
Login.add(btnNewButton);
JLabel lblWellcomeToMybox = new JLabel("Wellcome to MyBox");
lblWellcomeToMybox.setForeground(new Color(51, 204, 255));
lblWellcomeToMybox.setFont(new Font("Arial", Font.PLAIN, 36));
lblWellcomeToMybox.setBounds(224, 23, 327, 42);
Login.add(lblWellcomeToMybox);
JLabel lblUserName = new JLabel("User Name:");
lblUserName.setBounds(268, 109, 89, 14);
lblUserName.setFont(new Font("Arial", Font.PLAIN, 14));
Login.add(lblUserName);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setBounds(268, 139, 69, 14);
lblPassword.setFont(new Font("Arial", Font.PLAIN, 14));
Login.add(lblPassword);
JLabel lblServerPort = new JLabel("Server port:");
lblServerPort.setBounds(268, 197, 82, 14);
lblServerPort.setFont(new Font("Arial", Font.PLAIN, 14));
Login.add(lblServerPort);
JLabel lblServerIp = new JLabel("Server IP:");
lblServerIp.setBounds(266, 222, 71, 14);
lblServerIp.setFont(new Font("Arial", Font.PLAIN, 14));
Login.add(lblServerIp);
UserName = new JTextField();
UserName.setBounds(406, 107, 96, 20);
Login.add(UserName);
UserName.setColumns(10);
port = new JTextField();
port.setBounds(406, 195, 96, 20);
Login.add(port);
port.setColumns(10);
IP = new JTextField();
IP.setBounds(406, 220, 96, 20);
Login.add(IP);
IP.setColumns(10);
passwordField = new JPasswordField();
passwordField.setBounds(406, 137, 96, 20);
Login.add(passwordField);
frmMybox.getContentPane().add(UserMenu, "User Menu");
UserMenu.setLayout(null);
JButton LeaveGOI = new JButton("Back");
LeaveGOI.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
setScreen(UserMenu,Login);
}
});
LeaveGOI.setBounds(10, 66, 153, 23);
UserMenu.add(LeaveGOI);
JButton btnJoinAGoi = new JButton("Join a GOI");
btnJoinAGoi.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
}
});
btnJoinAGoi.setBounds(10, 100, 153, 23);
UserMenu.add(btnJoinAGoi);
JButton btnSearchForA = new JButton("Search for a GOI");
btnSearchForA.setBounds(10, 134, 153, 23);
UserMenu.add(btnSearchForA);
JButton btnCreateAGoi = new JButton("Create a GOI");
btnCreateAGoi.setBounds(10, 32, 153, 23);
UserMenu.add(btnCreateAGoi);
JButton btnFilesSharedWith = new JButton("Files shared with you");
btnFilesSharedWith.setBounds(271, 66, 153, 23);
UserMenu.add(btnFilesSharedWith);
JButton btnUploadAFile = new JButton("Upload a file");
btnUploadAFile.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
JPanel UpLoad = new UploadFile();
setScreen(UserMenu,UpLoad);
// frmMybox.getContentPane().add(UpLoad, "UpLoad");
// UserMenu.setVisible(false);
// UpLoad.setVisible(true);
}
});
btnUploadAFile.setBounds(271, 32, 153, 23);
UserMenu.add(btnUploadAFile);
JButton btnSignout = new JButton("Sign-Out");
btnSignout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int dialog=JOptionPane.showConfirmDialog(Login, getUserName()+", are you sure you wants to leave?", "Do you want to leave?", JOptionPane.YES_NO_OPTION);
if(dialog==0){
//client.quit();
}
}
});
btnSignout.setBounds(293, 227, 131, 23);
UserMenu.add(btnSignout);
JButton btnHelpme = new JButton("Help-Me");
btnHelpme.addActionListener(new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
JOptionPane.showMessageDialog(Login,"Hello "+ getUserName()+", wellcom to Mybox!\n"
+ "Inside GOIs buttons you can ask to join, leave and even create a GOI.\n"
+ "Inside Files buttons you can check and edit files people shared with you.\n"
+ "You can even become an uploader and share files you own.\n"
+ "We wish you good luck and have fun using MyBox!");
}
});
btnHelpme.setBounds(10, 227, 131, 23);
UserMenu.add(btnHelpme);
}
public static String getUserName(){
return UserName.getText();
}
#SuppressWarnings("deprecation")
public static String getPassword(){
return passwordField.getText();
}
public static String getIP(){
return IP.getText();
}
public static String getPort(){
return port.getText();
}
public void setScreen(JPanel fls, JPanel tru)
{
frmMybox.getContentPane().add(tru);
tru.setVisible(true);
fls.setVisible(false);
}
}
UploadFile Class
package GUIs;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import main.MyBoxGUI;
public class UploadFile extends MyBoxGUI {
private JTextField textField;
/**
* Create the panel.
*/
public static final JPanel UpLoad = new JPanel();
public UploadFile()
{
setBounds(100, 100, 800, 500);
setLayout(null);
JButton btnNewButton = new JButton("Back");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
setScreen(UpLoad,UserMenu);
System.out.print("A+++");
}
});
btnNewButton.setBounds(126, 145, 205, 30);
add(btnNewButton);
textField = new JTextField();
textField.setBounds(409, 150, 300, 20);
add(textField);
textField.setColumns(10);
JButton btnDone = new JButton("Done");
btnDone.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnDone.setBounds(365, 223, 89, 30);
add(btnDone);
JButton btnHelpMe = new JButton("Help Me");
btnHelpMe.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnHelpMe.setBounds(188, 390, 122, 52);
add(btnHelpMe);
JButton SignOut = new JButton("Sign-Out");
SignOut.setBounds(501, 392, 122, 48);
add(SignOut);
}
}
public void setScreen(JPanel fls, JPanel tru)
{
frmMybox.getContentPane().add(tru);
tru.setVisible(true);
fls.setVisible(false);
frmMybox.getContentPane().revalidate();
frmMybox.getContentPane().repaint();
}
update your setScreen method as above.

no content in Jframe java

i have two jframes in my app, Addnmember.java and Frame1.java
Frame1 is the main Jframe,
i want when someone presses the Add button, the Addmember will be shown, i have done this with this code, and every thing is fine:
AddB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
frame.dispose();
AddMember addmem = new AddMember();
addmem.setVisible(true);
}
});
But in the new Jframe, i want to come back again when Done Bt is selected, i have done this whit this code:
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//dispose();
Frame1 addmem = new Frame1();
addmem.setVisible(true);
}
});
but this doesent work! mean the Jframe Loads but there is no content in it! look:
why this happens? here is my codes:
AddMember.java:
public class AddMember extends JFrame {
private JFrame frame;
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
private JTextField textField_4;
private JTextField textField_5;
private JTextField textField_6;
private JButton btnNewButton;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AddMember frame = new AddMember();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public AddMember() {
setTitle("\u0627\u0641\u0632\u0648\u062F\u0646 \u0639\u0636\u0648 \u062C\u062F\u06CC\u062F");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 331);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel label = new JLabel("\u0646\u0627\u0645:");
label.setFont(new Font("Tahoma", Font.BOLD, 11));
label.setBounds(332, 60, 46, 14);
contentPane.add(label);
textField = new JTextField();
textField.setToolTipText("\u0646\u0627\u0645");
textField.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
textField.setText("");
}
});
textField.setHorizontalAlignment(SwingConstants.RIGHT);
textField.setText("\u0646\u0627\u0645");
textField.setBounds(236, 57, 86, 20);
contentPane.add(textField);
textField.setColumns(10);
JLabel label_1 = new JLabel("\u0634.\u062F\u0627\u0646\u0634\u062C\u0648\u06CC\u06CC:");
label_1.setFont(new Font("Tahoma", Font.BOLD, 11));
label_1.setBounds(328, 103, 85, 14);
contentPane.add(label_1);
textField_1 = new JTextField();
textField_1.setToolTipText("\u0634\u0645\u0627\u0631\u0647 \u062F\u0627\u0646\u0634\u062C\u0648\u06CC\u06CC");
textField_1.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
textField_1.setText("");
}
});
textField_1.setText("\u0634\u0645\u0627\u0631\u0647 \u062F\u0627\u0646\u0634\u062C\u0648\u06CC\u06CC");
textField_1.setHorizontalAlignment(SwingConstants.RIGHT);
textField_1.setColumns(10);
textField_1.setBounds(236, 100, 86, 20);
contentPane.add(textField_1);
JLabel label_2 = new JLabel("\u0631\u0634\u062A\u0647:");
label_2.setFont(new Font("Tahoma", Font.BOLD, 11));
label_2.setBounds(332, 145, 46, 14);
contentPane.add(label_2);
textField_2 = new JTextField();
textField_2.setToolTipText("\u0631\u0634\u062A\u0647 \u062A\u062D\u0635\u06CC\u0644\u06CC");
textField_2.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
textField_2.setText("");
}
});
textField_2.setText("\u0631\u0634\u062A\u0647 \u062A\u062D\u0635\u06CC\u0644\u06CC");
textField_2.setHorizontalAlignment(SwingConstants.RIGHT);
textField_2.setColumns(10);
textField_2.setBounds(236, 142, 86, 20);
contentPane.add(textField_2);
JLabel label_3 = new JLabel("\u0646\u0627\u0645 \u062E\u0627\u0646\u0648\u0627\u062F\u06AF\u06CC:");
label_3.setFont(new Font("Tahoma", Font.BOLD, 11));
label_3.setBounds(144, 61, 82, 14);
contentPane.add(label_3);
textField_3 = new JTextField();
textField_3.setToolTipText("\u0646\u0627\u0645 \u062E\u0627\u0646\u0648\u0627\u062F\u06AF\u06CC");
textField_3.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
textField_3.setText("");
}
});
textField_3.setText("\u0646\u0627\u0645 \u062E\u0627\u0646\u0648\u0627\u062F\u06AF\u06CC");
textField_3.setHorizontalAlignment(SwingConstants.RIGHT);
textField_3.setColumns(10);
textField_3.setBounds(48, 58, 86, 20);
contentPane.add(textField_3);
JLabel label_4 = new JLabel("\u0634. \u062A\u0645\u0627\u0633:");
label_4.setFont(new Font("Tahoma", Font.BOLD, 11));
label_4.setBounds(144, 104, 69, 14);
contentPane.add(label_4);
textField_4 = new JTextField();
textField_4.setToolTipText("\u0634\u0645\u0627\u0631\u0647 \u062A\u0645\u0627\u0633");
textField_4.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
textField_4.setText("");
}
});
textField_4.setText("\u0634\u0645\u0627\u0631\u0647 \u062A\u0645\u0627\u0633");
textField_4.setHorizontalAlignment(SwingConstants.RIGHT);
textField_4.setColumns(10);
textField_4.setBounds(48, 101, 86, 20);
contentPane.add(textField_4);
textField_5 = new JTextField();
textField_5.setToolTipText("\u0633\u0627\u0644 \u0648\u0631\u0648\u062F");
textField_5.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
textField_5.setText("");
}
});
textField_5.setText("\u0633\u0627\u0644 \u0648\u0631\u0648\u062F");
textField_5.setHorizontalAlignment(SwingConstants.RIGHT);
textField_5.setColumns(10);
textField_5.setBounds(48, 140, 86, 20);
contentPane.add(textField_5);
JLabel label_5 = new JLabel("\u0648\u0631\u0648\u062F\u06CC:");
label_5.setFont(new Font("Tahoma", Font.BOLD, 11));
label_5.setBounds(144, 143, 46, 14);
contentPane.add(label_5);
textField_6 = new JTextField();
textField_6.setToolTipText("\u0636\u0631\u0648\u0631\u06CC \u0646\u06CC\u0633\u062A");
textField_6.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
textField_6.setText("");
}
});
textField_6.setHorizontalAlignment(SwingConstants.RIGHT);
textField_6.setText("\u0636\u0631\u0648\u0631\u06CC \u0646\u06CC\u0633\u062A");
textField_6.setColumns(10);
textField_6.setBounds(131, 187, 86, 20);
contentPane.add(textField_6);
JLabel label_6 = new JLabel("\u0627\u06CC\u0645\u06CC\u0644:");
label_6.setFont(new Font("Tahoma", Font.BOLD, 11));
label_6.setBounds(227, 190, 46, 14);
contentPane.add(label_6);
btnNewButton = new JButton("Done");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//dispose();
Frame1 addmem = new Frame1();
addmem.setVisible(true);
}
});
btnNewButton.setFont(new Font("Tahoma", Font.BOLD, 11));
btnNewButton.setBounds(171, 227, 89, 23);
contentPane.add(btnNewButton);
}
private static void addPopup(Component component, final JPopupMenu popup) {
component.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()) {
showMenu(e);
}
}
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
showMenu(e);
}
}
private void showMenu(MouseEvent e) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
});
}
}
And Frame1.java:
public class Frame1 extends JFrame {
Connection connection = null;
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Frame1 window = new Frame1();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
private JTable table;
public Frame1() {
JOptionPane.showMessageDialog(null, "sazande :|");
this.initialize();
connection = DataBConect.dbConnect();
try {
String query = "select * from Users";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
JOptionPane.showMessageDialog(null, "intialize :|");
frame.setTitle("App");
frame.setBounds(100, 100, 725, 465);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton AddB = new JButton("Add");
AddB.setBackground(Color.WHITE);
AddB.setFont(new Font("Tahoma", Font.BOLD, 11));
AddB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
frame.dispose();
AddMember addmem = new AddMember();
addmem.setVisible(true);
}
});
AddB.setBounds(302, 392, 135, 23);
frame.getContentPane().add(AddB);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(22, 26, 658, 359);
frame.getContentPane().add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
}
}
thanks.
As to why your second Frame1 shows no data, I'm not 100% sure, but perhaps it has something to do with your failure to close your database connection. Regardless, it seems wasteful and even potentially dangerous to want to gather the database data twice when you've already obtained it once, and to create your Frame1 GUI twice when you've already created it once.
You should re-design your GUI. The main JFrame GUI should remain visible, and the Frame1 window should be a modal JDialog. As a modal dialog, it will prevent users from being able to interact with the parent JFrame until the dialog is no longer visible.
Note that to get started requires only a few changes:
in Frame1.java
AddB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// frame.dispose();
AddMember addmem = new AddMember(Frame1.this); // !!
addmem.setVisible(true);
}
});
in AddMember.java
class AddMember extends JDialog {
public AddMember(JFrame frame) {
super(frame, "", ModalityType.APPLICATION_MODAL);
setTitle("\u0627\u0641\u0632\u0648\u062F\u0646 \u0639\u0636\u0648 \u062C\u062F\u06CC\u062F");
// !! setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// dispose();
dispose(); // !!
// !! Frame1 addmem = new Frame1();
// addmem.setVisible(true);
}
});
Also, you'll want to avoid null layouts and setBounds(...) as this will lead to very rigid, hard to debug and improve programs.

Connecting of Database per each JFrame

I have created this Automated Library. And I need to know how to connect my Database per each JFrame.
This is my main method:
package com.Student.GUI;
public class Student_HomePage extends JFrame {
private JPanel contentPane;
private JTextField searchBox;
private static String results[];
private static Connection conn;
private static String searchText;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DBConnect db = new DBConnect();
conn = db.openConnection();
Student_HomePage frame = new Student_HomePage();
frame.setVisible(true);
frame.setBounds(400,150,599,489);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Student_HomePage() {
setBackground(Color.WHITE);
setIconImage(Toolkit.getDefaultToolkit().getImage("D:\\ITC302-Core Java\\java_workspace\\Pictures\\lala.png"));
setTitle("LookBook");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 599, 489);
contentPane = new JPanel();
contentPane.setBackground(Color.WHITE);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnHome = new JButton("Home");
btnHome.setFont(new Font("Plantagenet Cherokee", Font.PLAIN, 16));
btnHome.setEnabled(false);
btnHome.setContentAreaFilled(false);
btnHome.setBorder(null);
btnHome.setBounds(144, 24, 95, 25);
contentPane.add(btnHome);
JButton btnAuthors = new JButton("Authors");
btnAuthors.setFont(new Font("Plantagenet Cherokee", Font.PLAIN, 16));
btnAuthors.setContentAreaFilled(false);
btnAuthors.setBorder(null);
btnAuthors.setBounds(241, 24, 95, 25);
contentPane.add(btnAuthors);
JButton btnBooks = new JButton("Books");
btnBooks.setFont(new Font("Plantagenet Cherokee", Font.PLAIN, 16));
btnBooks.setContentAreaFilled(false);
btnBooks.setBorder(null);
btnBooks.setBounds(338, 24, 95, 25);
contentPane.add(btnBooks);
JTextArea textArea = new JTextArea();
textArea.setText("|");
textArea.setFont(new Font("Monospaced", Font.PLAIN, 35));
textArea.setEditable(false);
textArea.setBounds(227, 11, 26, 57);
contentPane.add(textArea);
JTextArea textArea_1 = new JTextArea();
textArea_1.setText("|");
textArea_1.setFont(new Font("Monospaced", Font.PLAIN, 35));
textArea_1.setEditable(false);
textArea_1.setBounds(325, 11, 26, 57);
contentPane.add(textArea_1);
searchBox = new JTextField();
searchBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String temp = new String(searchBox.getText());
searchText = temp;
}
});
searchBox.setColumns(10);
searchBox.setBounds(37, 210, 148, 25);
contentPane.add(searchBox);
JTextArea textArea_2 = new JTextArea();
textArea_2.setText("Search title of books,\r\nauthors or genre");
textArea_2.setFont(new Font("Plantagenet Cherokee", Font.PLAIN, 14));
textArea_2.setBounds(37, 248, 188, 40);
contentPane.add(textArea_2);
JButton btnSearch = new JButton("Search");
btnSearch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String temp = new String(searchBox.getText());
btnSearchActionPerformed(e, temp);
}
});
btnSearch.setIcon(new ImageIcon("D:\\ITC302-Core Java\\java_workspace\\Pictures\\searchIcon.png"));
btnSearch.setContentAreaFilled(false);
btnSearch.setBorder(null);
btnSearch.setBackground(Color.WHITE);
btnSearch.setBounds(185, 210, 87, 25);
contentPane.add(btnSearch);
JLabel label = new JLabel("");
label.setIcon(new ImageIcon("D:\\ITC302-Core Java\\java_workspace\\Pictures\\download.jpg"));
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setBounds(270, 202, 290, 215);
contentPane.add(label);
JLabel bookIcon = new JLabel("");
bookIcon.setIcon(new ImageIcon("D:\\ITC302-Core Java\\java_workspace\\Pictures\\BookIcon.png"));
bookIcon.setBounds(101, 78, 116, 90);
contentPane.add(bookIcon);
JLabel lookBookIcon = new JLabel("");
lookBookIcon.setIcon(new ImageIcon("D:\\ITC302-Core Java\\java_workspace\\Pictures\\image.png"));
lookBookIcon.setBounds(213, 74, 290, 135);
contentPane.add(lookBookIcon);
}
public void btnSearchActionPerformed (ActionEvent e, String searchText) {
DBConnect db = new DBConnect();
results = db.selectMatchedData(searchText, conn);
//if (results.length != 0) {
this.dispose();
Student_SearchList window = new Student_SearchList();
window.setVisible(true);
//}
//else {
//Student_Warning window = new Student_Warning();
//window.setVisible(true);
//}
}
}
And this is where I want to connect my Database:
JButton btnSearch = new JButton("Search");
btnSearch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String temp = new String(searchBox.getText());
btnSearchActionPerformed(e, temp);
}
});
This whole code is my Main.java.

Categories

Resources