Scrollbar JTextarea not working - java

For some reason my scrollbar is appearing but it is not working. What is suppose to happen is using the scrollbar to scroll through the text of the textarea. Can somebody please explain why this isnt working?
import java.io.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class App extends JFrame{
private JPanel paneel;
public App(){
paneel = new AppPaneel();
setContentPane(paneel);
}
public static void main(String args[]){
JFrame frame = new App();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setTitle("Auto Clicker");
frame.setVisible(true);
}
}
class AppPaneel extends JPanel{
private JTextField delayField, xLocation, yLocation;
private JTextArea listArea;
private JButton addButton, saveButton, runButton;
private JScrollPane scroll;
public AppPaneel(){
setLayout(null);
delayField = new JTextField();
delayField.setBounds(10, 10, 85, 25);
delayField.setText("delay in ms");
xLocation = new JTextField();
xLocation.setBounds(105, 10, 85, 25);
xLocation.setText("X position");
yLocation = new JTextField();
yLocation.setBounds(200, 10, 85, 25);
yLocation.setText("Y position");
addButton = new JButton("Add");
addButton.setBounds(295, 10, 75, 24);
addButton.addActionListener(new AddHandler());
listArea = new JTextArea();
listArea.setBounds(10, 45, 360, 180);
scroll = new JScrollPane(listArea);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setBounds(370, 45, 20, 180);
saveButton = new JButton("Save");
saveButton.setBounds(10, 230, 85, 24);
runButton = new JButton("Run (F1)");
runButton.setBounds(105, 230, 85, 24);
runButton.addActionListener(new RunHandler());
add(delayField);
add(xLocation);
add(yLocation);
add(addButton);
add(listArea);
add(saveButton);
add(runButton);
add(scroll);
}
class AddHandler implements ActionListener{
public void actionPerformed(ActionEvent a){
listArea.setText(listArea.getText() + delayField.getText() + ", " + xLocation.getText() + ", " + yLocation.getText() + ", " + "click;" + "\n");
}
}
class RunHandler implements ActionListener{
private Robot bot;
private String text;
int foo = Integer.parseInt("1234");
public void actionPerformed(ActionEvent b) {
try{
text = listArea.getText();
bot = new Robot();
for(String line : text.split("\\n")){
int delay = Integer.parseInt((line.substring(0, 4)));
int xpos = Integer.parseInt((line.substring(6, 10)));
int ypos = Integer.parseInt((line.substring(12, 16)));
bot.mouseMove(xpos, ypos);
Thread.sleep(delay);
bot.mousePress(InputEvent.BUTTON1_MASK);
bot.mouseRelease(InputEvent.BUTTON1_MASK);
}
}
catch (AWTException | InterruptedException e){
e.printStackTrace();
}
}
}
}

Don't use null layouts and setBounds as it is messing up your program. We tell folks time and time again not to do this for a reason -- by setting the JTextArea's bound you constrain its size so it won't grow when it needs to. The solution, as always -- learn and use the layout managers. Set the JTextArea's column and row properties but not its bounds, its size, or its preferred size.
Next don't do this: Thread.sleep(delay); in your Swing application as it will put the entire application to sleep. Use a Swing Timer instead for any delays. The tutorials can help you use this.
For a non-functional layout example:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.*;
#SuppressWarnings("serial")
public class App2 extends JPanel {
private static final int GAP = 5;
private JTextField textField1 = new JTextField(GAP);
private JTextField textField2 = new JTextField(GAP);
private JTextField textField3 = new JTextField(GAP);
private JTextArea textArea = new JTextArea(15, 30);
public App2() {
JPanel topPanel = new JPanel(new GridLayout(1, 0, GAP, GAP));
topPanel.add(textField1);
topPanel.add(textField2);
topPanel.add(textField3);
topPanel.add(new JButton("Add"));
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JPanel bottomPanel = new JPanel(new GridLayout(1, 0, GAP, GAP));
bottomPanel.add(new JButton("Save"));
bottomPanel.add(new JButton("Run (F1)"));
bottomPanel.add(new JLabel(""));
bottomPanel.add(new JLabel(""));
setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
setLayout(new BorderLayout(GAP, GAP));
add(topPanel, BorderLayout.PAGE_START);
add(scrollPane, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Auto Clicker");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new App2());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Your whole approach is wrong. You should not be using a null layout. For example:
scroll.setBounds(370, 45, 20, 180);
you are setting the width to 20. Well how to you expect the text area to display in 20 pixels? This is the problem with using setBounds(...), the random numbers you use have no meaning. Let a layout manager do its job. Also:
add(listArea);
The problem is that a component can only have a single parent. You originally created the JScrollPane with the text area which is correct.
But then you add the text area directly to the frame which removes it from the scroll pane so the scroll panel will no longer function.
Get rid of that statement and just add the scroll pane to the frame.
However, I don't recommend you use this as your final solution. I just wanted to mention the current problems so you hopefully understand the benefits of using layout managers and so that you don't try to share components again.
The proper solution is to use layout managers as has been suggested by the "Community Wiki". Then the layout manager will determine the size and location of each component so you don't need to worry about calculating your pixel values correctly.

Related

JLabel not positioning correctly

I am just throwing together a quick and dirty GUI to display some data when I ran into an odd issue. The last label I add to the JFrame doesn't want to be positioned or display the border I put on it, so it looks like this:
Here is my code:
public DisplayData (Connection tConn)
{
ID = tID;
conn = tConn;
setupObjects();
setupFrame();
}
private void setupObjects()
{
JLabel caseLabel = new JLabel ("Case #:");
JLabel dateLabel = new JLabel ("Date:");
JLabel reportLabel = new JLabel ("Report:");
JLabel offenceLabel = new JLabel ("Offence:");
JLabel descriptionLabel = new JLabel ("Description:");
this.add(caseLabel);
this.add(dateLabel);
this.add(reportLabel);
this.add(offenceLabel);
this.add(descriptionLabel);
caseLabel.setBounds(50, 50, 130, 25); //x, y, width, height
dateLabel.setBounds(50, 100, 130, 25);
reportLabel.setBounds(50, 150, 130, 25);
offenceLabel.setBounds(50, 200, 130, 25);
descriptionLabel.setBounds(100, 50, 130, 25);
caseLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
dateLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
reportLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
offenceLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
descriptionLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
}
private void setupFrame()
{
this.setTitle("Data Display");
this.setSize (650, 700); //Width, Height
this.setLocation(300, 10);
this.setResizable(false);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLayout(null);
}
Yes, I know I should be using a proper layout manager, but like I said i just wanted something quick and dirty. Plus, I will not be beaten by something that should be this simple. Any ideas would be appreciated.
EDIT:
As Compass and Neophyte pointed out, my order of operations was off. Flipped my method calls and all is good again in the world. Thanks for the 2nd pair of eyes.
Contrary to the original poster's strategy, or any of the answers so far, the best approach to this problem is to use layouts.
Here is an example that shows how easy it is to position fields using layouts, and to change the GUI on later updates to the specification.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class CourtDetailsGUI {
private JComponent ui = null;
static final String[] FIELD_NAMES = {
"Case #:",
"Date:",
"Report:",
"Offence:",
"Plaintiff:",
"Defendant:"
};
CourtDetailsGUI(int num) {
initUI(num);
}
public void initUI(int num) {
if (ui != null) {
return;
}
ui = new JPanel(new BorderLayout(4, 4));
ui.setBorder(new EmptyBorder(4, 4, 4, 4));
ui.add(getFieldsPanel(num), BorderLayout.PAGE_START);
JTextArea ta = new JTextArea(5, 40);
JScrollPane sp = new JScrollPane(ta);
JPanel p = new JPanel(new GridLayout());
p.add(sp);
p.setBorder(new TitledBorder("Details"));
ui.add(p);
}
private JPanel getFieldsPanel(int num) {
JPanel outerPanel = new JPanel(new FlowLayout());
JPanel innerPanel = new JPanel(new GridLayout(0, 1, 15, 15));
outerPanel.add(innerPanel);
for (int ii=1; ii<num; ii++) {
JLabel l = new JLabel(FIELD_NAMES[ii]);
l.setBorder(new LineBorder(Color.BLACK));
innerPanel.add(l);
}
return outerPanel;
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
for (int ii=0; ii<FIELD_NAMES.length; ii++) {
CourtDetailsGUI o = new CourtDetailsGUI(ii+1);
JFrame f = new JFrame("Data " + (ii+1));
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
}
};
SwingUtilities.invokeLater(r);
}
}
Your order of operations is incorrect.
You initially call setupObjects();
This plays your objects out onto a JFrame, which has the default LayoutManager of BorderLayout.
By using the default add(Component comp) method, with BorderLayout, you end up putting the component into null for BorderLayout, which is not supposed to be normal. Furthermore, the reason you can't see the border for this object is because the border is actually the size of the frame. If you explicitly set a region for BorderLayout, then you'll see it work, but setting to no region seems to just break BorderLayout.
Additional add calls appear to free the previous item from the BorderLayout null management, allowing the bounds to take over.
Afterwards, you call setupFrame(); which removes the layout manager, but does not refresh what is currently rendered.
This sets the layout to null, which does nothing to how the frame is displayed, but just removes the layout.
To avoid this issue, call setupFrame(); prior to setupObjects();, and then setVisible(true) can be called at the end of setupObjects();

Can't position Buttons or JLabels

I am new to working with GUI's in Java and I am having a problem moving my text and buttons around. No matter what coordinates I give my button or any of the other JLabel it doesn't move, I was wondering how I could fix it this in such a way that I can place my components where ever I want on the JPanel
public class IntroPage extends JFrame {
public static void main(String[] args) {
IntroPage main = new IntroPage();
main.setVisible(true);
}
private JPanel contentPane;
public IntroPage (){
//make sure the program exits when the frame closes
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Welcome");
contentPane = new JPanel();
setSize(400,700);
//This will center the JFrame in the middle of the screen
setLocationRelativeTo(null);
//Welcome Page stuff :D
JLabel ApplauseLabel = new JLabel("Welcome to U.X.Dot.X");
ApplauseLabel.setFont(new Font("Gill Sans MT", Font.PLAIN, 30));
ApplauseLabel.setLocation(100, 50);
contentPane.add(ApplauseLabel);
JLabel slogan = new JLabel("Register below");
slogan.setFont(new Font("Gill Sans MT", Font.PLAIN, 15));
slogan.setLocation(100, 400);
contentPane.add(slogan);
//FacebookSignUp.
JButton FBbutton = new JButton("Login With FaceBook");
FBbutton.setBackground(Color.BLUE);
FBbutton.setSize(50,50);
FBbutton.setLocation(20, 40);
FBbutton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//Add JPanel to go to FB API. Much later
}
});
contentPane.add(FBbutton);
add(contentPane);
//make sure the JFrame is visible
setVisible(true);
}
}
You're ignoring the layout managers of your contentPane JPanel. Understand that it uses FlowLayout by default, and will ignore your setLocation and setBounds statements. Ror the JPanel to accept absolute positioning, you would have to give it a null layout via contentPane.setLayout(null).
Having said that, I do not advise you to do this! While null layouts, setLocation(...) and setBounds(...) might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.
For example the following GUI
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import javax.swing.*;
public class IntroPage2 extends JPanel {
public static final String TITLE = "Welcome to U.X.Dot.X";
private JLabel welcomeLabel = new JLabel(TITLE, SwingConstants.CENTER);
private JButton fbButton = new JButton("Login With Facebook");
public IntroPage2() {
fbButton.setBackground(Color.BLUE);
fbButton.setForeground(Color.CYAN);
welcomeLabel.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 30));
int wlGap = 20;
welcomeLabel.setBorder(BorderFactory.createEmptyBorder(wlGap, wlGap, wlGap, wlGap));
JLabel registerBelowLabel = new JLabel("Register Below");
registerBelowLabel.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 15));
JPanel centralPanel = new JPanel(new GridBagLayout());
centralPanel.setPreferredSize(new Dimension(300, 600));
centralPanel.add(registerBelowLabel);
JPanel topPanel = new JPanel(new BorderLayout());
topPanel.add(fbButton, BorderLayout.LINE_START);
topPanel.add(welcomeLabel, BorderLayout.CENTER);
setLayout(new BorderLayout());
int ebGap = 8;
setBorder(BorderFactory.createEmptyBorder(ebGap, ebGap, ebGap, ebGap));
add(topPanel, BorderLayout.PAGE_START);
add(centralPanel, BorderLayout.CENTER);
}
private static void createAndShowGui() {
IntroPage2 mainPanel = new IntroPage2();
JFrame frame = new JFrame("Welcome");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
would create something like:

Java swing JTextField dissapears after adding a button to BorderLayout.SOUTH [duplicate]

This question already has an answer here:
Java aligning components in panels
(1 answer)
Closed 6 years ago.
I add a JTextField to my game in the bottom left corner using a nested BorderLayout inside my main panel's BorderLayout.SOUTH. This works fine, but then when I add a button to go right next to it, my JTextField dissapears. Can someone please help?
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class BlackjackGUI{
private JFrame frame;
private JPanel panel, panelLeft, panelBottom;
private JButton newGameBtn, dealBtn, hitBtn, standBtn;
private JLabel placeBetLbl, playerMoneyLbl;
private JLabel playerCard1Lbl, playerCard2Lbl, playerCard3Lbl,
playerCard4Lbl, playerCard5Lbl, playerCard6Lbl, playerCard7Lbl;
private JLabel dealerCard1Lbl, dealerCard2Lbl, dealerCard3Lbl, dealerCard4Lbl,
dealerCard5Lbl, dealerCard6Lbl, dealerCard7Lbl;
private JLabel playerCardValueLbl, dealerCardValueLbl;
private JLabel spacer1, spacer2;
private JTextField betInputBox;
public BlackjackGUI(){
createForm();
addTextField();
addButtons();
addLabels();
frame.add(panel);
frame.setVisible(true);
}
public void createForm() {
frame = new JFrame("Blackjack");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1200,800);
panel = new JPanel();
panel.setLayout(new BorderLayout());
Color c = new Color(0, 100, 0);
panel.setBackground(c);
panelLeft = new JPanel();
Color panelLeftBG = new Color (23, 25, 100);
panelLeft.setBackground(panelLeftBG);
panel.add(panelLeft, BorderLayout.WEST);
panelBottom = new JPanel();
Color panelBottomBG = new Color (56, 12, 10);
panelBottom.setBackground(panelBottomBG);
panelBottom.setLayout(new BorderLayout());
panel.add(panelBottom, BorderLayout.SOUTH);
}
public void addButtons() {
newGameBtn = new JButton("New Game");
panelLeft.add(newGameBtn, BorderLayout.WEST);
newGameBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
dealBtn = new JButton("Deal");
dealBtn.setPreferredSize(new Dimension (100, 50));
panelBottom.add(dealBtn, BorderLayout.WEST);
newGameBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
}
public void addTextField() {
betInputBox = new JTextField("£25.00");
betInputBox.setFont(new Font("Gill Sans MT", Font.PLAIN, 35));
betInputBox.setHorizontalAlignment(SwingConstants.RIGHT);
betInputBox.setPreferredSize(new Dimension(175,50));
panelBottom.add(betInputBox, BorderLayout.WEST);
}
public void addLabels() {
placeBetLbl = new JLabel("Place your bets!");
placeBetLbl.setFont(new Font("Gill Sans MT", Font.PLAIN, 35));
panelBottom.add(placeBetLbl);
playerMoneyLbl = new JLabel("£2,500");
playerMoneyLbl.setFont(new Font("Gill Sans MT", Font.PLAIN, 35));
panelBottom.add(playerMoneyLbl, BorderLayout.EAST);
}
public static void main(String[] args) {
new BlackjackGUI();
}
}
Excerpt from the BorderLayout javadoc:
Each region may contain no more than one component, and is identified
by a corresponding constant: NORTH, SOUTH, EAST, WEST, and
CENTER.
Your are first adding the text field and then the button to the same region (WEST), thus button just replaces the text field.
To solve the issue you can use FlowLayout for the panelBottom:
panelBottom.setLayout(new FlowLayout(FlowLayout.LEFT));

How can I properly adjust the size and location of a button in JFrame?

I am attempting to make a PC Application using Java and JFrame. I'm trying to format 2 transparent buttons, each sized half of the full screen shown (vertically). The top half of the screen will hold to option to debate someone and the bottom half of the screen will hold the option to spectate a debate if clicked on. Here is what I have so far:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class BackgroundImageJFrame extends JFrame {
JButton b1;
JButton b2;
JPanel j1;
JPanel j2;
public BackgroundImageJFrame() {
setTitle("Background Color for JFrame");
setSize(340,563);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setLayout(null);
/*
One way
-----------------
setLayout(new BorderLayout());
JLabel background=new JLabel(new ImageIcon("C:\\Users\\Computer\\Downloads\\colorful design.png"));
add(background);
background.setLayout(new FlowLayout());
l1=new JLabel("Here is a button");
b1=new JButton("I am a button");
background.add(l1);
background.add(b1);
*/
// Another way
setLayout(new BorderLayout());
setContentPane(new JLabel(new ImageIcon("C:\\Users\\MLH-User\\Downloads\\Front.jpg")));
setLayout(new FlowLayout());
j1 = new JPanel();
j1.setLayout(null);
b1 = new JButton("Spectate");
//b1.setBounds(0,0,50,50);
b1.setOpaque(false);
b1.setContentAreaFilled(false);
b1.setBorderPainted(false);
j1.add(b1);
b2 = new JButton("Debate");
b2.setLocation(0,0);
b2.setOpaque(false);
b2.setContentAreaFilled(false);
b2.setBorderPainted(false);
j1.add(b2);
add(j1);
// Just for refresh :) Not optional!
setSize(339,562);
setSize(340,563);
}
public static void main(String args[]) {
new BackgroundImageJFrame();
}
}
This is some stuff I experimented with so far, can anyone help me out about where I went wrong?
You should use a layout manager. Here is an example with GridLayout:
public class Example extends JFrame {
private static final int SIZE = 300;
public Example() {
setLayout(new GridLayout(2, 1, 0, 5));
getContentPane().setBackground(Color.WHITE);
JButton debate = new JButton("DEBATE") {
public Dimension getPreferredSize() {
return new Dimension(SIZE, SIZE);
}
};
Font font = debate.getFont().deriveFont(30f);
debate.setFont(font);
// debate.setBorderPainted(false);
debate.setBackground(Color.BLUE.brighter());
debate.setForeground(Color.WHITE);
JButton spectate = new JButton("SPECTATE") {
public Dimension getPreferredSize() {
return new Dimension(SIZE, SIZE);
}
};
spectate.setFont(font);
// spectate.setBorderPainted(false);
spectate.setBackground(Color.RED.brighter());
spectate.setForeground(Color.WHITE);
add(debate);
add(spectate);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public static void main(final String[] args) {
SwingUtilities.invokeLater(() -> new Example());
}
}
Notes:
You have to realize that screen sizes vary. Setting SIZE to 300 was an arbitrary choice for presentation, screens might not have the required size. You can also set the insets or an empty border instead of specifying the size of the component directly.
You can consider creating a class for these buttons if you have more of them.
This is an example of setting the sizes. I don't know about the location part though.
JFrame frame = new JFrame("test");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(4,4,4,4));
for(int i=0 ; i<16 ; i++){
JButton btn = new JButton(String.valueOf(i));
btn.setPreferredSize(new Dimension(40, 40));
panel.add(btn);
}
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);

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