Ask AI on The Internet
Question: Write a java program that has a button that you can push
Sure, here is a simple example of a Java GUI program featuring a JButton using Swing. ```java import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JOptionPane; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class ButtonExample { public static void main(String[] args) { // Creating instance of JFrame JFrame frame = new JFrame("Button Example"); // Creating panel JPanel panel = new JPanel(); // Creating the JFrame settings frame.setSize(300, 200); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Creating button JButton button = new JButton("Click Me"); // Add action listener to button button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, "Button pressed!"); } }); // Add the button to the panel panel.add(button); // Add the panel to the frame frame.add(panel); // Setting the frame visibility to true frame.setVisible(true); } } ``` This program will create a frame with a button saying "Click Me". When the button is clicked, it will display a dialog box saying "Button pressed!".
when you want to find the number of days since 1/1/2001 import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Date; import javax.swing.*; public class DaysSince { public static void main(String[] args) { JFrame frame = new JFrame("Days Since 1/1/2001"); JButton btn = new JButton("Find Number of Days Since 1/1/2001"); btn.setBounds(150,100,200, 40); btn.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ Date startDate = new Date(2001,1,1); Date endDate = new Date(); long startTime = startDate.getTime(); long endTime = endDate.getTime(); long diffTime = endTime - startTime; long diffDays = diffTime / (1000 * 60 * 60 * 24); JOptionPane.showMessageDialog(frame, "Number of Days Since 1/1/2001: " + diffDays); } }); frame.add(btn); frame.setSize(500,500); frame.setLayout(null); frame.setVisible(true); } }
Feb. 8, 2023, 10:08 a.m.
A new large language model has been made available since this question was asked.
To generate an updated answer from the new model, click the button below.
Think your answer is better than the AI's? Post it below.
Other Most Relevant Posts:
Question Tags
If you want your question answered by an AI, click here.
Post your own comment: