I have to write some Java code to create GUI and the idea is this. The user will input two numbers and then he will choose one of the radiobuttons. If he chooses "zgjidh", he should click a button that will do the calculations depending on what kind of calculation the button is for. "Fshij"button is kinda like reset to clear all field. If he chooses "dil" the window will close. For some reason it doesn't seem to work. Can someone help me?
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class Gui extends JFrame implements ActionListener{
JButton plus,minus,fshi;
JTextField vn1,vn2,vrez;
JLabel n1,n2,rezultati;
JRadioButton zgjidh,dil;
ButtonGroup grupi;
public Gui(){
setLayout(new FlowLayout());
JPanel veri=new JPanel();
veri.setLayout(new GridLayout(3,2));
n1=new JLabel("Jep numrin e 1");
veri.add(n1);
vn1=new JTextField(10);
veri.add(vn1);
n2=new JLabel("Jep numrin e 2");
veri.add(n2);
vn2=new JTextField(10);
veri.add(vn2);
rezultati=new JLabel("Rezultati");
veri.add(rezultati);
vrez=new JTextField(10);
veri.add(vrez);
add(veri,BorderLayout.NORTH);
JPanel qender=new JPanel();
qender.setLayout(new GridLayout(2,1));
zgjidh=new JRadioButton("Zgidh Veprimin");
zgjidh.addActionListener(this);
dil=new JRadioButton("Dil");
dil.addActionListener(this);
grupi=new ButtonGroup();
grupi.add(zgjidh);
grupi.add(dil);
qender.add(zgjidh);
qender.add(dil);
add(qender,BorderLayout.CENTER);
JPanel jug=new JPanel();
jug.setLayout(new GridLayout(1,3));
plus=new JButton("+");
plus.addActionListener(this);
jug.add(plus);
minus=new JButton("-");
minus.addActionListener(this);
jug.add(minus);
fshi=new JButton("Fshij");
fshi.addActionListener(this);
jug.add(fshi);
add(jug,BorderLayout.SOUTH);
}
public void actionPerformed (ActionEvent e){
double n1=Double.parseDouble(vn1.getText());
double n2=Double.parseDouble(vn2.getText());
if (e.getSource()==zgjidh) {
if (e.getSource()==plus) {
vrez.setText(""+(n1+n2));
}
else if (e.getSource()==minus) {
vrez.setText(""+(n1-n2));
}
else if (e.getSource()==fshi) {
vn1.setText("");
vn2.setText("");
vrez.setText("");
}
}
else if(e.getSource()==dil) {
System.exit(0);
}
}
public static void main(String args[]) {
Gui ob=new Gui();
ob.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ob.setSize(500,500);
ob.setVisible(true);
}
}
Was able to fix it. This is the modified code
public void actionPerformed(ActionEvent e){
double n1=Double.parseDouble(vn1.getText());
double n2=Double.parseDouble(vn2.getText());
if (zgjidh.isSelected()) {
if (e.getSource()==plus) {
vrez.setText(""+(n1+n2));
}
else if (e.getSource()==minus) {
vrez.setText(""+(n1-n2));
}
else if (e.getSource()==fshi) {
vn1.setText("");
vn2.setText("");
vrez.setText("");
}
}
else if(dil.isSelected()) {
System.exit(0);
}
}
Related
I am new to JAVA swing , where i develop two different JFrame if I click on button frame should move to another frame and previous frame should close by opening of next frame.
I click on button a next frame open but data inside frame is not displaying and previous frame is not closed on button . Please help to find the problem in code.
Frame 1:---------------------------------
package com.demo.test;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.GroupLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import com.demo.gui.TestjigWindow;
public class TestjigWindowCheck extends JFrame{
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
public TestjigWindowCheck() {
initUI();
}
private void initUI() {
mainFrame = new JFrame("Fuse Test jig");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(500,500);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
public void showEventDemo(){
//TestjigWindow frame1 = new TestjigWindow();
headerLabel.setText("Fuse Test Jig");
headerLabel.setFont(new Font( "Arial", Font.BOLD, 25));
headerLabel.setBackground(Color.green);
JButton startButton = new JButton("Start");
startButton.setActionCommand("Start");
JButton closeButton = new JButton("Close");
closeButton.setActionCommand("close");
startButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
try
{
if(e.getSource() == startButton)
{
TestjigWindow2 frame2 = new TestjigWindow2();
frame2.setVisible(true);
dispose();
}
else if(e.getSource() == closeButton)
{
System.exit(0);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
});
closeButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
try
{
System.exit(0);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
});
controlPanel.add(startButton);
controlPanel.add(closeButton);
mainFrame.setVisible(true);
}
public static void main(String[] args) {
TestjigWindowCheck test = new TestjigWindowCheck();
test.showEventDemo();
//test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Frame 2----------------------------------- .
package com.demo.test;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class TestjigWindow2 extends JFrame{
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
private JPanel controlPanel1;
public TestjigWindow2()
{
prepareGUI();
}
public static void main(String args[])
{
TestjigWindow2 test = new TestjigWindow2();
test.showRadioButton();
}
private void prepareGUI()
{
mainFrame = new JFrame("Fuse Test2 jig");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(500,500);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
public void showRadioButton()
{
headerLabel.setText("Fuse Mode");
final JRadioButton setting =new JRadioButton("Setting");
final JRadioButton testing =new JRadioButton("Testing");
setting.setBounds(75,50,100,30);
testing.setBounds(75,100,100,30);
setting.setMnemonic(KeyEvent.VK_S);
testing.setMnemonic(KeyEvent.VK_T);
ButtonGroup group = new ButtonGroup();
group.add(setting);
group.add(testing);
controlPanel.add(setting);
controlPanel.add(testing);
JButton button = new JButton("Next");
button.setActionCommand("Next");
controlPanel.add(button);
mainFrame.setVisible(true);
}
}
For this problem, I think it's a fairly simple solution, as Andrew commented, you don't need to keep creating JFrames, you can create your JFrame in your first program, and pass it to your second class through the constructor.
Why I think your program is closing is because you are calling dispose() after creating the new frame which might be destroying the components in your new frame.
You could take this approach, which uses only one frame creating in the opening class and carried over to the second class
For Example (using snipplets of your code):
Frame 1
//This is where you are moving to the second frame.
if(e.getSource() == startButton)
{
mainFrame.getContentPane().removeAll(); //removeAll() method wipes all components attached to the contentpane of the frame
//Frame can be reused when passed to second class
TestjigWindow2 frame2 = new TestjigWindow2(this.mainFrame);
}
Frame 2
//In your constructor you could have something like this
private JFrame mainFrame;
/*
* Other variables and constants go here
*
*/
public TestjigWindow2(JFrame mainFrame)
{
this.mainFrame = mainFrame;
prepareGUI();
}
And then in prepareGUI(), you would then be adding your components to your frame, without creating a new frame. With this, your first page will be closed, and the second frame will be open, without you having to creating mutiple JFrames.
You should just create a new Instance of TestjigWindow2 in the actionPerformed method within your first frame. Instead of adding actionPerformed on the startbutton and stopbutton seperately, implement ActionListener interface in your Frame1 class and just keep one method since you are checking for the source inside the method anyways.
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
try
{
if(e.getSource() == startButton)
{
TestjigWindow2 frame2 = new TestjigWindow2();
//frame2.setVisible(true); do this inside the frame2 preparegui method
dispose();
}
else if(e.getSource() == closeButton)
{
System.exit(0);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
});
Also the code will have a more generalized flow if you have the main method inside Frame1 and instantiate the Frame1 in it.
And you don't need to use setVisible inside the actionPerformed of Frame1.
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.
I'm working on a simple GUI. On Button press i want to increase/decrease a variable and update the corresponding JLabel.
class JFrameSetUp
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JFrameSetUp extends JFrame implements ActionListener {
private int RecHeight = 0;
private int RecWidth = 0;
//Here Buttons
JButton HeightIncrease = new JButton("+");
JButton HeightDecrease = new JButton("-");
JLabel height = new JLabel(Integer.toString(RecHeight));
JLabel width = new JLabel(Integer.toString(RecWidth));
GridLayout gridLayout = new GridLayout(2, 4);
public JFrameSetUp(){
}
public void addComponentsToPane(final Container pane){
//Create GridPanel and set Layout
JPanel grid = new JPanel();
grid.setLayout(gridLayout);
//Create buttondrawPanel and set Layout
JPanel buttondraw = new JPanel();
buttondraw.setLayout(new GridLayout(2, 0));
//Adding Components to GridPanel
//Adding Layouts to pane
pane.add(grid, BorderLayout.NORTH);
pane.add(new JSeparator(), BorderLayout.CENTER);
pane.add(buttondraw, BorderLayout.SOUTH);
}
#Override
public void actionPerformed(ActionEvent e) {
//Setting up ActionListener to Buttons
if (e.getSource() == this.HeightDecrease) {
RecHeight -= 1;
height.setText(Integer.toString(RecHeight));
} else if (e.getSource() == this.HeightIncrease) {
RecHeight += 1;
height.setText(Integer.toString(RecHeight));
}
}
}
Class with MainMethod
import javax.swing.JFrame;
public class Program {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrameSetUp frame = new JFrameSetUp();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
frame.addComponentsToPane(frame.getContentPane());
//Display the window.
frame.pack();
frame.setVisible(true);
}
}
I'm aware, that's kind a newbish question. I think I'm wrong with my Code Structure. Any help is appreciated.
Thanks in advance.
You never register any ActionListeners to the buttons...
HeightIncrease.addActionListener(this);
HeightDecrease.addActionListener(this);
You also never add the buttons to the GUI
buttondraw.add(HeightIncrease);
buttondraw.add(HeightDecrease);
You also never add the labels to the GUI either...
grid.add(height);
grid.add(width);
I reworked the code, because your example was messing with my mind, hope you don't mind...
It's conceptually the same idea, just done slightly more efficently
import java.awt.BorderLayout;
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.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private int recHeight = 0;
private int recWidth = 0;
//Here Buttons
JButton heightIncrease = new JButton("+");
JButton heightDecrease = new JButton("-");
JLabel height = new JLabel(Integer.toString(recHeight));
JLabel width = new JLabel(Integer.toString(recWidth));
GridLayout gridLayout = new GridLayout(2, 4);
public TestPane() {
setLayout(new BorderLayout());
//Create GridPanel and set Layout
JPanel grid = new JPanel();
grid.setLayout(gridLayout);
grid.add(height);
grid.add(width);
//Create buttondrawPanel and set Layout
JPanel buttondraw = new JPanel();
buttondraw.setLayout(new GridLayout(2, 0));
heightIncrease.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
recHeight += 1;
height.setText(Integer.toString(recHeight));
}
});
heightDecrease.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
recHeight -= 1;
height.setText(Integer.toString(recHeight));
}
});
buttondraw.add(heightIncrease);
buttondraw.add(heightDecrease);
//Adding Components to GridPanel
//Adding Layouts to pane
add(grid, BorderLayout.NORTH);
add(new JSeparator(), BorderLayout.CENTER);
add(buttondraw, BorderLayout.SOUTH);
}
}
}
I would encourage you to spend some time having a look at How to Use Buttons, Check Boxes, and Radio Buttons and How to Write an Action Listeners for more details
After changing the value call
frame.repaint();
Good to see you learning Java! A few things I should point out.
Firstly, your variable names are good, but they don't follow the Java naming convention. Even though it seems small, it's just good practice to follow.
Of course, your actual problem; the action listener you've implemented is on the JFrame. (See how you extend JFrame and implement ActionListener?) This ActionListener should be on the button. You'll can do this a few ways.
Method 1: By adding it inline with your code
JButton heightButton = new JButton("Increase Height");
heightButton.addActionListener(new ActionListener(){
#Override
public void run(){
//run method here
}
});
Method 2: Create a class which implements ActionListener
class ButtonListener implements ActionListener{
#Override
public void run(){
//actionListener code here
}
}
And then instantiate an object of this type and add it directly to your code.
ActionListner buttonListener = new ButtonListener(); //or ButtonListener buttonListener = new ButtonListener();
JButton heightButton = new JButton("Increase Height");
heightButton.addActionListener(buttonListener);
Of course, as in MadProgrammers answer, don't forget to add the labels and such to your JFrame or JPanel. Good luck learning Java!
I bet that your program just shows nothing, isn't it? That's because in addComponentsToPane method, you didn't add any component but empty JPanels. After the comment //Adding Components to GridPanel, you should:
buttondraw.add(HeightIncrease);
buttondraw.add(HeightDecrease);
grid.add(height);
grid.add(width);
Then, to listen to button event, you should also add :
HeightIncrease.addActionListener(this);
HeightDecrease.addActionListener(this);
"this" is because your frame JFrameSetUp implements ActionListener, so when either bootton is clicked the method actionPerformed is invoked.
As JLabel.setText method will repaint itself and consequently its component hierarchi is repainted as well, you haven't to do anything othr.
I'm trying to make a program that can add name and address.
I'm trying to use the GridLayout but there is no buttons that shows up.
What did I do wrong here?
Thanks
Hello. I'm trying to make a program that can add name and address.
I'm trying to use the GridLayout but there is no buttons that shows up.
What did I do wrong here?
Thanks
import java.awt.Color;
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;
public class AddressBookProgram extends JFrame {
public AddressBookProgram() {
super("Test");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setContentPane(new GridPanel());
setSize(300, 300);
setVisible(true);
}
private final class GridPanel extends JPanel {
private JPanel bookPanel;
private JPanel buttonPanel;
private JButton add;
private JButton delete;
private JButton search;
private JButton displayAll;
private JButton exit;
private ActionListener buttons = new ButtonListener();
private GridPanel() {
setLayout(new GridLayout(2, 3));
setBackground(Color.green);
bookPanel = new JPanel();
bookPanel.setBackground(Color.white);
buttonPanel = new JPanel();
buttonPanel.setBackground(Color.white);
add = new JButton("Add");
delete = new JButton("Delete");
search = new JButton("Search");
displayAll = new JButton("Display All");
exit = new JButton("Exit");
add.addActionListener(buttons);
delete.addActionListener(buttons);
search.addActionListener(buttons);
displayAll.addActionListener(buttons);
exit.addActionListener(buttons);
buttonPanel.add(add);
buttonPanel.add(delete);
buttonPanel.add(search);
buttonPanel.add(displayAll);
buttonPanel.add(exit);
}
private class ButtonListener implements ActionListener {
/**
* <p>Updates the watchLabel label when button is pushed.</p>
* #param event a button is pushed
*/
public void actionPerformed(ActionEvent event) {
if (event.getSource() == add) {
}
if (event.getSource() == delete) {
}
if (event.getSource() == search) {
}
if (event.getSource() == displayAll) {
}
if (event.getSource() == exit) {
}
}
}
}
public static void main(String[] args) {
new AddressBookProgram();
}
}
This is because you create buttonPanel but you don't add it. Just write this line:
add(buttonPanel);
This would make your code:
buttonPanel.add(add);
buttonPanel.add(delete);
buttonPanel.add(search);
buttonPanel.add(displayAll);
buttonPanel.add(exit);
add(buttonPanel);
By now, I already know my code is flawed. I just want to know why it's flawed. I want to activate the "webButton" so that when it gets clicked, it prints a message on the console that reads "This opens Mozilla Firefox."
package smartphone;
import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.*;
import java.util.Scanner;
public class Smartphone implements ActionListener {
public static void main(String[] args) {
{
{
JFrame container = new JFrame();
container.setLayout(new BorderLayout());
Scanner daniel = new Scanner(System.in);
JButton webButton = new JButton(new ImageIcon("Firefox.png"));
JButton phoButton = new JButton(new ImageIcon("Facebook.png"));
JButton texButton = new JButton(new ImageIcon("Phone.png"));
JButton setButton = new JButton(new ImageIcon("Settings.png"));
JButton smsButton = new JButton(new ImageIcon("sms.png"));
container.setTitle("Smartphone Interface!");
container.setSize(240,340);
container.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
container.add(setButton, BorderLayout.CENTER);
container.add(webButton, BorderLayout.SOUTH);
container.add(texButton, BorderLayout.NORTH);
container.add(phoButton, BorderLayout.EAST);
container.add(smsButton, BorderLayout.WEST);
container.setVisible(true);
webButton.addActionListener(instanceofSmartphone);
}
}
}
}
Do this.
webButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
}
});
If you want to use the ActionListener interface then, implement it in your Frame class and then replace that instanceOfSmartphone with
webButton.addActionListener(this);
And put this outside the method
public void actionPerformed(ActionEvent e) {
if(e.getSource() == webButton) {
}
}
You need to implement the actionPerformed method. An example follows.
public void actionPerformed(ActionEvent e) {
System.out.println("This method opens Mozilla Firefox.");
}
Additionally, you need to change how you add the action listener to the following.
webButton.addActionListener(this);
There are also a number of other issues. Here is a modified version of your code to get it working but far from perfect or what you will want in the end. I strongly recommend you walk through all of the tutorials in order at the below website. It doesn't get any easier than what they have. Also, if your not already using it, you should try Netbeans or some other IDE. It give you feedback that may help while you are starting out.
https://docs.oracle.com/javase/tutorial/
package smartphone;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.util.Scanner;
public class Smartphone extends Frame implements ActionListener {
static JButton webButton = new JButton(new ImageIcon("Firefox.png"));
static JButton phoButton = new JButton(new ImageIcon("Facebook.png"));
static JButton texButton = new JButton(new ImageIcon("Phone.png"));
static JButton setButton = new JButton(new ImageIcon("Settings.png"));
static JButton smsButton = new JButton(new ImageIcon("sms.png"));
Smartphone(){
webButton.addActionListener(this);
}
public static void main(String[] args) {
Smartphone container = new Smartphone();
container.setLayout(new BorderLayout());
Scanner daniel = new Scanner(System.in);
container.setTitle("Smartphone Interface!");
container.setSize(240, 340);
container.add(setButton, BorderLayout.CENTER);
container.add(webButton, BorderLayout.SOUTH);
container.add(texButton, BorderLayout.NORTH);
container.add(phoButton, BorderLayout.EAST);
container.add(smsButton, BorderLayout.WEST);
container.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("This opens a Firefox Webbrowser.");
}
}
You need to add an ActionListener to the buttons INSIDE of the constructor: buttonName.addActionListener(this);.
Then you need to create the following method:
public void actionPerformed(ActionEvent event) {
Object control = event.getSource();
if (control == buttonName) {
//Run code...
}
}