JFrame is very tiny when restore down is pressed - java

My question is why when I press to the restore down (on a Windows platform) the JFrame is very tiny (see the bellow screenshot).
I use this code regarding State of the JFrame:
this.setExtendedState(View.MAXIMIZED_BOTH);
I need to use setMinimumSize()?

Be sure that this.setExtendedState(JFrame.MAXIMIZED_BOTH) is executed AFTER setVisible(true). Also if you have a setResizable(false) call make sure it is executed AFTER the setExtendedState() one.

I think no one understood his question. He doesn't want to maximize it, he wants when he press "Restore Down", the window won't become so small. So what you need to do, "Restore Down" restores the window to its previous size before "Maximize" has been pressed.
So what I did was this
int Width = (int) java.awt.Toolkit.getDefaultToolkit().getScreenSize().getWidth();
int Height = (int) java.awt.Toolkit.getDefaultToolkit().getScreenSize().getHeight();
this.setSize(Width-100,Height-100);
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
Therefore, every time you press Restore Down, the first time, the size will be the screen size - 100 pixels for width and height.

What class is View?
If you are trying to set your JFrame size to maximum do this (notice I used the static variable available in JFrame class and not View):
JFrame frame=...;
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);

As this was the first and most accurate question to my issue, I will add what I found here. I know it is 3 years old but my answer might help someone in the future. My issue was the same as above. When I built the Jframe I used:
frame.setExtendedState(java.awt.Frame.MAXIMIZED_BOTH);
When I clicked the "restore down" button the window was really small and in the top left corner of the screen. I fixed this by calling:
frame.setBounds(100, 100, 450, 300);
After setVisible(true). Here is the code after my editing, the original code was created with Eclipse WindowBuilder. I am just editing it after. Here is the code complete:
public class MainWindow extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainWindow frame = new MainWindow();
frame.setVisible(true);
frame.setBounds(100, 100, 450, 300);
frame.setExtendedState(java.awt.Frame.MAXIMIZED_BOTH);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MainWindow() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//setExtendedState(java.awt.Frame.MAXIMIZED_BOTH);
//setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
}
}
Basically what is happening (as far as I can determine) after the Jframe becomes visible it is first set to a size of 450x300, then immediately changes the size to maximized. Now when you hit the restore down button it will set it to the 450x300 size. I am currently searching for a way to override the method used to set the window size to the previous size (before hitting max), but I'm not at a point that I need to ask yet.

appFrame = new JFrame("BufferedImage layers");
Dimension asRestoredDown = new Dimension(400,400);//first time restored
appFrame.setMinimumSize(asRestoredDown);
appFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
appFrame.setExtendedState(appFrame.getExtendedState() | JFrame.MAXIMIZED_BOTH);

Related

Getting stared with GUI programming in JAVA

When I compile the code below in Eclipse, I expect a window to appear with a button on the upper left corner of the window. Instead, the button has the same size as the window and fills the window completely, although I suppose to have restricted the size of the button in line 11 with "button.setBounds(20, 20, 200, 50);". Can anybody tell me what I did wrong or what I forgot?
import javax.swing.*;
import java.awt.*;
public class BeobachterGUI {
public BeobachterGUI() {
JFrame frame = new JFrame("A frame");
frame.setSize(new Dimension(600, 600));
JButton button = new JButton("Click me");
button.setBounds(20, 20, 200, 50);
frame.getContentPane().add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new BeobachterGUI();
}
});
}
}
JFrames automatically give themselves a default BorderLayout, which is what is making your button fill the entire screen. If you want to have direct control over the size and position of your button, you have to get rid of that layout manager. Use this line of code:
frame.getContentPane().setLayout(null);
A word of advice, though: working without a layout manager is OK for fun and experimentation, but you shouldn't make a habit of it. You'll get a better GUI (and the users of your GUI get a better experience) if you learn to design with layout managers.
To see an example of what I mean, just watch what happens when you resize your window: if you make the window too small, the button can get cut off or hidden completely. A layout manager would try to reposition and/or resize the button so it stays visible.

Show the hidden JFrame

When I run my JFrame it shows me in hidden size. I have to resize to see JFrame.
Why I cannot get fully sized JFrame.
I used: Pack(); setVisible(true); but it doesn't work.
Here is my code:
public class Mytest extends JFrame{
JLabel label=new JLabel();
JLabel label2=new JLabel();
Timer myTimer;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
new Mytest().show();
}
public Mytest(){
getContentPane().setLayout(new GridBagLayout());
setTitle("test");
GridBagConstraints gridCon=new GridBagConstraints();
gridCon.gridx=0;
gridCon.gridy=0;
getContentPane().add(label,gridCon);
gridCon.gridx=0;
gridCon.gridy=1;
getContentPane().add(label2,gridCon);
myTimer = new Timer(1000,new ActionListener(){
public void actionPerformed(ActionEvent e){
myTimerActionPerformed(e);
}
});
pack();
myTimer.start();
setLocationRelativeTo(null);
}
private void myTimerActionPerformed(ActionEvent e){
Date today=new Date();
label.setText(DateFormat.getDateInstance(DateFormat.FULL).format(today));
label2.setText(DateFormat.getTimeInstance().format(today));
}
}
There are two basic problems...
The first is, when you create and add your JLabels, they have no content, therefore their preferred size is 0x0...
The second is the use of pack, from the JavaDocs
Causes this Window to be sized to fit the preferred size and layouts
of its subcomponents. The resulting width and height of the window are
automatically enlarged if either of dimensions is less than the
minimum size as specified by the previous call to the setMinimumSize
method. If the window and/or its owner are not displayable
yet, both of them are made displayable before calculating the
preferred size. The Window is validated after its size is being
calculated.
So, basically, you are adding two labels, whose total combined size is 0x0 and pack is doing exactly what it was designed to, packing the frame to meet the requirements of the layout manager.
You need to seed the values of the labels before you call pack, for example, add a method that updates the labels, for example...
public void updateLabels() {
Date today = new Date();
label.setText(DateFormat.getDateInstance(DateFormat.FULL).format(today));
label2.setText(DateFormat.getTimeInstance().format(today));
}
Then in your constructor, before you call pack, call this method...
updateLabels();
pack();
myTimer.start();
setLocationRelativeTo(null);
(You should also call this updateLabels method from the Timers actionPerformed method to keep it consistent).
This will seed the labels with some content, which pack and the layout manager can use to determine size of the window...
You should also use setVisible over show as show is deprecated and may be removed at some time in the future
You can maximize frame like this :
setExtendedState(JFrame.MAXIMIZED_BOTH);
or you can size frame as per your requirement like
setSize(500,500);
and you have to add below statement as i cant see this in your code
setVisible(true);

How to add scrollbars on JPanel using null layout manager?

I'm working on a class extending JDialog. I have a JPanel field named "panel" inside it, which is added to the contentPane (another JPanel), and I add the components that are intended to be displayed to "panel".
"Panel" always has the same size as the window itself. (It's practically a duplicate of contentPane.) But the window's size is different by every run, its size is counted in the constructor of the class based on the value of some specific fields that come from the program's business logic. (This size is static through one run, but when writing the code I don't know the exact numbers yet, only the method how to count it.)
This size could sometimes be very big, but I never want my window to be bigger than a specific size, e.g. (1300,800). When the window would be not larger than this size, I don't want the scrollbars to appear. When it would be larger than this on one dimension only, I only want the appropriate scrollbar to appear (vertical / horizontal). And when it's larger on both dimensions, then both scrollbars should appear.
I have read at least 50 tutorials and questions on this topic, here and on other similar forums. And I tried every idea that I found, in every different combination I could only think of. But none of them worked, and now I'm already very desperate.
It might be because neither my contentPane, nor "panel" uses a layout manager. They both use null. I read by another question that we have to set the preferred size of the component we want to be scrolled, but setPreferredSize leans on a layout manager. They there wrote that they don't really have an idea how to solve this issue, else than starting using a layout manager.
But if I start using one, it confuses the layout that I have designed, it ruins the x, y values, which I have set manually by each component. Layout is important in my exercise. It's not right if a layout manager confuses it, and I don't really like for this excercise how the different layout managers set the layout.
Could you give me any ideas on how I could make scrollbars work keeping using null layout manager?... :/
Here's my class Kimenet (Kimenet is the word for "output" in my mother tongue):
public class Kimenet extends JDialog {
private JPanel contentPane, panel;
private int window_width, window_height;
public static Kimenet showDialog(...) {...}
public Kimenet(...){
window_width = ...; //some counting here
window_height = ...; //some counting here
GUI();
}
private void GUI(){
setBounds(0, 0, window_width, window_height);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
setContentPane(contentPane);
panel = new JPanel();
panel.setLayout(null);
panel.setBounds(0, 0, window_width, window_height);
contentPane.add(panel);
//here is where I try to add the scrollbars in every desperate way......
... components that I wanna add: panel.add(component);
}
Here's the part of the Main class from where I make an instance of Kimenet:
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Kimenet dialog = Kimenet.showDialog();
dialog.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
dialog.setModal(true);
dialog.setVisible(true);
System.exit(0);
} catch (Exception e) {
e.printStackTrace();
}
}
});
I have tried adding the scrollbars from Main before making the dialog visible, and from Kimenet's GUI() method as well.
I have tried creating JScrollPane in many different combinations, but this mostly resulted that the scrollbars still didn't appear, but every component that I added to "panel" disappeared.
panel.setPreferredSize(new Dimension(1000, 600));
JScrollPane scrollpane = new JScrollPane(panel);
panel.setAutoscrolls(true);
scrollpane.setPreferredSize(new Dimension(800, 300));
this.add(scrollpane);
I've tried here this.add(scrollpane), contentPane.add(scrollpane), panel.add(scrollpane), scrollpane.add(contentPane) and many combinations.
I have tried creating JScrollBars separately in many different combinations too, but this mostly resulted that the scrollbars simply didn't appear (I have tried much more combinations than what I copy here, e.g. vertical and horizontal scrollbar policy.)
vertikális = new JScrollBar(JScrollBar.VERTICAL, 0, 10, 0, 100);
vertikális.setPreferredSize(new Dimension(700, 600));
contentPane.add(vertikális);
This didn't work in no way either.

JButton not visible until mouseover

I'm creating a gui for my project. When the gui is first loaded only background is visible, so buttons are not visible, but when mouse over them, they are visible. What is the solve this problem?
public class Home extends JFrame{
//New JPanel
private JPanel home;
//Creating image url. You must be change url
ImageIcon icon = new ImageIcon("img//home1.jpeg");
//Home Class
public Home(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 960, 640);
setTitle("LoneyTunes Crush");
home = new JPanel();
home.setBorder(new EmptyBorder(5, 5, 5, 5));
home.setLayout(new BorderLayout(0, 0));
setContentPane(home);
getContentPane().setLayout(null);
JLabel background = new JLabel(new ImageIcon("img//giphy."));
getContentPane().add(background);
background.setLayout(new FlowLayout());
//Creating Buttons
JButton play = new JButton("Play");
play.setBounds(20, 20, 200, 30);
JButton setting = new JButton("Settings");
setting.setBounds(20, 60, 200, 30);
JButton exit = new JButton("Exit");
exit.setBounds(20, 100, 200, 30);
//Adding Buttons
home.add(play);
home.add(setting);
home.add(exit);
//ActionListeners
play.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
home.setVisible(false);
difficulty.setVisible(true);
}
});
exit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(1);
}
});
validate();
}
//Background paint method
public void paint(Graphics g){
g.drawImage(icon.getImage(), 0, 0, getWidth(), getHeight(), null);
}
}
Main Class
public class MainClass {
public static Home pencere;
public static void main(String args[]){
pencere=new Home();
pencere.setVisible(true);
}
}
Don't paint on top-level containers like JFrame as they already carry the burden of painting all of it's components.
Instead paint on JPanel or JComponent and Override it's paintComponent method.
On top of overriding paintComponent (or in your case paint), you need to also call super.paintComponent (in your case super.paint) inside the the method (first call under the method signature), as to not break the paint chain. Failing to do so may and probably will leave you with undesired paint artifacts.
Avoid using null layouts for a number of reason. Different platform will treat them differently. They are difficult to maintain, among many other reasons. Instead use layout managers, and let them do the laying out and sizing of the components, as they were designed to do with Swing apps. Learn more at Laying out components Within a Container
Setting Home pancere as a static class member of MainClass is completely pointless. Just declare and instantiate both in the main method.
Swing apps should be run on the Event Dispatch Thread (EDT). You can do so by wrapping your the code inside your main method with a SwingUtilities.invokeLater.... See more at Initial Threads
Instead of trying to make panels visible and not visible or adding an removing panel, consider using a CardLayout which will "layer" panels, and you can navigate through them with CardLayout's methods like show(), next(), previous(). See more at How to Use CardLayout
By time of deployments, the images you are using will need to become embedded resources, and should be loaded from the class path, and not from the file system. When you pass a String to ImageIcon, you are telling the program to look in the file system, which may work in your development environment, but that's it. See the wiki tag on embedded-resource an pay close attention to the very last link that will provide you will some resources on how to use and load embedded resources if the info doesn't provide enough detail.
Problem is with
getContentPane().setLayout(null);
remove it as you have already set the layout to a Border Layout and you will see all these buttons.
Just make sure that the setvisibility of all other panels except the one which you wish to display is set to false.I too had a similar problem but i had forgotten to set visibility of one of the 10 panels to false.Problem resolved once i set it to false.
I don't know how this worked for me I just typed jf.setVisible(true); at the end after adding all the GUI codes.
public Calculator(){
jf = new JFrame("Basic Calculator");
jf.setLayout(GridBagLayout);
jf.setSize(306, 550);
jf.setLocation(530, 109);
//all the GUI things like JButton, JLabel, etc...
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Try putting validate(); method on your main frame. I think it would help you.

Scrollpane scrollbars to entire Jframe when resizing/adding components

I edited my project using only swing components and a layout (not null).So now i want to add scrollbars to all frame not only at a pictrure.Resizing and moving the scrollbars and showing components under when you scroll down.The difficult is that the frame has many components and users can add pictures and admin can add labels or other components,so i don't know what to redraw when the frame is resized.Redraw everything i can't see for example.I paste some code to tell me where i add scrollpane or scrollbar
public class Test extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test frame = new Test();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Test() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new SpringLayout());
//Suppose that here we have many jlabels,jbuttons,jtextfields and other
}
}
I red some other examples and the problem is that i don't have only a picture to redraw or circles but stuff added by users.Its an online application.
I don't need a small program with a scrollbar example but help on my code how to add it in the entire frame and work dynamically.Resizing and moving the scrollbars and showing components under when you scroll down
Yes you do need a simple example. You should start with something that works and then modify it to meet your needs. You have many problems with your code:
Don't mix AWT and Swing components.
Don't use a null layout.
Don't randomly set the size of a component. Every Swing component is designed to have a preferred size at which is should be displayed.
Read the Swing tutorial. You will find plenty of examples that will show you the proper way to use Swing components and build the initial GUI on the EDT.

Categories