New JFrame Being Created When I Add Content Pane - java

I don't know why but when I add a content pane it creates a new JFrame window instead of replacing the old content pane on the same window. Thank you, my code follows below: I have a public void (container pane). This is what I'm adding to the JFrame.
public void Start1(){
if (number==0){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
add(getContentPane());
//Display the window.
pack();
setVisible(true);
setExtendedState(JFrame.MAXIMIZED_BOTH);
setVisible(true);
}
else {
add(getContentPane());
//Display the window.
pack();
}
}

As discussed in the comments, the problem you're facing with updating the contents of your ContentPane a simple removeAll(); and then repaint(); would be enought. A Content Pane is always created with it's JFrame, and should not be removed if you have other options. In your case, you should only update your Content Pane's components. This is a solution I made up when I faced a similar problem:
I had a JPanel created in my Content Pane:
JPanel viewport = new JPanel();
viewport.setBackground(Color.WHITE);
viewport.setBounds(0, 302, 414, 420);
contentPane.add(viewport);
viewport.setLayout(null);
And then, whenever I wanted to update that screen, I added the following code to the method/event:
viewport.removeAll();
viewport.repaint();
This will remove every component you had and repaint it to your JPanel. So if you update the information (or whatever it is you want to update) and then run these two simple methods, you'll have your components properly updated.
If you have any other doubts, feel to check the class in which I implemented this solution in my GitHub.

Related

Java Swing- can't get things to display properly using Border Layout, also getting an illegal component position error

I just wrote a simple code where I want a canvas to appear in the CENTER of a JFrame and a config panel to appear in the NORTH of the same JFrame.However after adding them both the 'canvas' doesn't get displayed at all.If I only add the canvas it does get displayed but as soon as I add the config panel it doesn't get displayed anymore.
Furthermore if I try to add something else in the SOUTH of the same JFrame I get a illegal component position error no matter what..
I'm a complete noob when it comes to Swing so sorry if the answer is obvious but I tried googling and researching this for the last few hours without any luck.
Here's what I tried:
public class MainFrame extends JFrame {
ConfigPanel configPanel;
ControlPanel controlPanel;
DrawingPanel canvas;
public MainFrame() {
super("My Drawing Application");
init();
}
private void init() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
canvas = new DrawingPanel(this);
configPanel = new ConfigPanel(this);
controlPanel=new ControlPanel(this);
add(canvas,CENTER);
add(configPanel,NORTH);
add(controlPanel,SOUTH); //this gives me a illegal component position error
pack();
}
}
add(controlPanel,SOUTH);
All the lines should have errors. I'm not sure why that is the only one highlighted. The code should be:
add(controlPanel, BorderLayout.SOUTH);
The preferred constraint is to use: BorderLayout.PAGE_END. Read the section from the Swing tutorial on How to Use BorderLayout for more information and working examples.
Also, there is no reason to pass the frame to the panel in the constructor. If for some reason you need to know the frame of the panel you can invoke the SwingUtiltites.windowForComponent(…) method after the frame is visible.
please try getContentPane().add(controlPanel, SOUTH); instead of add(controlPanel, SOUTH);
do that for every component in the code you provided...

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.

Dynamic changing of layouts in swing

I am almost certain this question was asked before here: Java Swing: How to change GUI dynamically , but I seem to just have some fundamental misunderstanding in how it works.
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
public class JTest extends JFrame
{
public static void main(String[] args)
{
JTest t = new JTest();
}
Container pane;
public JTest()
{
setSize(500,500);
setTitle("JTest");
setDefaultCloseOperation(EXIT_ON_CLOSE);
pane = getContentPane();
pane.setLayout(new GridLayout(1,2));
JButton old = new JButton("old");
old.addActionListener(new OldButton());
pane.add(old);
JScrollPane scroll = new JScrollPane(new JTextArea(50,20));
pane.add(scroll);
setVisible(true);
}
private class OldButton implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
pane.setLayout(new GridLayout(1,2));
JButton old = new JButton("new");
old.addActionListener(new NewButton());
pane.add(old);
JScrollPane scroll = new JScrollPane(new JTextArea(50,20));
pane.add(scroll);
pane.validate();
}
}
private class NewButton implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
pane.setLayout(new GridLayout(1,2));
JButton old = new JButton("old");
old.addActionListener(new OldButton());
pane.add(old);
JScrollPane scroll = new JScrollPane(new JTextArea(50,20));
pane.add(scroll);
pane.validate();
}
}
}
This code should replace the preexisting layout with a new one anytime the button in the corner is pressed, but instead, it just adds the new layout to the frame. Can someone tell me what I'm doing wrong?
EDIT:
Adding some information. A picture for reference:
I'm making a set of components like this inside the scroll pane. whenever I press the "Make new field" button, I want it to add a "field" (the name of the field followed by a textarea or some such) to the set in that scrollpane. This means changing the layout of the area inside the scrollpane to include the new field.
OK -- so it looks like what you want to do (and please correct me if I'm wrong) is to add a new component to a JPanel that is displayed within a JScrollPane. If so, then you do not want to change or swap layouts, and you certainly don't want to keep adding new JScrollPanes. Instead consider doing:
Create one JScrollPane and add to your GUI. Don't re-add this as you'll only need one.
add a JPanel to the JScrollPane's viewport that uses a layout that allows multiple components to be easily added to it. Perhaps a GridLayout or a BoxLayout, depending on what you need.
Also consider not adding the above JPanel directly to the viewport but rather adding it to another JPanel, one that uses BorderLayout, adding the first JPanel to the BorderLayout-using JPanel's BorderLayout.PAGE_START position, and then add this to the JScrollPane's viewport. This way the first JPanel won't stretch to fill the viewport initially.
Then in your button's ActionListener, add your components to the first JPanel by calling .add(...) on it, and then call revalidate() and repaint() on that first JPanel to layout the newly added components and repaint the JPanel and its contents.
Ok, so it turns out this wasn't a layout problem at all. I had failed to realize that setting a new layout doesn't cause the previous layout's components to disappear, you have to remove them before adding the new components. That's why I was getting duplication.
Thanks for pointing me in the right direction, though.

Swing: Start second JPanel, when the first JPanel is clicked

I'm writing a simple java game and I'm facing this problem:
My different layouts are in different JPanels (1 JPanel for the welcoming page, where I have to press 'start game' and another one with the actuall functionallity)
I start the game from a JFrame
import javax.swing.JFrame;
public class RType extends JFrame {
public RType() {
add(new Welcome());//first panel
add(new Board());//panel with the game
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(100, 100);
setResizable(false);
setVisible(true);
}
public static void main(String[] args) {
new RType();
}
}
obviuosly, this launches the second panel right after the first, and I cant see the first one.
I've tried some stuff, trying to invoke the second panel in the main method, when the first panel is clicked that way:
RType rt=new RType();
rt.add(new Board()); //in this case add(new Board()); is removed from constructor
but it's doing nothing.
how can I solve it?
As #nachokk has said, you should be using a CardLayout instead. It lets you do things like tabs in a browser, but you don't need to make the tabs visible for your game if you don't want to. You make your welcome "card" visible at first, then when the user clicks you switch to the Board "card".
I don't recommend to add directly to the JFrame components, instead use another container as JPanel . JFrame default layout is BorderLayout, when you add in the way you are adding it always put in the center.
Make something like this:
JFrame frame = new JFrame();
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new CardLayout());
mainPanel.add(new Welcome(), "Welcome");
mainPanel.add(new Board(),"Board");
frame.add(mainPanel);
Here is a tutorial How to use CardLayout
on first panel of welcome add a button, and apply actionperformed like
JButton myButton = new JButton("Add Component ");
myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.remove(welcome);
frame.add(Board, BorderLayout.CENTER);
frame.revalidate();
frame.repaint();
}
});
By default, both panels will fill up the entire Frame's area. To fix this, you will need to use another layout, such as a GridLayout to structure the areas in which the panels will take up the Frame's area.
You can also go with no layout to hard code the pixel values of where you want the panels to fit in your frame.
EDIT: Based on what you're looking to do, the CardLayout is probably what you'll want to use for your Frame's layout.

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