Resize Control with Java JSplitPane - java

Please see my image below at the link and then read below it for more details on my problem.
Imagine that is a Basic frame splited into two with a JSplitPane, by default when you resize your frame the gray part changes it's size, but I would like the white part to resize accordingly to the frame resizing.
Any help into the right direction would be appreciated as I am working on a project now and I am trying out all kind of weird stuff to be prepared for my biggest project set in the new year. :)
Regards
Theron

You need to use setResizeWeight to get the left and right take the extra space or reduce in size on JFrame resize, sample code below:
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JSplitPane;
public class TestJSplitPane {
private void init(){
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
splitPane.setRightComponent(new JButton("Here I Am"));
splitPane.setLeftComponent(new JButton("Me Too"));
splitPane.setResizeWeight(0.5);
frame.add(splitPane, BorderLayout.CENTER);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) {
new TestJSplitPane().init();
}
}
Java Doc for setResizeWeight.
Hope this helps.

Related

How to draw two JPanels on top of each other?

I am currently working on a N-Body simulation and I have made particles move on a black screen. My current problem is that there is no way of controlling it.
My plan:
Each color stands for a different JPanel. The blue one should contain the buttons and text fields, the red one the viewport.
But with my small knowledge in Java, I didn't succeed in creating this. I first tried with setBounds and setLayoutManager(null), in vain.
My structure goes like that:
Window class extends JFrame
Simulation class creating blueJPanel class (extends JPanel) and redJPanel,
adds them to the window.
But this is garbage code... So how would you draw these simple panels on top of each other?
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section. Pay particular attention to the Laying Out Components Within a Container section.
As I said in my comment, you create two JPanels. Here's an example.
Here's the complete runable code to create this example.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class BorderLayoutExampleGUI implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new BorderLayoutExampleGUI());
}
#Override
public void run() {
JFrame frame = new JFrame("BorderLayout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createButtonPanel(), BorderLayout.NORTH);
frame.add(createMainPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
panel.setPreferredSize(new Dimension(600, 100));
panel.setBackground(Color.blue);
// Add the buttons and text fields
return panel;
}
private JPanel createMainPanel() {
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
panel.setPreferredSize(new Dimension(600, 380));
panel.setBackground(Color.red);
// Add the drawing code
return panel;
}
}

Packed JFrame Too Tall?

I am trying to create a simple Java Swing GUI that consists of a panel on top and tabs in the center. I want the top panel to remain its preferred size and the tabs to take up the remaining space so I used a BorderLayout. The content of the tab can be tall so I put the tab component into a scroll pane.
Everything seems to work the way I expect (with respect to component sizing and scroll bar behavior when I resize the frame) except that my packed frame is 12 pixels too tall (and possibly 16 pixels too wide). Would someone please explain what is going on and how to resolve it. Somehow when the pack is sizing all of the components, something is smart enough to (mostly) respect the screen size. I am using Java 8 on Windows 7 with a screen resolution of 1920 x 1200.
Below is my test code and the output it produces.
Code:
package test;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GraphicsEnvironment;
import java.awt.Toolkit;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
public final class SizeTest
{
public static void main(final String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
createAndShowGui();
}
});
}
private static void createAndShowGui()
{
final JPanel topPanel = new JPanel();
topPanel.setBorder(BorderFactory.createTitledBorder("Top"));
topPanel.setPreferredSize(new Dimension(800, 150));
final JPanel centerPanel = new JPanel();
centerPanel.setBorder(BorderFactory.createTitledBorder("Center"));
centerPanel.setPreferredSize(new Dimension(800, 1300));
final JScrollPane scrollPane = new JScrollPane(centerPanel);
final JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("Tab", scrollPane);
final JPanel mainPanel = new JPanel(new BorderLayout(0, 10));
mainPanel.add(topPanel, BorderLayout.NORTH);
mainPanel.add(tabbedPane, BorderLayout.CENTER);
final JFrame mainFrame = new JFrame("Size Test");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.add(mainPanel);
mainFrame.pack();
System.err.println("***** Frame Size: " + mainFrame.getSize() + ", Screen Size: "
+ Toolkit.getDefaultToolkit().getScreenSize() + ", Maximum Window Bounds: "
+ GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds());
mainFrame.setVisible(true);
}
}
Output:
***** Frame Size: java.awt.Dimension[width=816,height=1212], Screen Size: java.awt.Dimension[width=1920,height=1200], Maximum Window Bounds: java.awt.Rectangle[x=0,y=0,width=1920,height=1156]
If you're going to stuff around with setPreferredSize, be prepared for things to go astray.
The first thing I would do, is seriously reconsider using setPreferredSize.
Because of the way the API works, JScrollPane will use the preferredSize of the component to make determinations about it's own size. You can change this by implementing the Scrollable interface, which allows you to return the preferredScrollableViewportSize, which JScrollPane will use instead when determing how large it needs to be
You see Scrollable demonstrated here and here and lots of other places if you do some searching

How do i add an image in Java?

frame.add(new JLabel(new ImageIcon("C:/Users/Sam/Pictures/DesktopBackgrounds/image.png")));
I saw this on another question so i tried to use it and the class runs with no errors however no image is on the screen.
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.KeyStroke;
class FullSceenToggleAction extends AbstractAction {
private JFrame frame;
private GraphicsDevice fullscreenDevice;
public FullSceenToggleAction(JFrame frame) {
this(frame, GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice());
}
public FullSceenToggleAction(JFrame frame, GraphicsDevice fullscreenDevice) {
this.frame = frame;
this.fullscreenDevice = fullscreenDevice;
}
#Override
public void actionPerformed(ActionEvent e) {
frame.dispose();
if (frame.isUndecorated()) {
fullscreenDevice.setFullScreenWindow(null);
frame.setUndecorated(false);
} else {
frame.setUndecorated(true);
fullscreenDevice.setFullScreenWindow(frame);
}
frame.setVisible(true);
frame.repaint();
}
}
public class Main {
public static final void addKeyBinding(JComponent c, String key, final Action action) {
c.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(key), key);
c.getActionMap().put(key, action);
c.setFocusable(true);
}
public static void main(String[] args) {
final JFrame frame = new JFrame("Fullscreen Toggle Test");
Container contentPane = frame.getContentPane();
contentPane.add(new JLabel("Hey"), BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(960, 600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setTitle("Virtual World");
frame.add(new JLabel(new ImageIcon("C:/Users/Sam/Pictures/DesktopBackgrounds/image.png")));
addKeyBinding(frame.getRootPane(), "F11", new FullSceenToggleAction(frame));
}
}
In case you need it this is the full code.
There are several issues with your codes. In Swing, the order of your codes does makes a difference.
Code order issue:
Currently you are adding an image to the frame after you set the size. When the frame size changes, the paint manager will be consulted to repaint the frame. Hence you will only be able to see the "Hey" label you added earlier but not the image.
It is advisable to set the size after you added all the components you need. If not, you may want to revalidate() your frame later.
I will usually setup the components in the following order:
// Create frame
// Set default close operation for frame
// Add components or container to frame
// pack the frame (frame will be repainted by this action)
// set visible as true
Layout issue:
You are using the frame's default layout (BorderLayout). If you do not state the position/direction for the components to be added in BorderLayout, it will be added to the CENTER by BorderLayout's default.
In your codes, you added the image (2nd label) without stating the position (String specification). Doing so will replace the first label with the second label. Hence only one component will be shown in the frame.
Other issues:
There are some other issues which I would summarize below:
It is advisable to setVisible(true) last to prevent flickering issues.
I would prefer to add another container such as JPanel into the JFrame and add the components in the panel instead of adding directly to the frame.
With the above, you can pack() the frame which allows it to determine its own preferredSize according to the added components.
Try adding imageIcon Label to content pane works.
Container contentPane = frame.getContentPane();
contentPane.add(new JLabel("Hey"), BorderLayout.SOUTH);
contentPane.add(new JLabel(new ImageIcon("C:/Users/Sam/Pictures/DesktopBackgrounds/image.png")));
you may find the code helpful.I posted this code for understanding purpose.
public class AddingIconJLabel {
public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame();
frame.setTitle("JLabel Test");
frame.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageIcon imageIcon = new ImageIcon("C:/Users/Sam/Pictures/DesktopBackgrounds/image.png");
JLabel label = new JLabel(imageIcon);
frame.add(label);
frame.pack();
frame.setVisible(true);
}
}
this will output the following..Hope you found my help useful.

How can I keep the vlcj player from taking up all the room?

I am writing a small Swing program which involves embedding a video player in the interface. In order to achieve this, I am using vlcj.
While the GUI itself has some more components, here is an analog code structure:
import uk.co.caprica.vlcj.component.EmbeddedMediaPlayerComponent;
import javax.swing.*;
import java.awt.*;
public class MyTestClass extends JFrame {
public MyTestClass(){
EmbeddedMediaPlayerComponent playerCmpt =
new EmbeddedMediaPlayerComponent();
playerCmpt.setPreferredSize(new Dimension(200, 100));
JPanel leftPane = new JPanel();
leftPane.setPreferredSize(new Dimension(100, 100));
JSplitPane mainSplit = new JSplitPane(
JSplitPane.HORIZONTAL_SPLIT,
leftPane, playerCmpt);
this.add(mainSplit);
this.pack();
this.setVisible(true);
}
public static void main(String[] args){
new MyTestClass();
}
}
(I tried this code separately, and I'm facing the same problem as in my GUI)
Basically, the window has two parts: a left panel in which I display some data, and a right panel in which the video is to be embedded. The panels are put together in a JSplitPane is order to allow the user to allocate the amount of room he desires for the player (and therefore, for the video itself). At first, the components get 100 and 200 pixels in width, respectively.
The problem is: EmbeddedMediaPlayerComponent is getting a little too confortable. While I have set it to a preferred size of 200x100, it refuses to shrink down once the vertical split has been moved. That is, I can't bring the player below 200 pixels in width, and once I've enlarge it, I can't bring it back to 200 pixels... Setting a maximum size doesn't change anything. This little problem is annoying because it forces my left panel to shrink again and again, until it becomes practically invisible.
Is there any way I could have the media player follow the constraints set by JSplitPane as the user tries to resize the components? If it's any use, the left pane contains a JTree in my application, which also gets crushed by the player.
This one works for me. Just improve the code to fit for your purpose.
import com.sun.jna.Native;
import com.sun.jna.NativeLibrary;
import java.awt.*;
import javax.swing.*;
import uk.co.caprica.vlcj.binding.LibVlc;
import uk.co.caprica.vlcj.component.EmbeddedMediaPlayerComponent;
import uk.co.caprica.vlcj.runtime.RuntimeUtil;
public class MyTestClass extends JFrame {
public MyTestClass() {
String vlcPath = "C:\\Program Files (x86)\\VideoLAN\\VLC";
NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(), vlcPath);
Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);
EmbeddedMediaPlayerComponent playerCmpt = new EmbeddedMediaPlayerComponent();
playerCmpt.setPreferredSize(new Dimension(200, 100));
JPanel leftPane = new JPanel();
leftPane.setPreferredSize(new Dimension(100, 100));
JPanel playerPanel = new JPanel(new BorderLayout());
playerPanel.add(playerCmpt);
JSplitPane mainSplit = new JSplitPane(
JSplitPane.HORIZONTAL_SPLIT,
leftPane, playerPanel);
playerPanel.setMinimumSize(new Dimension(10, 10));
this.add(mainSplit);
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new MyTestClass();
}
}

How to make JTextField expand with a BorderLayout (Java)

I have a Java program, in which, I'm using a JTextField, but if i don't specify a default size, it'll have the width 0. I'm inserting it in a BorderLayout, so how do I make it expand to fill the whole container?
In the above example, the text field will work fine. However, if you insert into EAST or WEST, it will not work.
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class TextFieldTest {
public static void main(String[] args) {
JFrame f = new JFrame();
f.setLayout(new BorderLayout());
JTextField tf = new JTextField();
f.getContentPane().add(BorderLayout.EAST, tf);
f.pack();
f.setVisible(true);
}
}
My question back to you is: Does this need to be a BorderLayout or can you use other Layout Managers? If you can, you should check out GridBagLayout that you can have an element auto expand (using a weight) to fit the entire container.
Fill the whole container? With BorderLayout?
container.add( jTextField, BorderLayout.CENTER );
Simple as that.
When programming with Swing the key thing is to use a good layout manager. For me the perfect layout manager is MigLayout. This is simply the best one-stop solution to all layout needs. Their site provides excellent documentation and examples.
It will automatically fill to the width of the container, example shown:
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class TextFieldTest {
public static void main(String[] args) {
JFrame f = new JFrame();
f.setLayout(new BorderLayout());
JTextField tf = new JTextField();
f.add(tf, BorderLayout.SOUTH);
f.pack();
f.setVisible(true);
}
}

Categories