JComponents only appear after resizing [duplicate] - java

This question already has answers here:
Java items appear only after the window is resize
(2 answers)
Closed 5 years ago.
I've encountered what I am pretty sure is a glitch, and have not found any way around it. I, at present, have only a simple window that has a text field and a label. When I first run the program, what appears is an empty window, when I resize the window, either by maximizing or just manually resizing a little bit, the components appear, what's going on here?
public class Calculator {
public static void main(String[] args) {
JFrame mainFrame = new JFrame("Calculator");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setSize(300,400);
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
JPanel mainPanel = new JPanel();
mainFrame.add(mainPanel);
JTextField mainField = new JTextField(20);
mainPanel.add(mainField);
JLabel mainLabel = new JLabel("Orange");
mainPanel.add(mainLabel);
}
}

By default the size of all components is (0, 0), so there is nothing to paint.
Components need to be added to the frame BEFORE the setVisible() method. Then when the frame is made visible the layout manager is invoked and components are given a size/location.

You're adding components to the frame after calling setVisible(true).
This question has already been asked.
Java items appear only after the window is resize

Related

Can someone help me understand how ImageIcon works for java?

So I have about a year a 5/12 months experience playing around with java but I have never been able to make anything outside of skeletons. I would really appreciate it if someone could help me understand how I can make an image from my computer visible using swing.
I have gone between different websites trying to find answers but none of the example codes I've tried have worked out. Stackoverflow has helped in the past to learn java through various questions other people asked so I have made an account to ask a question myself. I'm probably being very dumb but my image never appears despite what I've tried. I come back to trying to understand swing every few months after giving up on it previously and while I feel I have a grasp on some basic concepts such as something should be set as visible, how to make/add a JFrame, etc, it's always this that messes me up.
import javax.swing.*;
import java.awt.*;
public class Main extends JFrame {
public static void main(String[] args) {
JFrame frame = new JFrame("main");
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
ImageIcon ii = new ImageIcon("C:\\Users\\plasm\\IdeaProjects\\Shdo\\src\\mario.jpg");
JLabel lable = new JLabel(ii);
JScrollPane jsp = new JScrollPane(lable);
frame.getContentPane().add(jsp);
frame. setSize(1000, 700);
JButton button = new JButton();
button.setSize(new Dimension(300, 300));
button.setLocation(500, 350);
frame.getContentPane().add(button);
frame.setVisible(true);
}
}
The code above is copy-pasted from https://www.daniweb.com/programming/software-development/threads/379864/add-image-and-button-to-jframe aside from the pathway, however, it only shows a basic white JFrame at the set dimensions.
frame.getContentPane().add(jsp); // problem
frame. setSize(1000, 700);
JButton button = new JButton();
button.setSize(new Dimension(300, 300)); // does nothing
button.setLocation(500, 350); // does nothing
frame.getContentPane().add(button); //problem
The problem is that the default layout manager for the content pane of the JFrame is a BorderLayout. You are attempting to add two compnents to the CENTER of the BorderLayout which won't work. The button replaces the scroll pane.
Instead you should be using:
frame.getContentPane().add(jsp, BorderLayout.CENTER);
frame. setSize(1000, 700);
JButton button = new JButton("Testing");
frame.getContentPane().add(button, BorderLayout.PAGE_END);
Read the section from the Swing tutorial on Layout Manager for more information and working example of a BorderLayout.
As mentioned in the first comment. There is no need for the getContentPane(). The frame will automatically add the component to the content pane.
Also, when doing testing it is better to do something like:
JLabel label = new JLabel("Icon label");
label.setIcon(ii);
This way if you specify the wrong path for the image, you will at least see the text of the label and you will know the problem is in the path, not with the layout code.

JPanel in JScrollPane not showing [duplicate]

This question already has answers here:
Why is my table not visible when it's in a JScrollPane?
(2 answers)
Closed 8 years ago.
I'm busy making a level designer for a game I'm planning to make in Java. I have a panel for settings, for example the size of the level or what the background will be. You can also select images to put on the other panel, the 'DesignerPanel' and then you should be able to click on that panel to put it in a specific place. I put the DesignerPanel in a JScrollPane to scroll around bigger levels.
The problem is that the JScrollPane doesn't appear and neither does the panel that should be in it. I have found some questions about the scroll bars not appearing, but in my case nothing appears. Well, at least, almost nothing.
You can see really small stripes of the DesignerPanel to the right and below. However, there is no trace of the JScrollPane or the rest of the panel. Resizing or minimizing and unminimizing the screen doesn't make a difference. I would post an image and I think it would surely help, but apparently I need reputation to do that, so sorry about that.
Here's the relevant code I have so far. I have hidden most of the code because it is not important for this error.
package games;
import java.awt.*;
import java.io.*;
import javax.swing.*;
class LevelDesignerScreen extends JFrame
{
private SettingsPanel sp;
private DesignerPanel dp;
private JScrollPane scroller = new JScrollPane();
LevelDesignerScreen()
{
sp = new SettingsPanel(this);
add(sp, BorderLayout.WEST);
dp = new DesignerPanel(sp);
dp.setSize(1000, 1000);
scroller.setPreferredSize(new Dimension(600, 600));
scroller.add(dp);
add(scroller, BorderLayout.CENTER);
}
public static void main(String[] args)
{
new LevelDesignerScreen();
}
}
You should use
scroller = new JScrollPane(dp);
or
scroller.setViewportView(dp);
instead of scroller.add(dp).
And on a more general note: if you are having problems with layout, put prime colored line borders on all involved components to see what takes up space and what doesn't.

Resizable frame in Gui [duplicate]

This question already has answers here:
JFrame: How to disable window resizing?
(8 answers)
Closed 9 years ago.
how to get non resizable frame in gui i confused about this because i am using setLayout(new FlowLayout()); so if i drag the size of the frame the location of my button is going to disarrange . here is my code so far
import java.awt.*;
import javax.swing.*;
public class aw extends JFrame
{
private JTextField aw1;
private JLabel aww;
private JButton aw2;
public aw()
{
setLayout(new FlowLayout());
aww = new JLabel("Enter Your Password");
add(aww);
aw1 = new JTextField(15);
add(aw1);
aw2 = new JButton("Enter");
add(aw2);
}
public static void main(String args [])
{
aw v = new aw();
v.setSize(200,200);
v.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
v.setVisible(true);
}
}
I think setResizable(false) is what you're looking for
SIDE NOTES
Also, instead of setSize(). You should just pack() the frame. You can use EmptyBorders if you want empty space.
If you wanted the frame to be re-sizable and you want all the components centered when resizing, You could always wrap them all in a JPanel, then add the JPanel to the frame.
Use Java naming convention. Class names start with capital letters.
Run Swing apps form the Event Dispatch Thread, see Initial Threads
Put all the content into a JPanel, that would let you configure the pack() element, please ensure that you use an Empty Border. In the Object we have an accesor by setResizable set it to false.
Keep a note of rest and then use a Singleton thread model to run the Event-Dispatch Thread.
Thanks to AndrewThompson for his extra-ordinary knowledge that I was able to make the necessary updates

In JAVA, JButton, Button displayed only when cursor is on the button and works even on clicking anywhere in contentPane

I am a beginner into Java and OOPS in general. Am studyin Head First Java to start, and studying GUI and Swing concepts in it.
The below code is just for understanding purposes.
On running the code, The frame window is displayed with Button, and when I expand it I can see Radio Button too.
Issues-
Button works till the window size is not more than the button size . As soon as I increase the window size even slightly more than button's dimensions, then the button is displayed only when cursor is on it.
I am changing window size using mouse.
Also even if I set Frame size to be more than button. say frame.setSize(800,800); then the button covers whole contentPane. and still behaves same way on resizing.
And the button responds to clicking on mouse, irrespective of where I click in the contentPane. It should respond only when i click directly on the button.
Please inform me why it is behaving this way.
And if possible,corrections in code or additions to correct this.
import java.awt.Color;
import javax.swing.*;
import java.awt.event.*;
public class Test1 implements ActionListener {
JFrame frame = new JFrame("Frame");
JButton button = new JButton("Button!");
JRadioButton radio = new JRadioButton("VideoKilledTheRadioStar!",true);
int j=0;
public static void main(String[] args) {
Test1 t = new Test1();
t.method1();
}
public void method1()
{
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.setSize(100,100);
button.setBackground(Color.ORANGE);
frame.add(button);
frame.setSize(100,100);
frame.setVisible(true);
button.addActionListener(this);
frame.getContentPane().add(radio);
radio.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{j++;
button.setText("clicked .. " + j);
if(button.getBackground()==Color.ORANGE)
button.setBackground(Color.BLUE);
else
button.setBackground(Color.ORANGE);
}
}
P.S I did not know which segment of code is important or more relevant to this question, so I have put complete code.
You are trying to add the JButton button and JRadioButton objects in the default layout(BorderLayout) of the JFrame.
Whenevery you add a component to JFrame having BorderLayout the components goes in the Middle Section and BorderLayout center section has tendency to occupy the complete space, so to position elements properly you will need to specify the location as well as set the PreferredSize of the component.
frame.add(radio, BorderLayout.SOUTH);
component.setPreferredSize(Dimension);
You are adding the JButton button and the JRadioButton both in the BorderLayout.CENTER location so only one is being displayed. Components at this location will be sized in the X and Y axis.
The JButton only displays when the cursor is over it due to the fact that it has its own MouseListener used for painting.
Also, the statements
frame.add(myComponent);
and
frame.getContentPane().add(myComponent);
both add the component to the frame's ContentPane & are equivalent but the first is chosen for convenience.
Note that components cannot co-exist in the same position in a BorderLayout. You could place the button at the BorderLayout.SOUTH position (& add directly to the frame):
frame.add(radio, BorderLayout.SOUTH);
BorderLayout disregards any preferred sizes for components so you would have to use a different layout manager such as BoxLayout to maintain a fixed size JButton.
See more about Layout Managers

JEditorPane inside JScrollPane not resizing as needed

I am implementing a Comment box facility in my application which user can resize using mouse. This comment box contains a scrollpane which instead contains a JEditorPane in which user can insert comment. I have added the editor pane inside a scroll pane for the following reason:
auto scolling of jeditorpane
When the user resizes the comment box, I am setting the desired size for JScrollPane and the JEditorPane. When the user is increasing the size of the comment box, the size of these components are increasing as desired but when the size of the comment box is decreased, the size of the JEditorPane does not decrease even after setting the size. This leads to the scrollbars inside the scrollpane.
I tried using setPreferrredSize, setSize, setMaximumSize for JEditorPane. Still the size of the editor pane is not reducing. I tried calling revalidate() or updateUI() after the setting of size but no use.
I am using Java 1.4.2.
Please provide me some insight....
I realise this is long since answered, but for future reference all you need to do is override the getScrollableTracksViewportWidth() to always return true, eg.
JEditorPane pane = new JEditorPane() {
public boolean getScrollableTracksViewportWidth() {
return true;
}
};
panel.add(new JScrollPane(pane));
Actually it is possible, luiscubal. Here is how,
To the JScrollPane add a ComponentListener for resize events
public static void main(String...args) {
//our test frame
JFrame frame = new JFrame("JEditorPane inside JScrollPane resizing");
frame.setLayout(new BorderLayout());
//our editing pane
final JEditorPane editor = new JEditorPane();
//our simple scroll pane
final JScrollPane scroller = new JScrollPane(editor);
//NOTE: this is the magic that is kind of a workaround
// you can also implement your own type of JScrollPane
// using the JScrollBar and a JViewport which is the
// preferred method of doing something like this the
// other option is to create a JEditorPane subclass that
// implements the Scrollable interface.
scroller.addComponentListener(new ComponentAdapter() {
#Override
public void componentResized(ComponentEvent e) {
editor.setSize(new Dimension(
scroller.getWidth()-20,
scroller.getHeight()-20));
}
});
//just use up the entire frame area.
frame.add(scroller, BorderLayout.CENTER);
//quick and dirty close event handler
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(320, 240); //something not too big
frame.setLocationRelativeTo(null); //centers window on screen
frame.setVisible(true); // normally done in a SwingUtilities.invokeLater
}
Look luiscubal it is possible. Don't be so quick to announce things in Java as not possible. The swing api is quiet flexible and can do a lot of the work for you. However, if you use JComponents in ways they weren't made to be used you will end up with problems and have two options.
subclass subclass subclass basically create your own component.
find a work around, like the above solution.
Decreasing the size of a JEditorPane in a JScrollPane and then reducing it, is not possible.
You may want to use a JTextArea instead.

Categories