I am trying to create a simple program where when I press a button, new text will appear but I have no idea how to do it (I imagine it is very simple).
The code I have right now is:
import java.awt.*;
public class ConsumptionGUI extends Frame
{
public ConsumptionGUI()
{
Frame fr = new Frame();
Button b1 = new Button ("Terminate Program");
Button b2 = new Button ("Start");
b1.setBounds(50,50,50,50);
b2.setBounds(50,50,50,50);
b1.addActionListener(e-> System.exit(0));
Label txt = new Label ("This is my first GUI");
//add to frame (after all buttons and text was added)
fr.add(b2);
fr.add(txt);
fr.add(b1);
fr.setSize(500,300);
fr.setTitle("Vehicles Information System");
fr.setLayout(new FlowLayout());
fr.setVisible(true);
} //end constructor
public static void main(String args[]){
ConsumptionGUI frame1= new ConsumptionGUI();
} //end main
Basically after this point I managed to create a frame with 2 buttons and some text in the middle.
I am really struggling to continue from here.
I need the program to first start by the press of a button then print some new text (something like "please enter your car's speed") and then save this information (to be used in a simple formula).
Afterwards the program needs to display the formula used and print what is the value calculated.
Can anyone please help?
Thanks
To get user input, you can implement a Dialog like in below code. You can use another similar dialog to show the formula and result as well.
import java.awt.*;
import java.awt.event.*;
public class ConsumptionGUI extends Frame
{
public ConsumptionGUI()
{
Frame fr = new Frame();
Button b1 = new Button("Terminate Program");
Button b2 = new Button("Start");
//b1.setBounds(50, 50, 50, 50); // Unnecessary
//b2.setBounds(50, 50, 50, 50); // Unnecessary
b1.addActionListener(e -> System.exit(0));
b2.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
InputDialog dialog = new InputDialog(fr);
dialog.setVisible(true);
System.out.println("User inputted speed = " + dialog.getSpeed());
}
});
Label txt = new Label("This is my first GUI");
//add to frame (after all buttons and text was added)
fr.add(b2);
fr.add(txt);
fr.add(b1);
fr.setSize(500, 300);
fr.setTitle("Vehicles Information System");
fr.setLayout(new FlowLayout());
fr.setVisible(true);
} //end constructor
public static void main(String args[])
{
ConsumptionGUI frame1 = new ConsumptionGUI();
} //end main
}
class InputDialog extends Dialog
{
private int speed;
InputDialog(Frame owner)
{
super(owner, "Input", true);
addWindowListener(new WindowAdapter()
{
#Override
public void windowClosing(WindowEvent e)
{
dispose();
}
});
TextField textField = new TextField(20);
Button okButton = new Button("OK");
okButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
String speedString = textField.getText();
speed = !speedString.isEmpty() ? Integer.parseInt(speedString) : 0;
dispose();
}
});
setLayout(new GridLayout(3, 1));
add(new Label("Please enter your car's speed"));
add(textField);
add(okButton);
pack();
}
int getSpeed()
{
return speed;
}
}
Related
I've made two buttons in frame .I want to know how to display different images on clicking different buttons?
is there another way out or i have to make panel?I am at beginner stage
package prac;
import java.awt.*;
import java.awt.event.*;
public class b extends Frame implements ActionListener{
String msg;
Button one,two;
b()
{ setSize(1000,500);
setVisible(true);
setLayout(new FlowLayout(FlowLayout.LEFT));
one=new Button("1");
two=new Button("2");
add(one);
add(two);
one.addActionListener(this);
two.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
msg=e.getActionCommand();
if(msg.equals("1"))
{
msg="Pressed 1";
}
else
msg="pressed 2";
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,100,300);
}
public static void main(String s[])
{
new b();
}
}
Use JLabel and change the icon when button is clicked.
Some points:
call setVisible(true) in the end after adding all the component.
use JFrame#pack() method that automatically fit the components in the JFrame based on component's preferred dimension instead of calling JFrame#setSize() method.
sample code:
final JLabel jlabel = new JLabel();
add(jlabel);
final Image image1 = ImageIO.read(new File("resources/1.png"));
final Image image2 = ImageIO.read(new File("resources/2.png"));
JPanel panel = new JPanel();
JButton jbutton1 = new JButton("Show first image");
jbutton1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
jlabel.setIcon(new ImageIcon(image1));
}
});
JButton jbutton2 = new JButton("Show second image");
jbutton2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
jlabel.setIcon(new ImageIcon(image2));
}
});
panel.add(jbutton1);
panel.add(jbutton2);
add(panel, BorderLayout.NORTH);
How do I make the next button go to the next Frame in this GUI? I need to have it where I can click next to display 20 more details:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class FilledFrameViewer
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
/*JButton button = new JButton*/
JButton nextButton = new JButton("NEXT");
JLabel label = new JLabel("Frame 1.");
JPanel panel = new JPanel();
panel.add(nextButton);
panel.add(label);
frame.add(panel);
final int FRAME_WIDTH = 300;
final int FRAME_HEIGHT = 100;
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setTitle("A frame with two components");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
If you want to hide or show the frame, you can use like this
JFrame f1 = new JFrame("Frame 1");
JFrame f2 = new JFrame("Frame 2");
to hide f1, call f1.setVisible(false);
to show f2, call f2.setVisible(true);
A bit unclear. Do you want to move a JButton to another JFrame? I don't think you can manage that without dynamic programming or such (I guess?).
You should look through a tutorial of the Swing components from Oracle http://docs.oracle.com/javase/tutorial/uiswing/
And see your comments. I agree having multiple JFrame is a bad habit.
Edit
Use the eventlistner (see other answer) and make it follow a switch case? Then there you can make it display like a dialog or change a JLable inside your JFrame?
Dialog tutorial here: http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html.
I think you should go with a lable and change it's text.
JButton nextButton = new JButton("Next");
nextButton.addActionListener(new ActionListner(
private int counter = 0;
public void actionPerformed(ActionEvent e) {
counter++;
switch(counter){
case 1: somelable.setText("Your text here");
};
}));
I wrote this on free hand but I guess something like this would work?
You have to edit the codes in your next frame...
Example for your NextFrame,
public class NextFrame
public static void main(String[] args)
{
private static FilledFrameViewer parentFrame; //ADD THIS FOR CONNECTION TO FIRST FRAME
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
NextFrame frame = new NextFrame(null); //CHANGES MADE HERE
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
public NextFrame(FilledFrameViewer f) { //CHANGES MADE HERE
this.parentFrame = f; //CHANGES MADE HERE
setTitle("Personal Assistant");
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);
Ah, Yes...and also you'll have to add some things in the Next button...
Example:
btnNext = new JButton();
btnNext.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
goNext();
{
private void goNext(){
NextFrame nextframe= new NextFrame(null);
nextframe.setVisible(true);
}
}
});
I am writing a very simple GUI, that contains 3 buttons, 2 labels, 2 text fields and one text area. Strangely, the result is unstable: when running the class the GUI appears with random number of the controls. I tried various layout managers, changing the order among the control - nothing.
Can someone help?
package finaltestrunner;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FinalTestGUI extends JFrame implements ActionListener
{
public Boolean startState = false;
JButton sofButton;
JButton startStopButton;
JButton exitButton;
JTextField loopCounts;
JTextField trSnField;
JTextArea resultField = null;
public FinalTestGUI()
{
// The constructor creates the panel and places the controls
super(); // Jframe constructor
JFrame trFrame = new JFrame();
trFrame.setSize(1000, 100);
trFrame.setVisible(true);
trFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
trFrame.setTitle("Test runner");
setFont(new Font("SansSerif", Font.PLAIN, 14));
// trFrame.setLayout(new FlowLayout());
JPanel trControlPanel = new JPanel();
trControlPanel.setSize(1000, 100);
trControlPanel.setLayout(new GridLayout(1,7));
exitButton = new JButton("Exit");
trControlPanel.add(exitButton);
startStopButton = new JButton("Run ");
trControlPanel.add(startStopButton);
JLabel loopsLabel = new JLabel ("Loops count: ");
trControlPanel.add(loopsLabel);
loopCounts = new JTextField (5);
trControlPanel.add(loopCounts);
sofButton = new JButton("SoF");
trControlPanel.add(sofButton);
JLabel testLabel = new JLabel ("serial Number: ");
trControlPanel.add(testLabel);
trSnField = new JTextField (5);
trControlPanel.add(trSnField);
JTextArea trResultField = new JTextArea (80, 10);
trFrame.add(trControlPanel);
// cpl.add(trResultField);
startStopButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed (ActionEvent trStartStopButton)
{
startState = !startState;
if (startState)
{
startStopButton.setText("Run ");
startStopButton.setForeground(Color.red);
}
else
{
startStopButton.setText("Stop");
startStopButton.setForeground(Color.green);
}
}
});
sofButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed (ActionEvent trSofButton)
{
loopCounts.setText("SOF\n");
}
});
exitButton.addActionListener (new ActionListener()
{
#Override
public void actionPerformed (ActionEvent trExitButton)
{
System.exit(0);
}
});
} // End of the constructor
#Override
public void actionPerformed (ActionEvent ae) { }
public void atpManager ()
{
String selectedAtp = "";
}
}
There are a couple of issues with this code:
You are already inheriting from JFrame, so you do not need to create yet another JFrame
You are showing your frame with setVisible(true) and afterwards adding components to it. This invalidates your layout, you need to revalidate afterwards (or move setVisible() to a position where you already added your components)
You are adding your components to the JFrame directly, but you need to use its contentpane. Starting with Java 1.5, the JFrame.add() methods automatically forward to the content pane. In earlier versions, it was necessary to retrieve the content pane with JFrame.getContentPane() to add the child components to the content pane.
Try this:
public FinalTestGUI() {
// The constructor creates the panel and places the controls
super(); // Jframe constructor
setSize(1000, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Test runner");
setFont(new Font("SansSerif", Font.PLAIN, 14));
setLayout(new FlowLayout());
JPanel trControlPanel = new JPanel();
trControlPanel.setSize(1000, 100);
trControlPanel.setLayout(new GridLayout(1,7));
exitButton = new JButton("Exit");
trControlPanel.add(exitButton);
startStopButton = new JButton("Run ");
trControlPanel.add(startStopButton);
JLabel loopsLabel = new JLabel ("Loops count: ");
trControlPanel.add(loopsLabel);
loopCounts = new JTextField (5);
trControlPanel.add(loopCounts);
sofButton = new JButton("SoF");
trControlPanel.add(sofButton);
JLabel testLabel = new JLabel ("serial Number: ");
trControlPanel.add(testLabel);
trSnField = new JTextField (5);
trControlPanel.add(trSnField);
JTextArea trResultField = new JTextArea (80, 10);
// getContentPane().add(trControlPanel); // pre 1.5
add(trControlPanel); // 1.5 and greater
setVisible(true);
}
I am wanting to get a return from a gui instance
The code i run to create the GUI:
JFrame frame = new JFrame();
frame.getContentPane().add(new ChatPopup());
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
My GUI (ChatPopUp code is as follows:
public class ChatPopup extends javax.swing.JPanel {
private JButton cancelButton;
private JTextField textFieldchatRoomName;
private JLabel jLabel1;
private JButton okButton;
public ChatPopup() {
super();
initGUI();
}
private void initGUI() {
try {
this.setPreferredSize(new java.awt.Dimension(294, 85));
{
jLabel1 = new JLabel();
this.add(jLabel1);
jLabel1.setText("Please enter the new chat room name:");
}
{
textFieldchatRoomName = new JTextField();
this.add(textFieldchatRoomName);
textFieldchatRoomName.setPreferredSize(new java.awt.Dimension(263, 22));
}
{
cancelButton = new JButton();
this.add(cancelButton);
cancelButton.setText("Cancel");
cancelButton.setPreferredSize(new java.awt.Dimension(84, 22));
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.out.println("Cancel PRESSED");
}
});
}
{
okButton = new JButton();
this.add(okButton);
okButton.setText("Ok");
okButton.setPreferredSize(new java.awt.Dimension(60, 22));
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.out.println("OK PRESSED");
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is a pretty simple GUI which has a text field and 2 buttons one "Ok" one "Chancel".
When i click "Ok" i want the textField value to be sent to the class where the GUI instance is originally run.
Any ideas how to do this??
The JPanel you posted should be added to a modal JDialog content pane. In the same class, you can provide some methods to return the values the user entered into the text fields.
In the original window, you open the dialog.
SomeDialog dialog = new SomeDialog(parent);
dialog.setVisible(true);
The code after setVisible() will only be executed after the modal dialog is closed. At this point you can call the methods I mentioned above for getting the text field values.
I've trouble with actionListener. I created own simple dialog, which has only two JButtons - Yes and No. When I click on button, actionListener doesn't respond.
This is my code:
private void showInfoNewUML() {
Dimension buttonsSize = new Dimension(60, 25);
Dimension programSize = new Dimension(1200, 700);
final JDialog dialogWindow = new JDialog(this, "Erase actual UML diagram"
+ " with his files", true);
JTextArea descDialogWindow = new JTextArea("Do you really erase actual\n"
+ "UML diagram with his files? ");
descDialogWindow.setEditable(false);
descDialogWindow.setBackground(new Color(220, 220, 220));
descDialogWindow.setBorder(null);
dialogWindow.getContentPane().setBackground(new Color(220, 220, 220));
dialogWindow.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
dialogWindow.setModal(true);
dialogWindow.setResizable(false);
dialogWindow.setLayout(new FlowLayout());
dialogWindow.setSize(310, 100);
dialogWindow.setLocation((int) programSize.getWidth() / 2,
(int) programSize.getHeight() / 2);
JButton buttonYes = new JButton("Yes");
JButton buttonNo = new JButton("No");
buttonYes.setPreferredSize(buttonsSize);
buttonNo.setPreferredSize(buttonsSize);
dialogWindow.add(descDialogWindow);
dialogWindow.add(buttonYes);
dialogWindow.add(buttonNo);
dialogWindow.setVisible(true);
buttonYes.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
buttonAnoActionPerformed(e);
}
private void buttonAnoActionPerformed(ActionEvent e) {
dialogWindow.setVisible(false);
}
});
buttonNo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
buttonNeActionPerformed(e);
}
private void buttonNeActionPerformed(ActionEvent e) {
dialogWindow.setVisible(false);
}
});
}
I would like close this dialog after I click on button. When I click to top right button with cross, dialog window closes.
Thank you for help with this trouble.
Try adding the ActionListeners before calling dialogWindow.setVisible(true);.
Your dialog is modal, and so showInfoNewUML will block at dialogWindow.setVisible(true); until after the dialog is closed, which is too late to register any useful listeners.