setText method with panel and button - java

I tried fixing this in so many ways, and tried searching for answers everywhere, my color buttons are working, but same way built number buttons do not....
package tralala;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.*;
public class DugmiciKojiMenjajuBoju extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 4317497849622426733L;
private JButton dugme1;
private JButton dugme2;
private JButton dugme3;
private JPanel panel;
private JOptionPane a;
private JPanel panel1;
private JButton dugmeBroja0;
private JButton dugmeBroja1;
private JButton dugmeBroja2;
private JButton dugmeBroja3;
private JButton dugmeBroja4;
private JButton dugmeBroja5;
private JButton dugmeBroja6;
private JButton dugmeBroja7;
private JButton dugmeBroja8;
private JButton dugmeBroja9;
private JButton dugmeZaPlus;
private JButton dugmeZaMinus;
private JButton dugmeZaPuta;
private JButton dugmeZaPodeljeno;
private JButton dugmeZaJednako;
private JTextField polje;
DugmiciKojiMenjajuBoju(){
getContentPane().setBackground(Color.white);
this.setLayout(new FlowLayout());
a = new JOptionPane("");
dugme1 = new JButton("zuta");
dugme2 = new JButton("plava");
dugme3 = new JButton("crvena");
dugmeBroja0 = new JButton("0");
dugmeBroja1 = new JButton("1");
dugmeBroja2 = new JButton("2");
dugmeBroja3 = new JButton("3");
dugmeBroja4 = new JButton("4");
dugmeBroja5 = new JButton("5");
dugmeBroja6 = new JButton("6");
dugmeBroja7 = new JButton("7");
dugmeBroja8 = new JButton("8");
dugmeBroja9 = new JButton("9");
dugmeZaPlus = new JButton("+");
dugmeZaMinus = new JButton("-");
dugmeZaPuta = new JButton("*");
dugmeZaPodeljeno = new JButton("/");
dugmeZaJednako = new JButton("=");
polje = new JTextField("", 20);
panel = new JPanel();
panel1 = new JPanel();
dugmeBroja0.setSize(50,50);
dugmeBroja1.setSize(50,50);
dugmeBroja2.setSize(50,50);
dugmeBroja3.setSize(50,50);
dugmeBroja4.setSize(50,50);
dugmeBroja5.setSize(50,50);
dugmeBroja6.setSize(50,50);
dugmeBroja7.setSize(50,50);
dugmeBroja8.setSize(50,50);
dugmeBroja9.setSize(50,50);
panel1.add(dugmeBroja0);
panel1.add(dugmeBroja1);
panel1.add(dugmeBroja2);
panel1.add(dugmeBroja3);
panel1.add(dugmeBroja4);
panel1.add(dugmeBroja5);
panel1.add(dugmeBroja6);
panel1.add(dugmeBroja7);
panel1.add(dugmeBroja8);
panel1.add(dugmeBroja9);
panel1.add(dugmeZaPlus);
panel1.add(dugmeZaMinus);
panel1.add(dugmeZaPuta);
panel1.add(dugmeZaPodeljeno);
panel1.add(dugmeZaJednako);
panel1.add(polje);
panel1.setLayout(new FlowLayout(50, 0 ,0));
FlowLayout mojLayout = new FlowLayout(FlowLayout.CENTER , 20 , 20);
panel.setLayout(mojLayout);
panel.add(dugme1);
panel.add(dugme2);
panel.add(dugme3);
this.setTitle("Kalkulator Koji Menja Boju Pozadine");
this.setSize(500,500);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.add(panel1);
this.add(panel);
dugme1.addActionListener(this);
dugme2.addActionListener(this);
dugme3.addActionListener(this);
polje.addActionListener(this);
panel.setBackground(Color.white);
panel1.setBackground(Color.white);
}
public static void main(String[] args) {
DugmiciKojiMenjajuBoju a = new DugmiciKojiMenjajuBoju();
a.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent arg0) {
if( arg0.getSource() == dugme1){
panel.setBackground(Color.yellow);
panel1.setBackground(Color.yellow);
getContentPane().setBackground(Color.yellow);
a.setSize(200,200);
a.showMessageDialog(this, "Klikcite dalje :D" ,"Postavili ste zutu",JOptionPane.INFORMATION_MESSAGE);
}
else if(arg0.getSource() == dugme2){
panel.setBackground(Color.blue);
panel1.setBackground(Color.blue);
getContentPane().setBackground(Color.blue);
a.setSize(200,200);
a.showMessageDialog(this, "Klikcite dalje :D","Postavili ste plavu", JOptionPane.INFORMATION_MESSAGE);
}
else if(arg0.getSource() == dugme3){
panel.setBackground(Color.red);
panel1.setBackground(Color.red);
getContentPane().setBackground(Color.red);
a.setSize(200,200);
a.showMessageDialog(this, "Klikcite dalje :D","Postavili ste crvenu",JOptionPane.INFORMATION_MESSAGE);
}
else if(arg0.getSource() == dugmeBroja0){
polje.setText("0");
System.out.println("blabla");
}
}
}
My button 0 is not working... so i cannot continue writing the code.

My button 0 is not working... so i cannot continue writing the code.
You didn't add an ActionListener to the button.
However, before just fixing that problem you should simplify your code an learn how to use loops to create multiple components with the same functionality. Here is an example that creates a single ActionListener and add it to each button:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class CalculatorPanel extends JPanel
{
private JTextField display;
public CalculatorPanel()
{
Action numberAction = new AbstractAction()
{
#Override
public void actionPerformed(ActionEvent e)
{
// display.setCaretPosition( display.getDocument().getLength() );
display.replaceSelection(e.getActionCommand());
}
};
setLayout( new BorderLayout() );
display = new JTextField();
display.setEditable( false );
display.setHorizontalAlignment(JTextField.RIGHT);
add(display, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout( new GridLayout(0, 5) );
add(buttonPanel, BorderLayout.CENTER);
for (int i = 0; i < 10; i++)
{
String text = String.valueOf(i);
JButton button = new JButton( text );
button.addActionListener( numberAction );
button.setBorder( new LineBorder(Color.BLACK) );
button.setPreferredSize( new Dimension(50, 50) );
buttonPanel.add( button );
}
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("Calculator Panel");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.add( new CalculatorPanel() );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
Also, don't use setSize() on your components. The layout manager is responsible for determining the size of a component.

You have never added ActionListener to that button, just to three color buttons and a JTextField polje

I think you didn't added this as the actionListener of dugmeBroja0:
you need this:
dugmeBroja0.addActionListener(this);

Related

How to prevent writing in both TextField when I am writing in one TextField using this keypad?

I'm beginner in java and i stucked writing simple project using eclipse. I added numbered Buttons and they should be showed in TextField when user click them.
But when i'm trying to check this they add every number to both TextField.
How i can prevent this?
See Picture show it better:
private JFrame frame;
private final JPanel panel = new JPanel();
private final JButton btnNewButton_1 = new JButton("1");
private final JButton btnNewButton_1_1 = new JButton("2");
private final JButton btnNewButton_1_2 = new JButton("3");
private final JButton btnNewButton_1_3 = new JButton("4");
private final JButton btnNewButton_1_1_1 = new JButton("5");
private final JButton btnNewButton_1_2_1 = new JButton("6");
private final JButton btnNewButton_1_4 = new JButton("7");
private final JButton btnNewButton_1_1_2 = new JButton("8");
private final JButton btnNewButton_1_2_2 = new JButton("9");
private final JButton btnNewButton_1_1_3 = new JButton("0");
private final JButton btnNewButton_1_2_4 = new JButton("Enter");
private final JButton btnNewButton_1_2_4_1 = new JButton("Cancel");
private final JButton btnNewButton_1_2_4_2 = new JButton("Clear");
private final JLabel lblNewLabel_4 = new JLabel("Welcome..!");
private final JLabel lblNewLabel_5 = new JLabel("Account Number:");
private final JLabel lblNewLabel_5_1 = new JLabel("PIN:");
private final JTextField textField = new JTextField();
private final JPasswordField passwordField = new JPasswordField();
private void initialize() {
frame = new JFrame();
frame.setBounds(150, 10, 1000, 650);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
frame.getContentPane().add(panel);
panel.setLayout(null);
btnNewButton_1.setFont(new Font("Tahoma", Font.BOLD, 23));
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String Enternumber1 = textField.getText()+btnNewButton_1.getText();
textField.setText(Enternumber1);
String Enternumber2 = passwordField.getText()+btnNewButton_1.getText();
passwordField.setText(Enternumber2);
}
Create a custom Action that extends from TextAction. The TextAction allows you to track the last text component that had focus. You can then apply your keypad logic to this component:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.text.*;
public class NumpadPanel extends JPanel
{
public NumpadPanel()
{
setLayout( new BorderLayout() );
JTextField textField1 = new JTextField(4);
JTextField textField2 = new JTextField(2);
JTextField textField3 = new JTextField(2);
JPanel panel = new JPanel();
panel.add( textField1 );
panel.add( textField2 );
panel.add( textField3 );
add(panel, BorderLayout.PAGE_START);
Action numberAction = new TextAction("")
{
#Override
public void actionPerformed(ActionEvent e)
{
JTextComponent textComponent = getFocusedComponent();
if (textComponent != null)
textComponent.replaceSelection(e.getActionCommand());
}
};
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout( new GridLayout(0, 5) );
add(buttonPanel, BorderLayout.CENTER);
for (int i = 0; i < 10; i++)
{
String text = String.valueOf(i);
JButton button = new JButton( text );
button.addActionListener( numberAction );
button.setMargin( new Insets(20, 20, 20, 20) );
button.setFocusable( false );
buttonPanel.add( button );
}
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("Numpad Panel");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.add( new NumpadPanel() );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}

Fails to display label and text field in Swing

I just started learning Swing with a simple code to create login form.
package swingbeginner;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class LoginForm {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel inputLabel;
private JPanel inputPanel;
private JPanel controlPanel;
private JLabel statusLabel;
public LoginForm() {
prepareGUI();
}
public static void main(String[] args) {
LoginForm loginForm = new LoginForm();
loginForm.loginProcess();
}
private void prepareGUI() {
mainFrame = new JFrame("Login");
mainFrame.setSize(600, 600);
mainFrame.setLayout(new FlowLayout());
headerLabel = new JLabel("",JLabel.CENTER );
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent) {
}
});
inputLabel = new JLabel();
inputLabel.setLayout(null);
inputPanel = new JPanel();
inputPanel.setLayout(null);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(inputLabel);
mainFrame.add(inputPanel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void loginProcess() {
headerLabel.setText("Please Login to Continue!");
JLabel usernameLabel = new JLabel("Username");
usernameLabel.setBounds(10,20,80,25);
JLabel passwordLabel = new JLabel("Password");
passwordLabel.setBounds(10, 20, 80, 25);
JTextField usernameTextbox = new JTextField();
usernameTextbox.setBounds(100,20,165,25);
JPasswordField passwordTextbox = new JPasswordField();
passwordTextbox.setBounds(100,20,165,25);
JButton loginButton = new JButton("Login");
JButton cancelButton = new JButton("Cancel");
loginButton.setActionCommand("Login");
cancelButton.setActionCommand("Cancel");
loginButton.addActionListener(new ButtonClickListener());
cancelButton.addActionListener(new ButtonClickListener());
inputLabel.add(usernameLabel);
inputPanel.add(usernameTextbox);
inputLabel.add(passwordLabel);
inputPanel.add(passwordTextbox);
controlPanel.add(loginButton);
controlPanel.add(cancelButton);
mainFrame.setVisible(true);
}
private class ButtonClickListener implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
String command = actionEvent.getActionCommand();
if(command.equals("Login")) {
statusLabel.setText("Logging In");
}
else if(command.equals("Cancel")) {
statusLabel.setText("Login Cancelled");
}
}
}
}
My code displays header along with Login and Cancel button. But the Labels/Text field (Username and Password) are not been displayed in the panel.
Where am I going wrong?
since everyone is missing the fact of the null layout ill create an answer myself.
inputPanel.setLayout(null);
if you add components to this, you will have to specify the position or you simply use a layoutmanager like BorderLayout or FlowLayout.
inputPanel.setLayout(new FlowLayout());
if you use this you will be able to simply add the components to the JPanel. Also as stated in the other answers, don't add JLabels to other JLables, because the most top one will override the others. With that being said a solution code which should work would looks like this:
public class LoginForm {
private JFrame mainFrame;
private JLabel headerLabel;
private JPanel inputPanel;
private JPanel controlPanel;
private JLabel statusLabel;
public LoginForm() {
prepareGUI();
}
public static void main(String[] args) {
LoginForm loginForm = new LoginForm();
loginForm.loginProcess();
}
private void prepareGUI() {
mainFrame = new JFrame("Login");
mainFrame.setSize(600, 600);
mainFrame.setLayout(new FlowLayout());
headerLabel = new JLabel("",JLabel.CENTER );
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent) {
}
});
//changes here
inputPanel = new JPanel();
inputPanel.setLayout(new FlowLayout());
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(inputLabel);
mainFrame.add(inputPanel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void loginProcess() {
headerLabel.setText("Please Login to Continue!");
JLabel usernameLabel = new JLabel("Username");
usernameLabel.setBounds(10,20,80,25);
JLabel passwordLabel = new JLabel("Password");
passwordLabel.setBounds(10, 20, 80, 25);
JTextField usernameTextbox = new JTextField();
usernameTextbox.setBounds(100,20,165,25);
JPasswordField passwordTextbox = new JPasswordField();
passwordTextbox.setBounds(100,20,165,25);
JButton loginButton = new JButton("Login");
JButton cancelButton = new JButton("Cancel");
loginButton.setActionCommand("Login");
cancelButton.setActionCommand("Cancel");
loginButton.addActionListener(new ButtonClickListener());
cancelButton.addActionListener(new ButtonClickListener());
inputPanel.add(usernameLabel); //changes here
inputPanel.add(usernameTextbox);
inputPanel.add(passwordLabel); //changes here
inputPanel.add(passwordTextbox);
controlPanel.add(loginButton);
controlPanel.add(cancelButton);
mainFrame.setVisible(true);
}
private class ButtonClickListener implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
String command = actionEvent.getActionCommand();
if(command.equals("Login")) {
statusLabel.setText("Logging In");
}
else if(command.equals("Cancel")) {
statusLabel.setText("Login Cancelled");
}
}
}
}
Here is your solution:
package swingbeginner;
public class LoginForm {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel inputLabel;
private JPanel inputPanel;
private JPanel controlPanel;
private JLabel statusLabel;
public LoginForm() {
prepareGUI();
}
public static void main(String[] args) {
LoginForm loginForm = new LoginForm();
loginForm.loginProcess();
}
private void prepareGUI() {
mainFrame = new JFrame("Login");
mainFrame.setSize(600, 600);
mainFrame.setLayout(new BorderLayout());
headerLabel = new JLabel("header", JLabel.CENTER);
statusLabel = new JLabel("status", JLabel.CENTER);
statusLabel.setSize(350, 100);
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent) {
}
});
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 100, 100));
mainFrame.add(headerLabel, BorderLayout.NORTH);
mainFrame.add(controlPanel, BorderLayout.CENTER);
mainFrame.add(statusLabel, BorderLayout.SOUTH);
mainFrame.setVisible(true);
}
private void loginProcess() {
headerLabel.setText("Please Login to Continue!");
JLabel usernameLabel = new JLabel("Username");
usernameLabel.setBounds(10, 20, 80, 25);
JLabel passwordLabel = new JLabel("Password");
passwordLabel.setBounds(10, 20, 80, 25);
JTextField usernameTextbox = new JTextField(20);
usernameTextbox.setBounds(100, 20, 165, 25);
JPasswordField passwordTextbox = new JPasswordField(20);
passwordTextbox.setBounds(100, 20, 165, 25);
JButton loginButton = new JButton("Login");
JButton cancelButton = new JButton("Cancel");
loginButton.setActionCommand("Login");
cancelButton.setActionCommand("Cancel");
loginButton.addActionListener(new ButtonClickListener());
cancelButton.addActionListener(new ButtonClickListener());
controlPanel.add(usernameLabel);
controlPanel.add(usernameTextbox);
controlPanel.add(passwordLabel);
controlPanel.add(passwordTextbox);
controlPanel.add(loginButton);
controlPanel.add(cancelButton);
mainFrame.setVisible(true);
}
private class ButtonClickListener implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
String command = actionEvent.getActionCommand();
if (command.equals("Login")) {
statusLabel.setText("Logging In");
}
else if (command.equals("Cancel")) {
statusLabel.setText("Login Cancelled");
}
}
}
}
You are adding usernameLabel and passwordLabel onto another label inputLabel. [When stacking labels, the topmost label will overwrite and those labels will disappear.] (JLabel on top of another JLabel)! Why don't you add all the labels and fields directly to the mainFrame i.e. the JFrame object?
You are adding Labels/Textfield(Username and Password) to inputLabel which is an instance of JLabel which is not of type of a container.
Change
inputLabel.add(usernameLabel);
inputPanel.add(usernameTextbox);
inputLabel.add(passwordLabel);
inputPanel.add(passwordTextbox);
to
controlPanel.add(usernameLabel);
controlPanel.add(usernameTextbox);
controlPanel.add(passwordLabel);
controlPanel.add(passwordTextbox);
Also give JTextField a default size, so change
JTextField usernameTextbox = new JTextField();
JPasswordField passwordTextbox = new JPasswordField();
to
JTextField usernameTextbox = new JTextField(20);
JPasswordField passwordTextbox = new JPasswordField(20);
Or you can change the type of inputLabel variable to JPanel and set it a layout like FlowLayout.
In this case no need to use setBounds method on components.
Note: that you use the same bounds for multiple components which will make them one on top of another.

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

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

How to position JButton in a JFrame window?

My program is about a supermarket. I want to position the JButton 'b1' just below JLabel 'l1' and also below JTextField 'jt1'. I want the JButton 'b1' to also be in the centre but below 'l1' and 'jt1'. Below is the delivery() method of my program:
public static void delivery()
{
final JFrame f1 = new JFrame("Name");
f1.setVisible(true);
f1.setSize(600,200);
f1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f1.setLocation(700,450);
JPanel p1 = new JPanel();
final JLabel l1 = new JLabel("Enter your name: ");
final JTextField jt1 = new JTextField(20);
JButton b1 = new JButton("Ok");
b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
input1 = jt1.getText();
f1.setVisible(false);
}
});
p1.add(b1);
p1.add(l1);
p1.add(jt1);
f1.add(p1);
final JFrame f2 = new JFrame("Address");
f2.setVisible(true);
f2.setSize(600,200);
f2.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f2.setLocation(700,450);
JPanel p2 = new JPanel();
final JLabel l2 = new JLabel("Enter your address: ");
final JTextField jt2 = new JTextField(20);
JButton b2 = new JButton("Ok");
b2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
input2 = jt2.getText();
f2.setVisible(false);
}
});
p2.add(b2);
p2.add(l2);
p2.add(jt2);
f2.add(p2);
}
}
You can use multiple JPanels to get close to what you want:
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MyGui {
public static void delivery()
{
JFrame f1 = new JFrame("Name");
f1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f1.setBounds(200, 100, 500, 300);
Container cpane = f1.getContentPane();
JPanel p1 = new JPanel();
p1.setLayout(new BoxLayout(p1, BoxLayout.LINE_AXIS)); //Horizontal
JLabel l1 = new JLabel("Enter your name: ");
JTextField jt1 = new JTextField(20);
jt1.setMaximumSize( jt1.getPreferredSize() );
p1.add(l1);
p1.add(jt1);
JPanel p2 = new JPanel();
p2.setLayout(new BoxLayout(p2, BoxLayout.PAGE_AXIS)); //Vertical
p2.add(p1);
JButton b1 = new JButton("Ok");
p2.add(b1);
cpane.add(p2);
f1.setVisible(true);
}
}
public class SwingProg {
private static void createAndShowGUI() {
MyGui.delivery();
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Use the GridBagLayout Class. It's for custom designing using Constraints.

CardLayout issue

I have a card layout, first card is a menu.
I Select the second card, and carry out some action. We'll say add a JTextField by clicking a button. If I return to the menu card, and then go back to the second card, that JTextField I added the first time will still be there.
I want the second card to be as I originally constructed it each time I access it, with the buttons, but without the Textfield.
Make sure the panel you're trying to reset has code that takes it back to its "as it was originally constructed" state. Then, when you process the whatever event that causes you to change cards, call that code to restore the original state before showing the card.
Here is the final sorted out version, to remove the card, after doing changes to it, have a look, use the revalidate() and repaint() thingy as usual :-)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ApplicationBase extends JFrame
{
private JPanel centerPanel;
private int topPanelCount = 0;
private String[] cardNames = {
"Login Window",
"TextField Creation"
};
private TextFieldCreation tfc;
private LoginWindow lw;
private JButton nextButton;
private JButton removeButton;
private ActionListener actionListener = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
if (ae.getSource() == nextButton)
{
CardLayout cardLayout = (CardLayout) centerPanel.getLayout();
cardLayout.next(centerPanel);
}
else if (ae.getSource() == removeButton)
{
centerPanel.remove(tfc);
centerPanel.revalidate();
centerPanel.repaint();
tfc = new TextFieldCreation();
tfc.createAndDisplayGUI();
centerPanel.add(tfc, cardNames[1]);
}
}
};
private void createAndDisplayGUI()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
centerPanel = new JPanel();
centerPanel.setLayout(new CardLayout());
lw = new LoginWindow();
lw.createAndDisplayGUI();
centerPanel.add(lw, cardNames[0]);
tfc = new TextFieldCreation();
tfc.createAndDisplayGUI();
centerPanel.add(tfc, cardNames[1]);
JPanel bottomPanel = new JPanel();
removeButton = new JButton("REMOVE");
nextButton = new JButton("NEXT");
removeButton.addActionListener(actionListener);
nextButton.addActionListener(actionListener);
bottomPanel.add(removeButton);
bottomPanel.add(nextButton);
add(centerPanel, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
pack();
setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new ApplicationBase().createAndDisplayGUI();
}
});
}
}
class TextFieldCreation extends JPanel
{
private JButton createButton;
private int count = 0;
public void createAndDisplayGUI()
{
final JPanel topPanel = new JPanel();
topPanel.setLayout(new GridLayout(0, 2));
createButton = new JButton("CREATE TEXTFIELD");
createButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
JTextField tfield = new JTextField();
tfield.setActionCommand("JTextField" + count);
topPanel.add(tfield);
topPanel.revalidate();
topPanel.repaint();
}
});
setLayout(new BorderLayout(5, 5));
add(topPanel, BorderLayout.CENTER);
add(createButton, BorderLayout.PAGE_END);
}
}
class LoginWindow extends JPanel
{
private JPanel topPanel;
private JPanel middlePanel;
private JPanel bottomPanel;
public void createAndDisplayGUI()
{
topPanel = new JPanel();
JLabel userLabel = new JLabel("USERNAME : ", JLabel.CENTER);
JTextField userField = new JTextField(20);
topPanel.add(userLabel);
topPanel.add(userField);
middlePanel = new JPanel();
JLabel passLabel = new JLabel("PASSWORD : ", JLabel.CENTER);
JTextField passField = new JTextField(20);
middlePanel.add(passLabel);
middlePanel.add(passField);
bottomPanel = new JPanel();
JButton loginButton = new JButton("LGOIN");
bottomPanel.add(loginButton);
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
add(topPanel);
add(middlePanel);
add(bottomPanel);
}
}
If you just wanted to remove the Latest Edit made to the card, try this code :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ApplicationBase extends JFrame
{
private JPanel centerPanel;
private int topPanelCount = 0;
private String[] cardNames = {
"Login Window",
"TextField Creation"
};
private TextFieldCreation tfc;
private LoginWindow lw;
private JButton nextButton;
private JButton removeButton;
private ActionListener actionListener = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
if (ae.getSource() == nextButton)
{
CardLayout cardLayout = (CardLayout) centerPanel.getLayout();
cardLayout.next(centerPanel);
}
else if (ae.getSource() == removeButton)
{
TextFieldCreation.topPanel.remove(TextFieldCreation.tfield);
TextFieldCreation.topPanel.revalidate();
TextFieldCreation.topPanel.repaint();
}
}
};
private void createAndDisplayGUI()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
centerPanel = new JPanel();
centerPanel.setLayout(new CardLayout());
lw = new LoginWindow();
lw.createAndDisplayGUI();
centerPanel.add(lw, cardNames[0]);
tfc = new TextFieldCreation();
tfc.createAndDisplayGUI();
centerPanel.add(tfc, cardNames[1]);
JPanel bottomPanel = new JPanel();
removeButton = new JButton("REMOVE");
nextButton = new JButton("NEXT");
removeButton.addActionListener(actionListener);
nextButton.addActionListener(actionListener);
bottomPanel.add(removeButton);
bottomPanel.add(nextButton);
add(centerPanel, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
pack();
setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new ApplicationBase().createAndDisplayGUI();
}
});
}
}
class TextFieldCreation extends JPanel
{
private JButton createButton;
private int count = 0;
public static JTextField tfield;
public static JPanel topPanel;
public void createAndDisplayGUI()
{
topPanel = new JPanel();
topPanel.setLayout(new GridLayout(0, 2));
createButton = new JButton("CREATE TEXTFIELD");
createButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
tfield = new JTextField();
tfield.setActionCommand("JTextField" + count);
topPanel.add(tfield);
topPanel.revalidate();
topPanel.repaint();
}
});
setLayout(new BorderLayout(5, 5));
add(topPanel, BorderLayout.CENTER);
add(createButton, BorderLayout.PAGE_END);
}
}
class LoginWindow extends JPanel
{
private JPanel topPanel;
private JPanel middlePanel;
private JPanel bottomPanel;
public void createAndDisplayGUI()
{
topPanel = new JPanel();
JLabel userLabel = new JLabel("USERNAME : ", JLabel.CENTER);
JTextField userField = new JTextField(20);
topPanel.add(userLabel);
topPanel.add(userField);
middlePanel = new JPanel();
JLabel passLabel = new JLabel("PASSWORD : ", JLabel.CENTER);
JTextField passField = new JTextField(20);
middlePanel.add(passLabel);
middlePanel.add(passField);
bottomPanel = new JPanel();
JButton loginButton = new JButton("LGOIN");
bottomPanel.add(loginButton);
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
add(topPanel);
add(middlePanel);
add(bottomPanel);
}
}

Categories

Resources