How to get a JFrame in Swing - java

I'm working on a simple app and I need to access JFrame created when initializing a program from different places where it's not always possible to access it directly (e.g. contentPane is empty so SwingUtilities.getWindowAncestor(Component) won't work). Is there any other way to do this? For example, this is a class resposinble for initialization:
public final class Application{
public static void start(){
//Empty screen with menu
SwingUtilities.invokeAndWait(() -> {
JFrame frame = new JFrame("Main frame");
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Start");
menuBar.add(menu);
frame.setJMenuBar(menuBar);
});
}
}
And I need to use it from some other places, e.g.
JPanel panel = new JPanel();
//initialize the panel
//push it to the content pane of Main frame
So, in order to share the main frame I tend to wrap it in a singleton class and then provide a static method. Maybe there is another way of doing that?

You can store it in a static reference:
public final class Application{
static JFrame mainFrame; //static attribute
public static void start(){
//Empty screen with menu
SwingUtilities.invokeAndWait(() -> {
JFrame frame = new JFrame("Main frame");
mainFrame = frame; //Storing in static attribute
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Start");
menuBar.add(menu);
frame.setJMenuBar(menuBar);
});
}
}
An call it as follows:
JPanel panel = new JPanel();
//initialize the panel
Application.mainFrame.getContentPane().add(panel);
This is a ugly solution maybe you can review Design Patterns for a better solution:
http://www.tutorialspoint.com/design_pattern/

Related

How to add a panel class to my frame in main class

I am fairly new to oo, I have created a class which is most of the interface of my program, I have put it all together in a class. I then want to add my Panel class to my main class so my panels are attached to my Frame:
This is what I have tried, I am not receiving any errors, when I run my program but the panels are not displaying:
Panel Class:
public class PanelDriver extends JPanel {
public JPanel p1, myg;
public PanelDriver() {
JPanel p1 = new JPanel();
p1.setBackground(Color.CYAN);
// Graphicsa myg = new Graphicsa();
JTextArea txt = new JTextArea(5,20);
txt.setText("test");
p1.add(txt);
}
}
Main class:
public class GraphicMain {
public static void main(String[] args) {
JFrame frame = new JFrame("My Program");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 600);
PanelDriver panels = new PanelDriver();
frame.getContentPane().add(panels);
GridLayout layout = new GridLayout(1,2);
}
you need a super call (because you extend JPanel you don't need to create a new one) and a layout in you Panel class like this:
public class CustomerTest extends JPanel {
public CustomerTest() {
super();
this.setBackground(Color.CYAN);
this.setLayout(new BorderLayout());
JTextArea txt = new JTextArea();
txt.setText("test");
this.add(txt);
this.setVisible(true);
}
}
and then in your main class use this, to set the frame visible and display the content. you have to set the layout for the frame after you created it:
JFrame frame = new JFrame("My Program");
GridLayout layout = new GridLayout(1, 2);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 600);
CustomerTest panels = new CustomerTest();
frame.getContentPane().setLayout(layout);;
frame.add(panels);
frame.setVisible(true);
Your PanelDriver class creates a p1 JPanel, but doesn't add it to anything.
At least add it to the PanelDriver itself :
this.add(p1);
Note that as your code is, the frame isn't even displaying, look at the answer by #XtremeBaumer to fix that part.

Create Scroll Bar for JFrame

Hi I am trying to create Scroll Bar for my JFrame. I created JPanel object and set components into JPanel. Then created a JScrollPane object for the panel. Then add the ScrollPane object to JFrame. I am not seeing any scrollbar. Also I am wondering if there is a option in JPanel that would resize the object inside Jpanel automatically according to the zoom level of the JPanel. Any help would be highly appreciated.
public class xmlottgui {
private JPanel Container;
private JFrame frmCreateXml;
private JTextField titlename;
private JLabel lbltitlename;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
xmlottgui window = new xmlottgui();
window.frmCreateXml.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public xmlottgui() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
Container = new JPanel();
Container.setLayout(null);
//JScrollPane pane=new JScrollPane(Container,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
frmCreateXml = new JFrame();
frmCreateXml.setTitle("Create XML");
frmCreateXml.setBounds(100, 100, 1000, 1200);
frmCreateXml.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmCreateXml.getContentPane().setLayout(null);
//Create MenuBar
JMenuBar menuBar = new JMenuBar();
Container.add(menuBar);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
JMenuItem mntmImportFromCsv = new JMenuItem("Import From Excel File");
//Add menu item Exit
JMenuItem mntmexit = new JMenuItem("Exit");
mntmexit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
mnFile.add(mntmexit);
showform();
JScrollPane pane=new JScrollPane(Container,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
pane.setLayout(null);
frmCreateXml.setContentPane(pane);
frmCreateXml.getContentPane().add(pane);
}
private void showform(){
titlename = new JTextField();
titlename.setBounds(164, 27, 749, 26);
Container.add(titlename);
titlename.setColumns(10);
lbltitlename = new JLabel("Title Name");
lbltitlename.setBackground(Color.GRAY);
lbltitlename.setBounds(22, 1000, 90, 16);
Container.add(lbltitlename);
}
This:
pane.setLayout(null);
Will completely disable your JScrollPane and prevent it from working as it will prevent the JScrollPane from displaying and manipulating its view port properly. JScrollPanes have there own very special layout manager, one you never want to muck with unless you are very clever and know what you're doing. As a general rule you should almost never use null layouts.
Also this is not correct:
frmCreateXml.setContentPane(pane);
frmCreateXml.getContentPane().add(pane);
You make pane the contentPane and then add pane to itself.
AND THIS is messing you up:
frmCreateXml.getContentPane().setLayout(null);
You will want to learn about and use the layout managers as it will make your life much easier.

How do I change the direction of JMenus in a JMenuBar

When I create a menu in java GUI by using JMenuBar it puts all JMenus from Left-to-right direction like this:
I want to change it to Right-to-left like this:
I want do this in an English OS, so suggestions of an Arabic or Right-to-Left solution aren't what I'm looking for.
You can use Component.applyComponentOrientation to change the orientation of the JMenuBar:
import javax.swing.*;
import java.awt.*;
public class R_L_MenuBar_Demo
{
public static void main(String[] args){
SwingUtilities.invokeLater(() -> createAndShowGUI());
}
private static void createAndShowGUI()
{
JMenuBar mb = new JMenuBar();
JMenuItem item_1 = new JMenuItem("First Item");
JMenu menu_2 = new JMenu("Second Menu");
JMenuItem item_3 = new JMenuItem("First Item in Second");
menu_2.add(item_3);
mb.add(item_1);
mb.add(menu_2);
//switch the orientation of the menubar to right to left
JButton btn_r_to_l = new JButton("Switch menubar to r_to_l");
btn_r_to_l.addActionListener(e -> {
mb.invalidate();
mb.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
mb.validate();
});
//switch the orientation of the menubar to left to right
JButton btn_l_to_r = new JButton("Switch menubar to l_to_r");
btn_l_to_r.addActionListener(e -> {
mb.invalidate();
mb.applyComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
mb.validate();
});
JFrame frame = new JFrame("R_L_MenuBar");
frame.setLayout(new FlowLayout());
frame.add(btn_r_to_l);
frame.add(btn_l_to_r);
frame.setJMenuBar(mb);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200 , 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
This will look like this:
The Default look (left to right)
And after switching to right-to-left:

How to display another class in a gui class java?

I'm trying to create an employee payroll system. Im creating a dropdown menu with JMenuItem Add Employee, and when you click that menu item then it will display another jframe below to enter in all the employee details. I have the add employee JFrame made and it runs perfectly. So i was wondering how do link the two? This is a part of it that might help
public static void main(String[] args) {
final JFrame frame = new JFrame("Payroll");
//create the Employee menu
JMenu employee = new JMenu("Employee");
employee.setMnemonic(KeyEvent.VK_E);
employee.add(new JMenuItem("Add"));
final JMenuItem add = new JMenuItem();
add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (add.isSelected()) {
JFrame f = new EmployeeTaxDetails1();
final JFrame frame = new JFrame();
f.setVisible(true);
frame.setVisible(false);
}
}});
JInternal Frame is a frame within a frame in java so you should probably use JInternalFrame
You can learn how to use it here.

How do I open new windows from menubars?

This is my code so far:
public static void main(String[] args){
JFrame frame = new JFrame("Breakout!");
frame.setLocation(300, 300);
//Making the menubar
JMenuBar mb = new JMenuBar();
frame.setJMenuBar(mb);
JMenu fileMenu = new JMenu("File");
mb.add(fileMenu);
JMenuItem newAction = new JMenuItem("About");
fileMenu.add(newAction);
newAction.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println("open new window here");
}
});
BreakoutCourt c = new BreakoutCourt();
frame.add(c);
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
I am making a Breakout game. I want to make an About window that displays information about the game (like, how to play it and so on). How would I go about doing that? Thank you for the help! I'm very new to Java Swing, so yeah.
You could do a simple one with the message type of JOptionPane:
JOptionPane.showMessageDialog(frame, "Breakout! v1.0");
(You'll need to make the frame final to do this, since it's being accessed from within the anonymous action listener).
For more control over what is displayed, and whether it should be modal or not, you could look at JDialog. There's an overview of using dialogs in Swing here: http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html.

Categories

Resources