Add to JLabel method? - java

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.

Related

GUI goes blank when i try to define the public void actionPerformed(ActionEvent arg0)

When I try to add some function to get data from jtext field under public void actionPerformed(ActionEvent arg0) My GUI goes blank I have attached the images below I can't figure out what's wrong with it.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Register extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
private JTextField textField_4;
private JLabel lblNewLabel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Register frame = new Register();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Register() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblName = new JLabel("Name");
lblName.setBounds(56, 56, 56, 16);
contentPane.add(lblName);
JLabel lblUsername = new JLabel("Username");
lblUsername.setBounds(56, 85, 77, 16);
contentPane.add(lblUsername);
JLabel lblPassword = new JLabel("Password");
lblPassword.setBounds(56, 114, 56, 16);
contentPane.add(lblPassword);
JLabel lblAge = new JLabel("Age");
lblAge.setBounds(56, 143, 56, 16);
contentPane.add(lblAge);
JLabel lblGender = new JLabel("Gender");
lblGender.setBounds(56, 172, 56, 16);
contentPane.add(lblGender);
textField = new JTextField();
textField.setBounds(130, 53, 116, 19);
contentPane.add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(130, 82, 116, 22);
contentPane.add(textField_1);
textField_1.setColumns(10);
textField_2 = new JTextField();
textField_2.setBounds(130, 111, 116, 22);
contentPane.add(textField_2);
textField_2.setColumns(10);
textField_3 = new JTextField();
textField_3.setBounds(130, 140, 116, 22);
contentPane.add(textField_3);
textField_3.setColumns(10);
textField_4 = new JTextField();
textField_4.setBounds(130, 169, 116, 22);
contentPane.add(textField_4);
textField_4.setColumns(10);
JButton btnSubmit = new JButton("Submit");
btnSubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnSubmit.setBounds(169, 215, 97, 25);
contentPane.add(btnSubmit);
lblNewLabel = new JLabel("New label");
lblNewLabel.setBounds(330, 56, 56, 16);
contentPane.add(lblNewLabel);
}
}
EDIT 1: Added String name to action just to get name.
JButton btnSubmit = new JButton("Submit");
btnSubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String Name;
}
});
and This happened
GUI went blank:
You're using an absolute layout. Since you can't pack() the window, you need to at least validate() its contents.
Register frame = new Register();
frame.validate();
frame.setVisible(true);
Now you can see the real problem: you picked bounds for lblPassword and lblNewLabel that cut off the text on my computer. You really need to use a layout, maybe like this.

JDialog shows empty

I was trying to replace the use of JOptionPane by a new custom dialog here is what I did:
package pk;
import java.util.Enumeration;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import java.awt.Font;
import javax.swing.JTextArea;
import java.awt.SystemColor;
import javax.swing.JPanel;
import java.awt.Color;
import javax.swing.border.LineBorder;
public class SIMessage extends JDialog implements ActionListener{
private static final long serialVersionUID = 1L;
public JButton oui=new JButton("Oui"),btnClose=new JButton(new ImageIcon("images\\logo\\delete.gif")),
non=new JButton("Non"),annuler=new JButton("Annuler"),ok=new JButton("OK");
public JLabel lblImgErr=new JLabel(new ImageIcon("images\\logo\\msgErreur.png")),
lblImgConf=new JLabel(new ImageIcon("images\\logo\\msgQuestion.png")),
lblImgWarning=new JLabel(new ImageIcon("images\\logo\\msgWarning.png")),
lblImgInfo=new JLabel(new ImageIcon("images\\logo\\msgInformation.png")),
lblImgQuestion=new JLabel(new ImageIcon("images\\logo\\msgQuestion.png")),
lblImgIconApp=new JLabel(new ImageIcon("images\\logo\\clntIco.ico"));
public JLabel title=new JLabel(),message=new JLabel();
public enum TypeMessage{
ERROR_MESSAGE,
CONFIRMATION_MESSAGE,
WARNING_MESSAGE,
INFORMATION_MESSAGE,
VALIDATION_MESSAGE
}
public SIMessage(JFrame parent,String title,TypeMessage type,String message) {
super(parent,true);
setUndecorated(true);
getContentPane().setLayout(new GridLayout(1, 1));
JPanel mainDgPanel = new JPanel();
mainDgPanel.setBorder(new LineBorder(new Color(255, 255, 255), 3, true));
mainDgPanel.setBounds(0, 0, 444, 156);
getContentPane().add(mainDgPanel);
mainDgPanel.setLayout(null);
mainDgPanel.setBackground(Color.decode(EcranPrincipal.blueThemeCP));
JTextArea txtrTextarea = new JTextArea(message);
txtrTextarea.setRows(2);
txtrTextarea.setBounds(123, 62, 340, 80);
txtrTextarea.setFont(new Font("Iskoola Pota", Font.PLAIN, 18));
txtrTextarea.setEditable(false);
txtrTextarea.setFocusable(false);
txtrTextarea.setOpaque(false);
txtrTextarea.setBorder(null);
txtrTextarea.setWrapStyleWord(true);
txtrTextarea.setLineWrap(true);
txtrTextarea.setForeground(Color.decode(EcranPrincipal.blueThemeBT));
mainDgPanel.add(txtrTextarea);
JPanel panelButtons = new JPanel();
panelButtons.setBounds(47, 115, 344, 30);
mainDgPanel.add(panelButtons);
switch(type)
{
case ERROR_MESSAGE:
{
JLabel lblNewLabel =lblImgErr;
lblNewLabel.setBounds(10, 69, 79, 14);
mainDgPanel.add(lblNewLabel);
JButton btnOk = ok;
panelButtons.add(btnOk);
break;
}
case CONFIRMATION_MESSAGE:
{
JLabel lblNewLabel =lblImgConf;
lblNewLabel.setBounds(10, 69, 79, 14);
mainDgPanel.add(lblNewLabel);
JButton btnOui = oui;
panelButtons.add(btnOui);
break;
}
case WARNING_MESSAGE:
{
JLabel lblNewLabel =lblImgWarning;
lblNewLabel.setBounds(10, 69, 79, 14);
mainDgPanel.add(lblNewLabel);
JButton btnOk = ok;
panelButtons.add(btnOk);
break;
}
case INFORMATION_MESSAGE:
{
JLabel lblNewLabel =lblImgInfo;
lblNewLabel.setBounds(10, 69, 79, 14);
mainDgPanel.add(lblNewLabel);
JButton btnOk = ok;
panelButtons.add(btnOk);
break;
}
case VALIDATION_MESSAGE:
{
JLabel lblNewLabel =lblImgConf;
lblNewLabel.setBounds(10, 69, 79, 14);
mainDgPanel.add(lblNewLabel);
JButton btnOui = oui;
panelButtons.add(btnOui);
JButton btnNon = non;
panelButtons.add(btnNon);
JButton btnAnnuler = annuler;
panelButtons.add(btnAnnuler);
break;
}
default:
}
ok.addActionListener(this);
oui.addActionListener(this);
JPanel panel = new JPanel();
panel.setBounds(0, 0, 444, 27);
mainDgPanel.add(panel);
panel.setBackground(Color.WHITE);
panel.setLayout(null);
JButton btnCloseDf = btnClose;
btnCloseDf.setBounds(411, 0, 39, 23);
panel.add(btnCloseDf);
JLabel lblIconApp =lblImgIconApp;
lblIconApp.setBounds(10, 4, 77, 14);
panel.add(lblIconApp);
JLabel lblTitle = new JLabel(title);
lblTitle.setBounds(190, 4, 46, 14);
panel.add(lblTitle);
this.pack();
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Object source=e.getSource();
if(source==oui||source==ok)
{
this.dispose();
}
}
Then I call:
SIMessage sm=new SIMessage(this, "Attention", SIMessage.TypeMessage.WARNING_MESSAGE,"You need to change ...");
callMethode2();
The problem is that it executes the call to Methode2 before showing any dialog while it is supposed to force the user to respond before continuing.
I see an empty window side by side with the window generated by callMethod2!, so what is wrong?
You should set the modality for Dialog.
A modal window is a graphical control element subordinate to an application's main window. It creates a mode that disables the main window but keeps it visible with the modal window as a child window in front of it. Users must interact with the modal window before they can return to the parent application.
So, Set the modal flag of the dialog when initializing it.
setModal(True)
edit:
I don't know what you exactly changed in your code, but the code below works fine for me:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author Emad
*/
import java.awt.BorderLayout;
import java.util.Enumeration;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import java.awt.Font;
import javax.swing.JTextArea;
import java.awt.SystemColor;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import javafx.event.ActionEvent;
import javax.swing.border.LineBorder;
public class SIMessage extends JDialog implements ActionListener {
private static final long serialVersionUID = 1L;
public JButton oui = new JButton("Oui"), btnClose = new JButton(new ImageIcon("images\\logo\\delete.gif")),
non = new JButton("Non"), annuler = new JButton("Annuler"), ok = new JButton("OK");
public JLabel lblImgErr = new JLabel(new ImageIcon("images\\logo\\msgErreur.png")),
lblImgConf = new JLabel(new ImageIcon("images\\logo\\msgQuestion.png")),
lblImgWarning = new JLabel(new ImageIcon("images\\logo\\msgWarning.png")),
lblImgInfo = new JLabel(new ImageIcon("images\\logo\\msgInformation.png")),
lblImgQuestion = new JLabel(new ImageIcon("images\\logo\\msgQuestion.png")),
lblImgIconApp = new JLabel(new ImageIcon("images\\logo\\clntIco.ico"));
public JLabel title = new JLabel(), message = new JLabel();
#Override
public void actionPerformed(java.awt.event.ActionEvent e) {
// TODO Auto-generated method stub
Object source = e.getSource();
if (source == oui || source == ok) {
this.dispose();
}
}
public enum TypeMessage {
ERROR_MESSAGE,
CONFIRMATION_MESSAGE,
WARNING_MESSAGE,
INFORMATION_MESSAGE,
VALIDATION_MESSAGE
}
public SIMessage(JFrame parent, String title, TypeMessage type, String message) {
super(parent, true);
setUndecorated(true);
getContentPane().setLayout(new GridLayout(1, 1));
JPanel mainDgPanel = new JPanel();
mainDgPanel.setBorder(new LineBorder(new Color(255, 255, 255), 3, true));
mainDgPanel.setBounds(0, 0, 444, 156);
getContentPane().add(mainDgPanel);
// mainDgPanel.setBackground(Color.decode(EcranPrincipal.blueThemeCP));
JTextArea txtrTextarea = new JTextArea(message);
txtrTextarea.setRows(2);
txtrTextarea.setBounds(123, 62, 340, 80);
txtrTextarea.setFont(new Font("Iskoola Pota", Font.PLAIN, 18));
txtrTextarea.setEditable(false);
txtrTextarea.setFocusable(false);
txtrTextarea.setOpaque(false);
txtrTextarea.setBorder(null);
txtrTextarea.setWrapStyleWord(true);
txtrTextarea.setLineWrap(true);
// txtrTextarea.setForeground(Color.decode(EcranPrincipal.blueThemeBT));
mainDgPanel.add(txtrTextarea);
JPanel panelButtons = new JPanel();
panelButtons.setBounds(47, 115, 344, 30);
mainDgPanel.add(panelButtons);
switch (type) {
case ERROR_MESSAGE: {
JLabel lblNewLabel = lblImgErr;
lblNewLabel.setBounds(10, 69, 79, 14);
mainDgPanel.add(lblNewLabel);
JButton btnOk = ok;
panelButtons.add(btnOk);
break;
}
case CONFIRMATION_MESSAGE: {
JLabel lblNewLabel = lblImgConf;
lblNewLabel.setBounds(10, 69, 79, 14);
mainDgPanel.add(lblNewLabel);
JButton btnOui = oui;
panelButtons.add(btnOui);
break;
}
case WARNING_MESSAGE: {
JLabel lblNewLabel = lblImgWarning;
lblNewLabel.setBounds(10, 69, 79, 14);
mainDgPanel.add(lblNewLabel);
JButton btnOk = ok;
panelButtons.add(btnOk);
break;
}
case INFORMATION_MESSAGE: {
JLabel lblNewLabel = lblImgInfo;
lblNewLabel.setBounds(10, 69, 79, 14);
mainDgPanel.add(lblNewLabel);
JButton btnOk = ok;
panelButtons.add(btnOk);
break;
}
case VALIDATION_MESSAGE: {
JLabel lblNewLabel = lblImgConf;
lblNewLabel.setBounds(10, 69, 79, 14);
mainDgPanel.add(lblNewLabel);
JButton btnOui = oui;
panelButtons.add(btnOui);
JButton btnNon = non;
panelButtons.add(btnNon);
JButton btnAnnuler = annuler;
panelButtons.add(btnAnnuler);
break;
}
default:
}
ok.addActionListener(this);
oui.addActionListener(this);
JPanel panel = new JPanel();
panel.setBounds(0, 0, 444, 27);
mainDgPanel.add(panel);
panel.setBackground(Color.WHITE);
panel.setLayout(null);
JButton btnCloseDf = btnClose;
btnCloseDf.setBounds(411, 0, 39, 23);
panel.add(btnCloseDf);
JLabel lblIconApp = lblImgIconApp;
lblIconApp.setBounds(10, 4, 77, 14);
panel.add(lblIconApp);
JLabel lblTitle = new JLabel(title);
lblTitle.setBounds(190, 4, 46, 14);
panel.add(lblTitle);
this.pack();
this.setVisible(true);
}
public static void main(String[] args)
{
SIMessage sm=new SIMessage(null, "Attention", SIMessage.TypeMessage.WARNING_MESSAGE,"You need to change ...");
System.out.println("hello");
}
}

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;
}
}
}

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

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

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
}

Categories

Resources