I have tried to make an app that it will open a menu with buttons [ insert search for example]. When a click a button an other iframe will be open for each button. But when it comes to click second time the button insert, iframe was crashed.
Even if after the insert, I click search, the iframe was crashed again.
The main frame:
public Exercise(){
frame1= new JFrame();
frame1.setSize(400, 100);
panel1 = new JPanel();
panel1.setVisible(true);
in= new JButton("insert");
in.setSize(50, 10);
in.setLocation(100, 100);
panel1.add(in);
s = new JButton("search");
s.setSize(50, 10);
s.setLocation(200, 200);
panel1.add(s);
s.setVisible(true);
frame1.add(panel1);
frame1.setVisible(true);
in.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
insert();
});
s.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
search()
});
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
The search function:
public void search(){
frame3= new JFrame();
frame3.setSize(300, 300);
panel3 = new JPanel();
panel3.setLayout( null );
/* and other textfields and labels */
JButton go= new JButton("go");
go.setSize(100, 100);
go.setBounds(10, 200,200,20);
panel3.add(go);
frame3.add(panel3);
frame3.setVisible(true);
go.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
////// .... ////
frame3.setVisible(false)
/* I have already tried:
frame3.dispose().
frame3.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);*/
});
}
The insert function
public void insert(){
frame2= new JFrame();
frame2.setSize(300, 300);
panel2 = new JPanel();
panel2.setLayout( null );
/* and other labels and textfields */
JButton save= new JButton("save");
save.setSize(100, 100);
save.setBounds(10, 200,200,20);
panel2.add(save);
frame2.add(panel2);
frame2.setVisible(true);
save.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
////// .... ////
frame2.setVisible(false)
});
}
What can I do?
Thank you in advance
It's not a good practice to create a new frame each time a button is pressed: you do that with search() and insert(). So the bset you can do is keep one frame for frame 2, one for frame 3 etc and make them visible/invisible as needed.
That is create the frames outside the functions search() insert() - maybe in the constructor.
Related
I'm having an issue that I've been trying to solve all day. I have two panels inside a frame and in one panel I've added components. The components, however, seem to have an equal hierarchy value as the panel and as such treat the Frame as the parent instead, ignoring where the panels are located. Basically the components are added to one panel but display on top of both across the whole frame. (Unfortunately I can't post a picture at this time, please up vote the question to allow me to if needed). What is causing this and how can I fix it?
The relevant code:
JFrame arranFrame = new JFrame("Edit Arrangement");
arranFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel grid = new JPanel();
JPanel tools = new JPanel();
grid.setSize(700, 600);
tools.setSize(200, 600);
JLabel widthLabel = new JLabel("Width");
JLabel depthLabel = new JLabel("Depth");
JLabel columnLabel = new JLabel("Columns");
final JTextField rowWidthInput = new JTextField(30);
final JTextField rowsInput = new JTextField(30);
final JTextField columnInput = new JTextField(30);
rowWidthInput.setSize(40, 30);
rowsInput.setSize(40, 30);
columnInput.setSize(40, 30);
rowWidthInput.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
chartWidth = Integer.parseInt(rowWidthInput.getText());
}
});
rowsInput.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
chartRows = Integer.parseInt(rowsInput.getText());
}
});
columnInput.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
chartColumns = Integer.parseInt(columnInput.getText());
}
});
//Enter button for grid modifying creation and setup
JButton enterButton = new JButton("Enter");
enterButton.setSize(180, 50);
enterButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
chartWidth = Integer.parseInt(rowWidthInput.getText());
chartRows = Integer.parseInt(rowsInput.getText());
chartColumns = Integer.parseInt(columnInput.getText());
}
});
//Save Arrangement button creation and setup
JButton saveButton = new JButton("Save Arrangement");
saveButton.setSize(180, 50);
saveButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
SaveArrangement(userDocuments + "\\TSA Seating Chart\\Arrangements\\Period" + period + ".txt");
}
});
tools.setBackground(Color.RED); //Temp for visualization where the panes are
tools.add(widthLabel);
tools.add(rowWidthInput);
tools.add(depthLabel);
tools.add(rowsInput);
tools.add(columnLabel);
tools.add(columnInput);
tools.add(enterButton);
tools.add(saveButton);
arranFrame.getContentPane().add(grid);
arranFrame.getContentPane().add(tools);
//Finalize the GUI
arranFrame.pack(); //Pack all the content together
arranFrame.setSize(900, 600); //Set the size of the window
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
arranFrame.setLocation(dim.width/2-arranFrame.getSize().width/2, dim.height/2-arranFrame.getSize().height/2);
arranFrame.setVisible(true); //Display the seatingFrame
I want to ask what function or another have to write so that every time I pressed the Start button (function:addbutton), the other button to exit (function:addButton2) to change its title to how many times I press the start?
class DroppingFrame extends JFrame {
public DroppingFrame() {
int clicked=0;
String b="a";
setSize(1400, 700);
setTitle("Dropping");
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
Container contentPane = getContentPane();
canvas = new JPanel();
contentPane.add(canvas, "Center");
JPanel p = new JPanel();
addButton(p, "Drop ball", clicked, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//addButton.setText(String.valueOf(++clicked));
Ball b = new Ball(canvas);
// if(b== new Ball(canvas)){
// clicked++;
// }
b.start();
}
});
addButton2(p, b, clicked, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
canvas.setVisible(false);
System.exit(0);
}
});
contentPane.add(p, "South");
}
public void addButton(Container c, String title, int i, ActionListener a) {
//i++;
//title = Integer.toString(i);
JButton b = new JButton(title);
c.add(b);
b.addActionListener(a);
}
public void addButton2(Container c, String title, int i, ActionListener a ) {
i++;
title = Integer.toString(i);
JButton b = new JButton(title);
c.add(b);
b.addActionListener(a);
}
private JPanel canvas;
}
My preference would be:
Make clicked a class field - that way you can access it and mutate it inside the event handler
Create a class field for a button
Refactor the addButton method so there is only one of them - this makes your code tidier:
Change the method return type to return the button created, then you decide if you store it or not from the caller. This just smells nicer.
The code looks like:
class DroppingFrame extends JFrame {
final JPanel canvas = new JPanel();
JButton button2;
int clicked = 0;
public DroppingFrame() {
setSize(1400, 700);
setTitle("Dropping");
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
Container contentPane = getContentPane();
contentPane.add(canvas, "Center");
JPanel p = new JPanel();
addButton(p, "Drop ball", clicked, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Ball b = new Ball(canvas);
b.start();
button2.setText(String.valueOf(++clicked));
}
});
button2 = addButton(p, String.valueOf(clicked), clicked, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
canvas.setVisible(false);
System.exit(0);
}
});
contentPane.add(p, "South");
}
public JButton addButton(Container c, String title, int i, ActionListener a) {
JButton b = new JButton(title);
c.add(b);
b.addActionListener(a);
return b;
}
}
It requires the reference of the second button so that start button can update its text.
Keep it simple:
Use setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); instead of adding WindowListener to close the window.
Use JFrame#dispose to close the JFrame programmatically.
Favor Composition over Inheritance It means if you are not overriding any logic/implementation of the existing class then don't extend it.
There is no meaning of creating separate method for adding each component. Either make the method generic or simply remove it.
Sample code:
public class DroppingFrame {
private int clicked = 0;
public DroppingFrame() {
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPane = frame.getContentPane();
JPanel p = new JPanel();
final JButton btn2 = new JButton(String.valueOf(clicked));
btn2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
frame.dispose();
}
});
JButton btn1 = new JButton("Drop ball");
btn1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
btn2.setText(String.valueOf(++clicked));
}
});
p.add(btn1);
p.add(btn2);
contentPane.add(p, BorderLayout.SOUTH);
frame.setVisible(true);
}
}
It's not correct.. addButton always creates a new button and its reference is lost.. you should make it class-scoped.
So make a class variable:
JButton button = new JButton();
Change your function:
public void addButton(Container c, String title, int i, ActionListener a) {
button.setText(title);
c.add(button);
button.addActionListener(a);
}
And also change your actionPerformed override:
public void actionPerformed(ActionEvent evt) {
button.setText(String.valueOf(++clicked));
....
});
I found this code online and modified it and it stopped working. I'm thinking it has something to do with when I added the Jpanel but what I am doing works best with a JPanel. How do I make it that the events in the action performed if statements work?
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import javax.swing.*;
public class GUI extends JFrame implements ActionListener {
static JPanel panel = new JPanel(new GridLayout(5, 5, 1, 1));
public GUI() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
//setSize(100, 100);
//setLocation(100, 100);
//Button 1
JButton button1 = new JButton("1");
button1.addActionListener(this);
panel.add(button1);
//Button 2
JButton button2 = new JButton("2");
button2.addActionListener(this);
panel.add(button2);
//Button 3
JButton button3 = new JButton("3");
button3.addActionListener(this);
panel.add(button3);
//Button 2
JButton button4 = new JButton("4");
button4.addActionListener(this);
panel.add(button4);
//Button 2
JButton button5 = new JButton("5");
button5.addActionListener(this);
panel.add(button5);
//Button 2
JButton button6 = new JButton("6");
button6.addActionListener(this);
panel.add(button6);
//Button 2
JButton button7 = new JButton("7");
button7.addActionListener(this);
panel.add(button7);
//Button 2
JButton button8 = new JButton("8");
button8.addActionListener(this);
panel.add(button8);
//Button 2
JButton button9 = new JButton("9");
button9.addActionListener(this);
panel.add(button9);
panel.setVisible(true);
}
public static void main(String[] args) {
new GUI();
JFrame f = new JFrame("Calc");
f.setContentPane(panel);
f.setSize(1000, 1000);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
ArrayList numbers = new ArrayList();
#Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("button1")) {
myMethod();
numbers.add(1);
System.out.println("1");
}
if (command.equals("button1")) {
numbers.add(2);
System.out.println("2");
}
}
public void myMethod() {
JOptionPane.showMessageDialog(this, "Hello, World!!!!!");
System.out.println("Hey");
}
}
You need to change the part actionPerformed as:
#Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("1")) {
myMethod();
numbers.add(1);
System.out.println("1");
}
if (command.equals("2")) {
numbers.add(2);
System.out.println("2");
}
}
Here, when a button is clicked, your e.getActionCommand() will give the constructor string. i.e. "1", "2" ,"3" and so on
reference
I put comments in code, but the first thing you should do is to read official tutorials. How to use Buttons
public class GUI /*extends JFrame implements ActionListener*/ {
//don't extend JFrame is you don't have too neither implement ActionListener in top-container classes that breaks single responsability principle
private JPanel panel = new JPanel(new GridLayout(5, 5, 1, 1)); // why static??
public JPanel getPanel(){
return panel;
}
public GUI() {
//i use anonymous classes for this, then you don't have to use if-else
//Button 1
JButton button1 = new JButton("1");
button1.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent evt){
myMethod();
numbers.add(1);
System.out.println("1");
}
});
panel.add(button1);
//Button 2
JButton button2 = new JButton("2");
button2.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent evt){
//put here logic for button2
}
});
panel.add(button2);
//and goo on with other buttons
//panel.setVisible(true); you don't need to call this!!
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GUI gui = new GUI();
frame.add(gui.getPanel());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private List<Integer> numbers = new ArrayList<>();//use generics!
public void myMethod() {
JOptionPane.showMessageDialog(this, "Hello, World!!!!!");
System.out.println("Hey");
}
}
The following is my code...the jButton would be added in the GuI method. I need a jbutton to add to the container and an eventlistener to enable the application to close when pushed.
public class BeetsWk1 extends JFrame{
public BeetsWk1(){
GuI();
}
public void GuI(){
FlowLayout layout = new FlowLayout();
layout.setAlignment(FlowLayout.CENTER);
Container container;
container = getContentPane();
container.setBackground(new Color(052,062,138));
container.setLayout(layout);
JLabel label = new JLabel();
label.setText ("Hello World" );
label.setSize( 500, 400);
label.setFont( new Font( "SanSerif", Font.PLAIN, 15) );
label.setHorizontalAlignment( JLabel.CENTER );
label.setForeground(Color.white);
container.add( label );
}
public static void main(String[] args) {
// TODO code application logic here
Dimension dimension = new Dimension(500, 500);
BeetsWk1 window = new BeetsWk1();
window.setVisible(true);
window.setSize(dimension);
window.setDefaultCloseOperation(window.EXIT_ON_CLOSE);
}
private Dimension Dimension(int i, int j) {
throw new UnsupportedOperationException("Not yet implemented");
}
}
What's stopping you?
JButton button = new JButton();
button.setText("Some text");
getContentPane().add(button);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
System.exit(0);
}
});
// 'this' represents the frame
// the 'button' is provided free
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
If you want to close your container then
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
jframe.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);//jframe is your JFrame Object
}
});
or if you want to close the total application then
system.exit(0);
I have a JFrame with three JButtons on it. I have set txtSearch (a JTextField component) to have the focus when JFrame loads. One of the buttons is set as the default button. This is my code:
private void formWindowOpened(java.awt.event.WindowEvent evt)
{
// btnRefresh.setMnemonic(KeyEvent.VK_R); // Even if this line
// is not commented, but
// still the event wouldn't fire.
this.getRootPane().setDefaultButton(btnRefresh);
}
When it loads, the button is just selected, but it did nothing when the Enter key was being pressed. How do I correctly implement it?
btnRefresh.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRefreshActionPerformed(evt);
}
});
private void btnRefreshActionPerformed(java.awt.event.ActionEvent evt) {
JOptionPane.showMessageDialog(this, "Pressed!");
// Other codes here (Replace by JOptionPane)
}
What component has focus when the JFrame comes up? I ask because some components "eat" the Enter key event. For example, a JEditorPane will do that.
Also, when you assign an ActionListener to JTextField, the ActionListener will be called instead of the DefaultButton for the root pane. You must choose either to have an ActionListener or a DefaultButton, but you can't have both fire for the same JTextField. I'm sure this applies to other components as well.
I don't see what you are doing incorrectly from what is posted. Here is a short example that works. Perhaps it will reveal something useful to you.
import java.awt.BorderLayout;
public class ExampleFrame extends JFrame
{
private JPanel m_contentPane;
private JTextField m_textField;
/**
* Launch the application.
*/
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
ExampleFrame frame = new ExampleFrame();
frame.setVisible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ExampleFrame()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
m_contentPane = new JPanel();
m_contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
m_contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(m_contentPane);
m_textField = new JTextField();
m_contentPane.add(m_textField, BorderLayout.NORTH);
m_textField.setColumns(10);
JButton btnNewButton = new JButton("Default");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(ExampleFrame.this, "Default.");
}
});
m_contentPane.add(btnNewButton, BorderLayout.CENTER);
JButton btnNewButton_1 = new JButton("Not default");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(ExampleFrame.this, "Not default.");
}
});
m_contentPane.add(btnNewButton_1, BorderLayout.WEST);
m_textField.requestFocus();
getRootPane().setDefaultButton(btnNewButton);
}
}