Text boxes squished in Swing layout - java

I have a frame that opens when you click file>new user, but the text fields are all squished together.
I'm trying to have them all stacked vertically so I use new GridLayout(3, 2) as my LayoutManager. However, the stuff for the new window is all the way at the bottom.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class App extends JFrame implements ActionListener
{
private final int WIDTH = 300;
private final int HEIGHT = 550;
private int control = 0;
String[] username = new String[10];
String[] pass = new String[10];
private String tempName;
private String tempPass;
Container con = getContentPane();
JPanel panel = new JPanel();
private JTextField name = new JTextField();
private JPasswordField password = new JPasswordField();
JMenuBar mainBar = new JMenuBar();
JMenu menu1 = new JMenu("File");
JMenu menu2 = new JMenu("Edit");
JMenuItem newUser = new JMenuItem("New User");
JButton but1 = new JButton("Log In");
JButton but2 = new JButton("test");
JLabel error = new JLabel("Login info not corret\n Or user not registered.");
JLabel success = new JLabel("Success!");
/////////////stuff for dialog///////////////////
JPanel panel2 = new JPanel();
JTextField newModalUser = new JTextField();
JPasswordField newModalPass = new JPasswordField();
JPasswordField newModalPassCon = new JPasswordField();
JButton register = new JButton("Register");
////////////////////////////////////////////////
public static void main(String[] args)
{
App frame = new App();
}
public App()
{
//just settin some stuff up
super("For The Bold");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
//setResizable(false);
setVisible(true);
//add menubar
setJMenuBar(mainBar);
mainBar.add(menu1);
menu1.add(newUser);
//background of main JFrame
setContentPane(new JLabel(new ImageIcon("//Users//ryanchampin//Desktop//GUI app//image.png")));
//test names in the arrays
username[0] = "ryan";
pass[0] = "test";
//main stuff in the middle
//panel.setBackground(Color.RED);
panel.setSize(300,300);
panel.add(name);
panel.add(password);
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS ));
panel.add(but1);
panel.add(but2);
add(panel,new GridBagConstraints());
setLayout(new GridBagLayout());
//assign action listener
but1.addActionListener(this);
newUser.addActionListener(this);
register.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
tempName = name.getText();
tempPass = password.getText();
if(source == but1)
{
for(int x = 0; x < username.length; x++)
{
if(tempName.equalsIgnoreCase(username[x]) && tempPass.equals(pass[x]))
{
//display success JLabel
add(success);
System.out.println("success");
break;
}
else
{
success.setText(null);
add(error);
name.setText(null);
password.setText(null);
}
}
}
else
if(source == newUser)
{
panel.setVisible(false);
setLayout(new GridLayout(3,2));
add(panel2);
panel2.add(newModalUser);
panel2.add(newModalPass);
panel2.add(newModalPassCon);
panel2.add(register);
}
else if(source == register)
System.out.println("yay it worked");
}
}

Avoid using setSize(...) or setPreferredSize(...) if possible.
Instead let the components and their layout managers set their own sizes.
Use a CardLayout to swap views instead of what you're doing. If you do this, the CardLayout will size its container to fit all the "cards" that it has been given.
Don't forget to call pack() on the GUI after adding all components
Don't forget to call setVisible(true) after adding all components and after calling pack.
When creating new JTextFields and JPasswordFields, pass in an int for the number of columns into the constructors.
Edit
You ask:
whats pack() used for?
The pack() method tells the GUI to have all the layout managers of its constituent containers to lay out their components, and then to set the best size of the GUI after every component has been properly placed.

If you want spacing in a GridLayout, you can use the setHgap(int) and setVgap(int) methods to set the number of pixels of space that will appear between each element in the grid.
In your code, there are two ways you could do this: construct a GridLayout and call the two setter methods on it, then pass it into the setLayout(LayoutManager) method:
GridLayout layout = new GridLayout(3, 2);
layout.setHgap(5); // or whatever number of pixels you want
layout.setVgap(5); // same
setLayout(layout);
Alternatively, you could cast the LayoutManager you would get from calling getLayout() and call the two methods on it:
setLayout(new GridLayout(3, 2));
((GridLayout) getLayout()).setHgap(5);
((GridLayout) getLayout()).setVgap(5);

if you want them stacked vertically, wouldn't it be easier to keep using BoxLayout?

Related

Place label for text box above the box and not to the side

As stated in the title i need to move the label for the text box to be above the box and not to the side. attached i have a picutres of what i mean. what i have vs what i want i have tried searching for it but i cannot seem to find the answer im looking for/not exactly sure what to look up. I have tried using JFrame but it made a separate window unless i need to make the entire GUI a JFrame for me to get the result i want?
Also the actionPerformed method has things but it is irrelevant to the question but displays correctly still.
import java.awt.event.\*;
import javax.swing.\*;
import java.text.DecimalFormat;
public class Project4 extends JFrame implements ActionListener {
private JTextArea taArea = new JTextArea("", 30, 20);
ButtonGroup group = new ButtonGroup();
JTextField name = new JTextField(20);
boolean ch = false;
boolean pep = false;
boolean sup = false;
boolean veg = false;
DecimalFormat df = new DecimalFormat("##.00");
double cost = 0.0;
public Project4() {
initUI();
}
public final void initUI() {
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
JPanel panel5 = new JPanel();
getContentPane().add(panel1, "North");
getContentPane().add(panel2, "West");
getContentPane().add(panel3, "Center");
getContentPane().add(panel4, "East");
panel4.setLayout(new BoxLayout(panel4, BoxLayout.Y_AXIS));
getContentPane().add(panel5, "South");
JButton button = new JButton("Place Order");
button.addActionListener(this);
panel5.add(button);
JButton button2 = new JButton("Clear");
button2.addActionListener(this);
panel5.add(button2);
panel3.add(taArea);
JCheckBox checkBox1 = new JCheckBox("Cheese Pizza") ;
checkBox1.addActionListener(this);
panel4.add(checkBox1);
JCheckBox checkBox2 = new JCheckBox("Pepperoni Pizza");
checkBox2.addActionListener(this);
panel4.add(checkBox2);
JCheckBox checkBox3 = new JCheckBox("Supreme Pizza");
checkBox3.addActionListener(this);
panel4.add(checkBox3);
JCheckBox checkBox4 = new JCheckBox("Vegetarian Pizza");
checkBox4.addActionListener(this);
panel4.add(checkBox4);
JRadioButton radioButton1 = new JRadioButton("Pick Up");
group.add(radioButton1);
radioButton1.addActionListener(this);
panel1.add(radioButton1);
JRadioButton radioButton2 = new JRadioButton("Delivery");
group.add(radioButton2);
radioButton2.addActionListener(this);
panel1.add(radioButton2);
JLabel name_label = new JLabel("Name on Order");
name.addActionListener(this);
panel5.add(name_label);
panel5.add(name);
setSize(600, 300);
setTitle("Pizza to Order");
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent action) {
}
public static void main(String[] args) {
Project4 ex = new Project4();
ex.setVisible(true);
}
}
You can use a nested JPanel with another layout in order to achieve that. I would go with BorderLayout here. You can also other layouts that allow vertical orientation. Visiting the visual guide to Layout Managers will help you spot them.
JLabel name_label = new JLabel("Name on Order");
name.addActionListener(this);
JPanel verticalNestedPanel = new JPanel(new BorderLayout());
verticalNestedPanel.add(name_label, BorderLayout.PAGE_START);
verticalNestedPanel.add(name, BorderLayout.PAGE_END);
panel5.add(verticalNestedPanel);

Button layout outside of a GridLayout

I'm currently doing a quite simple GUI and was wondering how I could get the button in question out from the GridLayout and put it in its own say BorderLayout, if that's a bit vague I'll attach images to show you what I mean:
With that picture I would like the button to not be with the grid layout and for it to fill all the way across at the bottom of the program as it would in a border layout. My code is as follows:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
/**
* Write a description of class HW4GUI here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class HW4GUI extends JFrame implements ActionListener
{
private JButton jbtAction;
private JTextField jtfFName;
private JTextField jtfLName;
private JTextField jtfLibNo;
private int nextLibNo;
private JPanel textPanel;
/**
* The constructor for the GUI, also initalises nextLibNo number
*/
public HW4GUI()
{
super("Adding a borrower");
makeFrame();
showFrame();
nextLibNo = 1001;
}
/**
*
*/
private void makeFrame()
{
setLayout(new GridLayout(4,0));
setResizable(false);
textPanel = new JPanel();
//textPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
textPanel.setLayout(new BorderLayout());
jtfFName = new JTextField(15);
JLabel fNLbl = new JLabel("First Name: ");
add(fNLbl);
add(jtfFName);
// add(textPanel);
fNLbl.setHorizontalAlignment(JLabel.RIGHT);
jtfFName.setEditable(true);
jtfLName = new JTextField(15);
JLabel lNLbl = new JLabel("Last Name: ");
add(lNLbl);
add(jtfLName);
//add(textPanel);
lNLbl.setHorizontalAlignment(JLabel.RIGHT);
jtfLName.setEditable(true);
jtfLibNo = new JTextField(15);
JLabel lNOLbl = new JLabel("Library Number: ");
add(lNOLbl);
add(jtfLibNo);
// add(textPanel);
lNOLbl.setHorizontalAlignment(JLabel.RIGHT);
jtfLibNo.setEditable(false);
jbtAction = new JButton("Add Borrower");
add(jbtAction, BorderLayout.SOUTH);
jbtAction.addActionListener(this);
}
/**
* displays the frame window where you can set the size of it and also other variables
*/
private void showFrame()
{
setSize(400,200);
setResizable(false);
setLocationRelativeTo( null);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e)
{
String fn = jtfFName.getText();
String ln = jtfLName.getText();
boolean valid = true;
if (e.getActionCommand().equals("Add Borrower"))
{
if (fn.equals("") && (ln.equals("")))
{
jtfLibNo.setText("No Names");
valid = false;
}
else if (fn.equals("") )
{
jtfLibNo.setText("No First Name");
valid = false;
}
else if (ln.equals(""))
{
jtfLibNo.setText("No Last Name");
valid = false;
}
else
if (valid == true)
{
String lib = Integer.toString(nextLibNo++);
jtfLibNo.setText(lib);
jbtAction.setText("Confirm");
}
}
if (e.getActionCommand().equals("Confirm"))
{
jtfLibNo.setText("");
jbtAction.setText("Add Borrower");
}
}
}
As you have said that you want the Button outside your GridLayout, you can do:
Declare a new Panel, like mainPanel or something like that.
JPanel mp = new JPanel();
Set its layout to 3x1 using GridLayout.
mp.setlayout(new GridLayout(3,1));
Add you labels and text-fields to that panel.
mp.add(fNLbl);// and the rest.
Add this panel to your frame.
add(mp, BorderLayout.CENTER);
Then add the Button at the end, using, BorderLayout.SOUTH.
add(jbtAction, BorderLayout.SOUTH);
But as far as my knowledge goes, then your button will occupy the width of the whole frame. So, instead, you can add the button to a panel, and then add that panel to it. Like:
add( new JPanel(){{ add(jbtAction);}}, BorderLayout.SOUTH); // this is double-brace initialization.
The following code works fine:
private void makeFrame()
{
JPanel mp = new JPanel();
mp.setLayout(new GridLayout(3,1));
setResizable(false);
textPanel = new JPanel();
//textPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
textPanel.setLayout(new BorderLayout());
jtfFName = new JTextField(15);
JLabel fNLbl = new JLabel("First Name: ");
mp.add(fNLbl);
mp.add(jtfFName);
// add(textPanel);
fNLbl.setHorizontalAlignment(JLabel.RIGHT);
jtfFName.setEditable(true);
jtfLName = new JTextField(15);
JLabel lNLbl = new JLabel("Last Name: ");
mp.add(lNLbl);
mp.add(jtfLName);
//add(textPanel);
lNLbl.setHorizontalAlignment(JLabel.RIGHT);
jtfLName.setEditable(true);
jtfLibNo = new JTextField(15);
JLabel lNOLbl = new JLabel("Library Number: ");
mp.add(lNOLbl);
mp.add(jtfLibNo);
// add(textPanel);
lNOLbl.setHorizontalAlignment(JLabel.RIGHT);
jtfLibNo.setEditable(false);
jbtAction = new JButton("Add Borrower");
add(mp, BorderLayout.CENTER);
add( new JPanel(){{ add(jbtAction);}}, BorderLayout.SOUTH);
jbtAction.addActionListener(this);
}
With that picture I would like the button to not be with the grid layout and for it to fill all the way across at the bottom of the program as it would in a border layout
Then use a BorderLayout. The default layout manager for a JFrame is a BorderLayout. So you would do somethinglike:
Create a panel using a GridLayout. Add the first 5 components to this panel. Then add the panel to the "CENTER" of the frame.
Create your button. Add the button the the "PAGE_END" of the frame.
The idea of layout managers is that you can nest panels with different layouts to achieve your final layout.
I also agree, the main panel with multiple buttons should probably be a GridBagLayout as it will size each column to the width of the widest component in the column instead of making every column width identical, which will make the panel look better. Read the section from the Swing tutorial on How to Use GridBagLayout for more information and working examples.

Gridlayout button click then load under the buttons a form Java

I really didn't now how to form the question i have a gridlayout with 4 buttons. When the user press Add module i want under the buttons a form instead of a new windows if this is possible.
frame = new JFrame("ModuleViewer");
makeMenu(frame);
Container contentPane = frame.getContentPane();
// Specify the layout manager with nice spacing
contentPane.setLayout(new GridLayout(0, 2));
addModule = new JButton("Toevoegen Module");
contentPane.add(addModule);
overview = new JButton("Overzicht Modules");
contentPane.add(overview);
addSchoolweeks = new JButton("Aapassen schoolweken");
contentPane.add(addSchoolweeks);
weekheavy = new JButton("Weekbelasting");
contentPane.add(weekheavy);
frame.pack();
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation(d.width/2 - frame.getWidth()/2, d.height/2 - frame.getHeight()/2);
frame.setVisible(true);
I know that i first need to add een action method for the buttons i know how to do that so that isn't important. I only want to know how i could create a layout under the buttons so when a user clicks the layout will be draw.
Each panel can only have one layout, but you can use multiple panels for the desired effect: a top panel using GridLayout to hold your buttons, and a bottom panel using CardLayout to hold multiple other panels, one for each button click. Each of these panels can use whatever layout you want, depending on its contents.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutDemo implements Runnable
{
final static String CARD1 = "Red";
final static String CARD2 = "Green";
final static String CARD3 = "Blue";
JPanel cards;
CardLayout cardLayout;
public static void main(String[] args)
{
SwingUtilities.invokeLater(new CardLayoutDemo());
}
public void run()
{
JButton btnRed = createButton("Red");
JButton btnGreen = createButton("Green");
JButton btnBlue = createButton("Blue");
JPanel buttons = new JPanel(new GridLayout(1,3));
buttons.add(btnRed);
buttons.add(btnGreen);
buttons.add(btnBlue);
JPanel card1 = new JPanel();
card1.setBackground(Color.RED);
JPanel card2 = new JPanel();
card2.setBackground(Color.GREEN);
JPanel card3 = new JPanel();
card3.setBackground(Color.BLUE);
cardLayout = new CardLayout();
cards = new JPanel(cardLayout);
cards.add(card1, CARD1);
cards.add(card2, CARD2);
cards.add(card3, CARD3);
JFrame f = new JFrame("CardLayout Demo");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(buttons, BorderLayout.NORTH);
f.add(cards, BorderLayout.CENTER);
f.setSize(300, 200);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
private JButton createButton(final String name)
{
JButton button = new JButton(name);
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
cardLayout.show(cards, name);
}
});
return button;
}
}

My GUI window doesn't show anything

I'm trying to use a grid layout to make a GUI window. I add all my components and it compiles but when it runs it doesn't show anything. I'm trying to make a simple layout grouped and stacked like this.
{introduction message}
{time label
time input text}
{gravity label
gravity input text}
{answer label
answer text box}
{calculate button clear button}
Here is my code
import javax.swing.*;
import java.awt.*;
public class TurnerRandyFallingGUI extends JFrame
{
final int WINDOW_HEIGHT=500;
final int WINDOW_WIDTH=500;
public TurnerRandyFallingGUI()
{
setTitle("Falling Distance Calculator");
setSize(WINDOW_WIDTH,WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(1, 5));
//labels
JLabel introMessage = new JLabel("Welcome to the Falling distance"+
"calculator");
JLabel timeLabel = new JLabel("Please enter the amount of time "+
"in seconds the object was falling.");
JLabel gravityLabel = new JLabel("Enter the amount of gravity being "+
"forced onto the object");
JLabel answerLabel = new JLabel("Answer");
//text fields
JTextField fTime = new JTextField(10);
JTextField gForce = new JTextField(10);
JTextField answerT = new JTextField(10);
//buttons
JButton calculate = new JButton("Calculate");
JButton clr = new JButton("clear");
//panels
JPanel introP = new JPanel();
JPanel timeP = new JPanel();
JPanel gravityP = new JPanel();
JPanel answerP = new JPanel();
JPanel buttonsP = new JPanel();
//adding to the panels
//intro panel
introP.add(introMessage);
//time panel
timeP.add(timeLabel);
timeP.add(fTime);
//gravity panel
gravityP.add(gravityLabel);
gravityP.add(gForce);
//answer panel
answerP.add(answerLabel);
answerP.add(answerT);
//button panel
buttonsP.add(calculate);
buttonsP.add(clr);
setVisible(true);
}
public static void main(String[] args)
{
new TurnerRandyFallingGUI();
}
}
You've added nothing to the JFrame that your class above extends. You need to add your components to containers whose hierarchy eventually leads to the top level window, to the this if you will. In other words, you have no add(someComponent) or the functionally similar this.add(someComponent)method call in your code above.
Consider adding all of your JPanels to a single JPanel
Consider adding that JPanel to the JFrame instance that is your class by calling add(thatJPanel).
Even better would be to not extend JFrame and just to create one when needed, but that will likely be the subject of another discussion at another time.
Before setVisible (true) statement add following statements:
add (introP);
add (timeP);
add (gravityP);
add (answerP);
add (buttonsP);
There is nothing in your JFrame. That is the reason
import javax.swing.*;
import java.awt.*;
public class TurnerRandyFallingGUI extends JFrame
{
final int WINDOW_HEIGHT=500;
final int WINDOW_WIDTH=500;
public TurnerRandyFallingGUI()
{
//labels
JLabel introMessage = new JLabel("Welcome to the Falling distance"+
"calculator");
JLabel timeLabel = new JLabel("Please enter the amount of time "+
"in seconds the object was falling.");
JLabel gravityLabel = new JLabel("Enter the amount of gravity being "+
"forced onto the object");
JLabel answerLabel = new JLabel("Answer");
//text fields
JTextField fTime = new JTextField(10);
JTextField gForce = new JTextField(10);
JTextField answerT = new JTextField(10);
//buttons
JButton calculate = new JButton("Calculate");
JButton clr = new JButton("clear");
//panels
JPanel introP = new JPanel();
JPanel timeP = new JPanel();
JPanel gravityP = new JPanel();
JPanel answerP = new JPanel();
JPanel buttonsP = new JPanel();
//adding to the panels
//intro panel
introP.add(introMessage);
//time panel
timeP.add(timeLabel);
timeP.add(fTime);
//gravity panel
gravityP.add(gravityLabel);
gravityP.add(gForce);
//answer panel
answerP.add(answerLabel);
answerP.add(answerT);
//button panel
buttonsP.add(calculate);
buttonsP.add(clr);
setLayout(new GridLayout(5, 1));
this.add(introP);
this.add(timeP);
this.add(gravityP);
this.add(answerP);
this.add(buttonsP);
setTitle("Falling Distance Calculator");
this.pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
this.validate();
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TurnerRandyFallingGUI();
}
});
}
}
Consider the following
In GridLayout, the first parameter is Rows, Second is columns
Never set the size of JFrame manually. Use pack() method to decide
the size
Use SwingUtilities.InvokeLater() to run the GUI in another thread.

How to implement a JPanel that shows/hide content depending on its width?

I'm trying to implement a JPanel that displays more or less information depending on the available size.
Basically, the idea is have a default content like this:
That can shrinks to this when the space is reduced:
My code is like this:
import net.miginfocom.swing.MigLayout;
import javax.swing.*;
class PanelDemo extends JPanel {
private final JLabel title = new JLabel();
private final JLabel counter1 = new JLabel("00");
private final JLabel counter1Label = new JLabel();
private final JLabel counter2 = new JLabel("00");
private final JLabel counter2Label = new JLabel();
/**
* Instantiates a new obs app cadre message bloc panel.
*/
public PanelDemo() {
this.setOpaque(false);
initGUI();
}
private final void initGUI() {
// 1°)
final MigLayout migLayout = new MigLayout(
"fillx, hidemode 2, debug",
"[growprio 0][]" //define 4 columns
);
setLayout(migLayout);
// 2°)
//
add(title, "spanx");
add(counter1, "newline");
add(counter1Label);
add(counter2);
add(counter2Label);
}
public static void main(String[] args) {
final JFrame jFrame = new JFrame("test 4");
jFrame.getContentPane().setLayout(new MigLayout("fillx, debug"));
final PanelDemo item1 = new PanelDemo();
item1.title.setText("Element 1");
item1.counter1Label.setText("First lbl");
item1.counter2Label.setText("Second lbl");
jFrame.getContentPane().add(item1, "growx, gpx 110");
final PanelDemo item2 = new PanelDemo();
item2.title.setText("Element 2");
item2.counter1Label.setText("First lbl");
item2.counter2Label.setText("Second lbl");
jFrame.getContentPane().add(item2, "growx, gpx 100");
jFrame.pack();
jFrame.setVisible(true);
} }
I tried to add a ComponentListener and override componentResized() to find when I could show/hide my secondary labels but I was not successful.
Does anybody know how to implement such a behaviour that goes well with MigLayout grow priorities?
Update1: I was thinking... what if I set the minimum width to counter1+label1, and the maximum size to counter2+label2 and then listen to resize operations and change the preferred size to either its minimum or its maximum. Would that mecanism work?
How about this:
public static JPanel panel(String name) {
JPanel panel = new JPanel(new MigLayout("insets 0, wrap 4, fillx, debug", "[][][shrink 200][shrink 200, grow 200]"));
panel.add(new JLabel(name), "spanx 4");
panel.add(new JLabel("00"));
panel.add(new JLabel("First lbl"));
panel.add(new JLabel("01"));
panel.add(new JLabel("Second lbl"));
return panel;
}
public static void main(String[] args) {
JPanel panel = new JPanel(new MigLayout("insets 10, gap 10, fillx, debug"));
panel.add(panel("Element 1"), "w (50% - 15)!");
panel.add(panel("Element 2"), "w (50% - 15)!");
JFrame frame = new JFrame();
frame.setContentPane(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
I had trouble getting the two main columns to resize equally; I had to do it by setting a width on the components rather than the columns. I'm not sure why that is.
I implemented an autohide mechanism with a LayoutCallback switching the visibility of the component depending on the width of the panel.
Here is an example:
MigLayout layout = new MigLayout("fill");
JPanel panel = new JPanel(layout);
JLabel label1 = new JLabel("Label 1");
label1.putClientProperty("autohide.width", 300);
JLabel label2 = new JLabel("Label 2");
label2.putClientProperty("autohide.width", 200);
panel.add(label1, "grow");
panel.add(label2, "grow");
layout.addLayoutCallback(new LayoutCallback() {
#Override
public void correctBounds(ComponentWrapper wrapper) {
JComponent component = (JComponent) wrapper.getComponent();
Number width = (Number) component.getClientProperty("autohide.width");
if (width != null) {
if (component.isVisible() && wrapper.getParent().getWidth() < width.intValue()) {
component.setVisible(false);
} else if (!component.isVisible() && wrapper.getParent().getWidth() > width.intValue()) {
component.setVisible(true);
}
}
}
});
Here the label1 is hidden when the width of the panel shrinks below 300 pixels, and label2 disappears when the width is less than 200 pixels.

Categories