Java applet layout and action handler issue - java

In my application ,When the user clicks the JButton, display a JLabel that prompts the user to enter an integer, a JTextField into which the user can type the integer, and a secondJButton that contains the text Double me. When the user clicks the second button, the integer is doubled and the answer is displayed in the JTextField.
I am not able to display second button and text fields, when i click first button...please help
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class JDouble extends JApplet implements ActionListener {
private Container container = getContentPane();
/**
* The JButton.
*/
private JButton button = new JButton("Click me");
private JButton button2 = new JButton("Double me");
/**
* The JLabel.
*/
private JLabel label = new JLabel("Enter Integer");
private JTextField textfield = new JTextField(4);
private JTextField textfield2 = new JTextField(4);
public void init() {
// set the layout to FlowLayout
container.setLayout(new FlowLayout());
// register the 'this' action listener for the button
button.addActionListener(this);
container.add(button);
}
public void init1(){
container.setLayout(new FlowLayout());
container.add(textfield);
container.add(button2);
container.add(textfield2);
button2.addActionListener(this);
}
public void actionPerformed(ActionEvent actionEvent) {
container.add(label);
}
public void actionPerformed1(ActionEvent actionEvent) {
String me = textfield.getText();
int computation = Integer.parseInt(me);
computation = computation*2;
String changecomputation = Integer.toString(computation);
textfield2.setText(changecomputation);
container.remove(button);
container.add(label);
repaint();
validate();
}
}

Your init() method:
public void init() {
// set the layout to FlowLayout
container.setLayout(new FlowLayout());
// register the 'this' action listener for the button
button.addActionListener(this);
container.add(button);
}
We'll use this function to show the other fields when 'Click Me' is clicked...
private showInputFields(){
container.add(textfield);
button2.addActionListener(this);
container.add(button2);
container.add(textfield2);
}
Let's fix your action listener. If you want 'Click Me" button displayed on startup, init() takes care of that. When user clicks 'Click Me', we invoke showInputFields() to display the other components; we handle 'Double me' click using the same listener, we just check event source to handle appropriately...
private boolean inputFieldsDisplayed;
public void actionPerformed(ActionEvent actionEvent) {
if( actionEvent.getSource() == button && !inputFieldsDisplayed){
showInputFields();
inputFieldsDisplayed = true;
} else if ( actionEvent.getSource() == button2){
String me = textfield.getText();
int computation = Integer.parseInt(me);
computation = computation*2;
String changecomputation = Integer.toString(computation);
textfield2.setText(changecomputation);
}
validate();
repaint();
}

Related

JButton won't show text

This class represents the button panel of a UI I have created, the second JButton named 'btnNext' doesn't display text however the first JButton does, why is this?
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
public class ButtonPanel extends JPanel {
private MainPanel mainPanel;
// Buttons
private JButton btnRunTheAlgorithm = new JButton("Run the Algorithm");
public static JButton btnNext = new JButton("Next Step");
public ButtonPanel(MainPanel mainPanel) {
this.mainPanel = mainPanel;
this.setLayout(new FlowLayout());
this.add(btnRunTheAlgorithm);
this.add(btnNext);
this.btnRunTheAlgorithm.addActionListener(e -> {
Algorithm main = new Algorithm(mainPanel);
main.Run();
});
this.btnNext.setAction(new AbstractAction() {
public void actionPerformed(ActionEvent ae) {
synchronized (btnNext) {
btnNext.notify();
}
}
});
}
}
The buttons displays to the panel as on the image below:
Buttons:
I'm also not sure the AbstractAction works, so I suppose that could be the cause of the text not displaying but I have no idea why if that is the case.

Java Design Architecture

My question is
If I have a Jpanel having some JtextField and ComboBox. Another JPanel containing Buttons like Save, Update, Clear, Exit.
both the JPanel are added into JFrame and by the BoarderLayout.
If I write something in text field and press save button it will save the data into database. I know the connection code to database.
Problem is the connection between the Text Panel and Button Panel. If I made the JTextField public and JButtons Public I can access them in JFrame and Implements Listners to save data into Database, but I guess its not right practice.
Kindly guide me to the how to do it correctly.
Here is the Test Code.
Buttons Panel:
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
public class Buttons extends JPanel{
JButton btnSave, btnUpdate, btnClear, btnExit;
public Buttons(){
btnSave = new JButton("Save");
btnUpdate = new JButton("Update");
btnClear = new JButton("Clear");
btnExit = new JButton("Exit");
setLayout(new FlowLayout());
add(btnSave);
add(btnUpdate);
add(btnClear);
add(btnExit);
setSize(100,100);
}
}
TextPanel
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
*
* #author Aqeel
*/
public class textPanel extends JPanel{
JLabel ID , Name;
JTextField txtID, txtName;
GridBagConstraints gridBagConstraints;
public textPanel(){
ID = new JLabel("ID:");
Name = new JLabel("Name:");
txtID = new JTextField(10);
txtName = new JTextField(10);
setLayout(new GridBagLayout());
add(ID, new GridBagConstraints());
add(txtID, new GridBagConstraints());
gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
add(Name, gridBagConstraints);
gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
add(txtName, gridBagConstraints);
setSize(300,200);
}
}
Jframe
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.UnsupportedLookAndFeelException;
import org.openide.util.Exceptions;
/**
*
* #author Aqeel
*/
public class Jframe extends JFrame
{
textPanel textpanel;
Buttons buttons;
public Jframe() {
textpanel = new textPanel();
buttons = new Buttons();
setLayout(new BorderLayout());
add(textpanel, BorderLayout.CENTER);
add(buttons, BorderLayout.SOUTH);
setSize(400, 200);
buttons.btnSave.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e) {
String ID = textpanel.txtID.getText();
String Name = textpanel.txtName.getText();
System.out.println(ID);
System.out.println(Name);
}
});
buttons.btnExit.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
public static void main(String args[])
throws ClassNotFoundException, InstantiationException, UnsupportedLookAndFeelException
{
try {
for (javax.swing.UIManager.LookAndFeelInfo info :
javax.swing.UIManager.getInstalledLookAndFeels()
) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (IllegalAccessException ex) {
Exceptions.printStackTrace(ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Jframe().setVisible(true);
}
});
}
}
It's a good practice to isolate the components used in a specific implementation. You can focus on the role of each JPanel instead.
The TextPanel has to role of receiving the text input for Id and Name and the Buttons JPanel has the role of triggering specific actions.
A simple way to accomplish this would be to, instead of accessing directly the JButton and JTextField components (either making them public or by getters), create a getter in TextPanel class that returns a String for id and another String for name.
public class textPanel extends JPanel{
JLabel ID , Name;
JTextField txtID, txtName;
...
public String getId()
{
return txtID.getText();
}
public String getName()
{
return txtName.getText();
}
}
For the Buttons class, create an interface with methodos for each action.
public class Buttons extends JPanel{
private JButton btnSave, btnUpdate, btnClear, btnExit;
private ButtonsActions actionsListener;
public Buttons(ButtonsActions actionsListener){
this.actionsListener = actionsListener;
btnSave.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e) {
actionsListener.onSave();
}
});
...
}
public interface ButtonsActions {
public void onSave();
public void onUpdate();
public void onClear();
public void onExit();
}
}
The Jframe class would then be able to implement this interface and react to the actions when a button is clicked.
One of the reasons for isolating the implementation from each panel is that, let's say you later change the Buttons panel to have a JRadioButton listing all the action options and one apply button to trigger the selected action. Or if you change the TextPanel to offer o JComboBox instead of a simple JTextField. In any of those cases you would have to change all the places in your code that uses the Buttons or TextPanel classes to work with the new screen design.
use a methods to access or to modify (setters and getters ) attributes
as an exemple puts this method in Buttons class :
public JButton getbtnSave()
{
return this.btnSave;
}
this code is used for getting the btnSave with private access modifier.
and also use a method to get txtID (place this in the textPanel class)
public JTextField getTxtID()
{
return this.txtID;
}
public JTextField getTxtName()
{
return this.txtName;
}
so the code in the the JFrame will be
buttons.btnSave.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String ID = textpanel.getTxtID().getText();
String Name = textpanel.getTxtName().getText();
System.out.println(ID);
System.out.println(Name);
}
});

Custom JOptionPane / How to wait for a button in a frame to be clicked before returning a value to a method

I am trying to create a method which opens up a JFrame with some text and 4 JButtons. I need it to operate just like the methods in the JOptionPane class so that i can do things like
int i = JOptionPane.showConfirmDialog(...);
I want to be able to call the method and wait for one of the buttons to be clicked before returning a value.
This is what I have tried so far but obviously there are a couple of errors. Anybody know what i need to do to make this work and how to get around the errors. Here is the methood
private static String displaySetStatus(String text){
JButton jbtWin = new JButton("Win");
JButton jbtLose = new JButton("Lose");
JButton jbtCancelBet = new JButton("Cancel Bet");
JButton jbtSkip = new JButton("Skip");
JFrame f = new JFrame("Set Status");
f.add(new JLabel(text));
JPanel jpSouth = new JPanel();
jpSouth.add(jbtWin);
jpSouth.add(jbtLose);
jpSouth.add(jbtCancelBet);
jpSouth.add(jbtSkip);
f.add(jpSouth, "South");
f.setSize(200, 150);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
f.setVisible(true);
String status = "Empty";
ActionListener buttonListener = new SetStatusListener();
jbtWin.addActionListener(buttonListener);
jbtLose.addActionListener(buttonListener);
jbtCancelBet.addActionListener(buttonListener);
jbtSkip.addActionListener(buttonListener);
class SetStatusListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
status = ((JButton)e.getSource()).getText();
}
}
while(status.equals("Empty")){
//do nothing - wait until button is clicked
}
f.setVisible(false);
return status;
}
If you want JOptionPane functionality, which is in fact that of a modal dialog window, why not use a JOptionPane for this? Or if that won't work, use a modal JDialog window and not a JFrame. Your while (true) block is going to totally mess up your program, and modality is what you in fact want.
For example:
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
#SuppressWarnings("serial")
public class Foo1 extends JPanel {
private JTextField textField = new JTextField(10);
private JButton getStatusBtn = new JButton(new GetStatusAction("Get Status"));
public Foo1() {
textField.setFocusable(false);
add(new JLabel("Status:"));
add(textField);
add(getStatusBtn);
}
private class GetStatusAction extends AbstractAction {
public GetStatusAction(String name) {
super(name);
int mnemonic = name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
Component parentComponent = Foo1.this;
// this panel can hold any gui components that you desire
// here I simply give it a centered JLabel that displays some text
JPanel message = new JPanel(new GridBagLayout());
message.setPreferredSize(new Dimension(200, 100));
message.add(new JLabel("Some Text"));
String title = "Get Status";
int optionType = JOptionPane.OK_CANCEL_OPTION;
int messageType = JOptionPane.PLAIN_MESSAGE;
Icon icon = null;
String[] options = { "Win", "Lose" };
int initialValue = 0;
// create and show our JOptionPane, and get the information from it
int selection = JOptionPane.showOptionDialog(parentComponent,
message, title, optionType, messageType, icon, options,
initialValue);
// if the selection chosen was valid (win or lose pushed)
if (selection >= 0) {
// get the selection and use it
textField.setText(options[selection]);
}
}
}
private static void createAndShowGui() {
Foo1 mainPanel = new Foo1();
JFrame frame = new JFrame("Foo1");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Replacing a button with another button

import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class GUI extends JFrame {
private JButton reg;
private JButton custom;
private JButton custom2;
public GUI(){
super("Heartstone Arena Alpha 0.01");
setLayout(new FlowLayout());
reg = new JButton("Click Me");
add(reg);
Icon ACn = new ImageIcon(getClass().getResource("463.png"));
Icon ACg = new ImageIcon(getClass().getResource("463 (1).png"));
custom = new JButton("Custom", ACn);
custom.setRolloverIcon(ACg);
add(custom);
HandlerClass handler = new HandlerClass();
reg.addActionListener(handler);
custom.addActionListener(handler);
}
private class HandlerClass implements ActionListener {
public void actionPerformed(ActionEvent event) {
Icon An = new ImageIcon(getClass().getResource("Alexstrasza(303).png"));
custom2 = new JButton(" ", An);
custom2.setIcon(An);
custom2.setRolloverIcon(An);
}
}
Here is the code, what I want to do is have custom2 replace custom when it's clicked.
How would I go on about this?
I tried using custom = null and then add(custom2); but it doesn't show up
PS: Ignore the reg button
You need to add an ActionListener to your button, which should make the first button invisible and the second button visible. So it does not really get destroyed, you just dont show it.
Like this:
public class YourClassName implements ActionListener {
private JButton button1;
private JButton button2;
public YourClassName() {
// Code Snippet ----------------
button1 = new JButton("Click to replace");
button1.addActionListener(this);
// implement code for resizing and positioning here
button2 = new JButton("I am new here");
button2.setVisible(false);
// implement code for resizing and positioning here
// ...
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button1) {
button1.setVisible(false);
button2.setvisible(true);
}
}
}
Note: The code is made up out of my head, there may be a mistakes in it. Also, it is just a snippet, feel free to comment for full code

Java swing add Components from another Class

Im learning about Java Swing components and I want to do that when I push button, Java Swing would add label from another class into JFrame screen. Its just simple example for start.
I want to learn how to use and add swing components from another class.
There can be some stupid mistakes, but dont judge me, im new ^^
Frame class add button
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Frame extends JFrame{
private JButton btn;
private boolean regCompl = false;
public Frame(){
super("The title Macas");
setLayout(new FlowLayout());
btn = new JButton("Push for Registration");
btn.addActionListener(
new ActionListener(){
#Override
public void actionPerformed(ActionEvent event) {
regCompl = true;
}
}
);
add(btn);
if(regCompl == true){
RegComplete regObj = new RegComplete(this);
}
}// end of constructor
}
RegComplete Class add label to screen after button are pressed.
import javax.swing.JButton;
import javax.swing.JLabel;
public class RegComplete {
Frame frame;
private JLabel label;
public RegComplete(Frame fm){
this.frame = fm;
label = new JLabel("Hello world Mac4s");
fm.add(label);
}
}
You have to create Object inside the action Listener
btn = new JButton("Push for Registration");
btn.addActionListener(
new ActionListener(){
#Override
public void actionPerformed(ActionEvent event) {
RegComplete regObj = new RegComplete(Frame.this);
}
}
);

Categories