Why does my JFrame randomly shrink when starting on Mac? - java

When working on my mac laptop I have recently noticed that my frame sometimes shrinks when the program starts. It is about 70-90% that it does shrink.
It works as expected on a PC but not on any mac I have tried it on. I have tried to narrow it down a bit (to the code below) but from here I can't find any reason for it not working. Some friends of mine think it might have something to do with mac's own window manager. I don't know.
I am fairly new to this, just FYI.
public class Worms extends JFrame{
public static void main(String[] args) {
new Worms();
}
private JButton startGame;
public Worms(){
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Container contentPane = this.getContentPane();
//if i change it so it uses a new dimension not "screenSize" it works
contentPane.setPreferredSize(screenSize);
JPanel menu = new JPanel();
startGame = new JButton("Start Game");
menu.add(startGame);//or if i remove this button it also works
this.add(menu);
this.pack();
this.setVisible(true);
}
}
It starts in "fullscreen" than it shrinks down to the left corner. If I drag it back to normal size it works as normal.

Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Container contentPane = this.getContentPane();
//if i change it so it uses a new dimension not "screenSize" it works
contentPane.setPreferredSize(screenSize);
The content pane should not have the preferred size set to the screen size. That is too large, and does not account for the frame decorations or 'chrome'.
Here is a different approach that should work reliably across systems. It sets the extended sate of the frame.
import java.awt.*;
import javax.swing.*;
public class Worms extends JFrame{
public static void main(String[] args) {
new Worms();
}
private JButton startGame;
public Worms(){
JPanel menu = new JPanel();
startGame = new JButton("Start Game");
menu.add(startGame);
this.add(menu);
this.pack();
// this should do what you seen to want
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
// this is just polite..
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setVisible(true);
}
}
Note that Swing / AWT GUIs should be created & updated on the Event Dispatch Thread. The example above does not add that, for the sake of simplicity.

Related

Java basic GUI blank

When I run this program it appears as an empty window until you fullscreen, then it can be resized as you like, why is it doing this/how do I stop it?
the program is very basic just a menubar and two panels split.
public class SplitPane {
public static void main(String[] args) {
window view = new window();
}
private static class window extends JFrame {
public window() {
this.setSize(1000, 750);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//menubar is here, must lower code quantity for stack
//panels
//graph half
JPanel graphRep = new JPanel();
//Background colour - graphRep.setBackground(Color.RED);
graphRep.setVisible(true);
String graphTitle = "Textual Representation.";
Border graphBorder = BorderFactory.createTitledBorder(graphTitle);
graphRep.setBorder(graphBorder);
//text half
JPanel textRep = new JPanel();
textRep.setVisible(true);
String textTitle = "Graphical Representation.";
Border textBorder = BorderFactory.createTitledBorder(textTitle);
textRep.setBorder(textBorder);
//splitpane
JSplitPane splitPane = new JSplitPane();
splitPane.setSize(600, 750);
splitPane.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
splitPane.setOneTouchExpandable(true);
splitPane.setDividerSize(10);
splitPane.setDividerLocation(250);
splitPane.setLeftComponent(graphRep);
splitPane.setRightComponent(textRep);
this.add(splitPane);
}
}
this.setVisible(true);
You are making the frame visible BEFORE you add components to the frame. The layout manager is never invoked so the size of all the components remains (0, 0) so there is nothing to paint.
The frame should be made visible AFTER all the components have been added to the frame.
And the code should be:
frame.pack();
frame.setVisible();
So each component is displayed at its proper size. Don't hardcode the size() because you don't know what the size of a users screen might be.

Why doesn't my button position properly on my JFrame no layout?

So I've got a JFrame which uses setLayout(null) so I can position my elements by hand.
However, when accessing the content pane and getting the size for the frame, it says its height is 1.0.
Does anyone know how I can fix this?
Here is the code:
import javax.swing.*;
import java.awt.*;
public class Launcher extends JFrame
{
public Launcher(String title) {
super(title);
setLayout(null);
pack();
setSize(new Dimension(LauncherUtil.LAUNCHER_WIDTH, LauncherUtil.LAUNCHER_HEIGHT));
setLocationRelativeTo(null);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
displayComponents();
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
Launcher launch = new Launcher(LauncherUtil.LAUNCHER_TITLE);
launch.setVisible(true);
}
});
}
private void displayComponents() {
Dimension size = getContentPane().getSize();
JButton launchButton = new JButton("Launch Game");
System.out.println(size.getHeight());
launchButton.setBounds(0, (int)size.getHeight() - 60, (int)size.getWidth(), 60);
add(launchButton);
}
}
may be if you try to get the screen size by using Toolkit would be work like you want
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
it brings you the screen size where java program is running. Hope it helps.
The content pane is a JPanel whose default size is 1x1px. Since you did not put any components into the content pane and have not set a preferred size for the panel, the content pane's size remains 1x1px.
One way to fix this is to call these three methods in the following order:
setLayout(null);
setPreferredSize(new Dimension(300, 400));
pack();
However, you should be using a layout manager instead of managing
the size and position of your components by hand.

Java GUI FullScreen window with smaller window inside

I am working on a Java desktop application. It uses MySQL database to store all data etc. I use swing for the GUI.
The GUI of this application is layed out as follows:
Main Window taking the entire screen size (with image in the
background)
Internal Window 800 x 600 centered within the Main
Window (that holds current content that can be switched between
using menu and/or event within the application.
LoginPanel.java:
import javax.swing.*;
import java.awt.*;
public class LoginPanel {
private JPanel loginPanel;
public void loginForm()
{
JButton loginSubmit = new JButton("Login");
loginPanel = new JPanel();
loginPanel.add(loginSubmit);
loginPanel.setSize(800, 600);
}
public JComponent getGUI()
{
return loginPanel;
}
public static void main(String[] args)
{
}
}
Main.java:
import javax.swing.*;
import java.awt.*;
public class Main {
public static void main(String[] args)
{
JFrame mainFrame;
mainFrame = new JFrame();
mainFrame.setLayout(new BorderLayout());
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setTitle("Caledonian Library System");
LoginPanel loginObj = new LoginPanel();
mainFrame.add(loginObj.getGUI());
mainFrame.pack();
mainFrame.setVisible(true);
}
}
Should I maybe use box layout? any suggestions?
Ok, I have just run a test program, and have achieved the result you are looking for. I have used a GridBagLayout which defaults to centre into the Container it is added to. It will not show up with the borders or other buttons built into a JFrame (though you can add a border if you wish later).
JFrame mainframe = new JFrame();
JPanel mainPanel = new JPanel();
GridBagLayout gridLayout = new GridBagLayout();
mainPanel.setLayout(gridLayout);
//GridBagConstraints allow you to set various features of the way the components appear
//in the grid. You can set this up as you wish, but defaults are fine for this example
GridBagConstraints gridConstraints = new GridBagConstraints();
//Just using FlowLayout as a test for now
JPanel centerPanel = new JPanel(new FlowLayout());
centerPanel.add(new JLabel("Hello"));
centerPanel.add(new JLabel("Centered"));
mainPanel.add(centerPanel, gridConstraints);
mainFrame.add(mainPanel);
If you found that the space around the side of your centered panel wasn't being used, and you wanted it to be use, you could try nesting mainPanel inside another panel that is using a BorderLayout, making sure that it is in BorderLayout.CENTER.
In the example I didn't bother changing GridBagConstraints from the default, as it was ok for this demonstration. However you can edit it as you wish, and then apply to each component you add to the GridBagLayout, making sure to include the GridBagConstraints object in each mainPanel.add(). Check the GridBagLayout tutorials for some good information.
Of course, if you would like more components in the centre other than the main window, you can then simply add them to the mainPanel (making sure to change the position in the GridLayout). There are going to be numerous ways of achieving what you want, but it really depends on what you feel looks good. The Layout Managers will do all of the resizing work for you.

placing a transparent JPanel on top of another JPanel not working

I am trying to place a JPanel on top of another JPanel which contains a JTextArea and a button and i want to the upper apnel to be transparent. I have tried it by making the setOpaque(false) of the upper panel. but it is not working. Can anyone help me to get through this? Thanks in advance!
public class JpanelTest extends JPanel
{
public JpanelTest()
{
super();
onInit();
}
private void onInit()
{
setLayout(new BorderLayout());
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(new JTextArea(100,100),BorderLayout.CENTER);
panel.add(new JButton("submit"),BorderLayout.SOUTH);
JPanel glass = new JPanel();
glass.setOpaque(false);
add(panel,BorderLayout.CENTER);
add(glass,BorderLayout.CENTER);
setVisible(true);
}
public static void main(String args[])
{
new JpanelTest();
}
}
Indeed, it would be useful to tell the reason why you want panels one over another.
Starting with your code, and changing it a lot, I got it to work, but it might not do what you expect...
import java.awt.*;
import javax.swing.*;
public class Test extends JFrame
{
public Test()
{
super();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 200);
onInit();
setVisible(true);
}
private void onInit()
{
JLayeredPane lp = getLayeredPane();
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(new JTextArea(), BorderLayout.CENTER);
panel.add(new JButton("Submit"), BorderLayout.SOUTH);
panel.setSize(300, 150); // Size is needed here, as there is no layout in lp
JPanel glass = new JPanel();
glass.setOpaque(false); // Set to true to see it
glass.setBackground(Color.GREEN);
glass.setSize(300, 150);
glass.setLocation(10, 10);
lp.add(panel, Integer.valueOf(1));
lp.add(glass, Integer.valueOf(2));
}
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()
{
new Test();
}
});
}
}
If totally transparent, well, it is like it isn't here! When opaque, it just covers some of the GUI, but doesn't prevent mouse clicks, for example.
1) there are a few ways, there no issue to put JPanel, with covering full JFrames/JPanel area or only part of Rectangle / Dimension that returns JFrames/JPanel
use JLayer(Java7) based on JXLayer (Java6)
use GlassPane
use JViewport
use OverlayLayout
use transucent JDialog / JWindow
2) everything depends of if you want to protect against mouse and key events from the top layer to bottom, or not (to avoiding redispatch events from - to and vice versa)
Check out this tutorial on using Swing Root Panes.
The glass pane is useful when you want to be able to catch events or paint over an area that already contains one or more components. For example, you can deactivate mouse events for a multi-component region by having the glass pane intercept the events. Or you can display an image over multiple components using the glass pane.

JTabbedPane shows itself randomly

the problem I encountered is weird for me, because I was doing everything step by step, correctly (in my opinion) and finally when I could say I finished one part of my program it appeared to make a fun of me. The actual problem is that in GUI I created I used a JPanel, then I've put it into a JTabbedPane which I've finally put into a JFrame. Everything is fine and works apart from times when it doesn't. I know it sounds strange, but after running program once I get what I wanted (Frame with tabbed pane containing panel with some stuff in it) and then when I run it again it either show the correct thing again or just empty frame. The worst thing is that it's so random, I haven't got a clue what can be wrong, I don't even know what exactly should I google to find it out. The code is:
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.*;
public class GUI extends JFrame {
JFrame frame = new JFrame("WakeOnLan script generator");
JPanel panel1 = new JPanel(null);
JTextArea text; //= new JTextArea("test");
JScrollPane scroll = new JScrollPane();
JButton but = new JButton("test");
JTabbedPane tab = new JTabbedPane();
public GUI() {
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int w = frame.getSize().width;
int h = frame.getSize().height;
int x = (dim.width-w)/3;
int y = (dim.height-h)/4;
frame.setSize(500,500);
frame.setLocation(x,y);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setLayout(null);
createTab1();
tab.addTab("Tab 1", panel1);
tab.setVisible(true);
tab.setBounds(0, 0, 500, 500);
frame.add(tab);
}
public void createTab1(){
text = new JTextArea("test");
text.setVisible(true);
scroll.setViewportView(text);
scroll.setBounds(10,10,465,300);
panel1.setLayout(null);
panel1.add(scroll);
panel1.setVisible(true);
panel1.setSize(500,500);
//panel.setBackground(Color.blue);
}
}
And then I just run it in the main method in other class:
public class GUIStarter {
public static void main(String[] args) {
GUI start = new GUI();
}
}
So could anyone give me an answer or just a hint?
Thank you.
You should call frame.setVisible(true) after adding all your components to your JFrame. So try moving it to the end of your constructor.
Alternatively, you can call frame.validate() after all the components have been added.

Categories