Is there a simple way to align just the checkbox of a JCheckBox to the right without creating a separate label and check box component? I am aware of setHorizontalTextPosition(SwingConstants.LEADING); This only results in the box being on the right side of the text, but not right aligned.
What I want:
| Some sample text ☑ |
instead of
| Some sample text ☑ |
Thanks in advance!
You can manually manipulate the icon text gap every time the check box size changes by adding a ComponentListener to the check box:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SSCCE extends JPanel
{
public SSCCE()
{
setLayout( new BorderLayout() );
JCheckBox checkBox = new JCheckBox("Some Sample Text");
checkBox.setHorizontalTextPosition(JCheckBox.LEADING);
add(checkBox, BorderLayout.PAGE_START);
checkBox.addComponentListener( new ComponentAdapter()
{
#Override
public void componentResized(ComponentEvent e)
{
JCheckBox checkBox = (JCheckBox)e.getComponent();
int preferredWidth = getPreferredSize().width;
int actualWidth = getSize().width;
int difference = actualWidth - preferredWidth;
int gap = checkBox.getIconTextGap() + difference;
gap = Math.max(UIManager.getInt("CheckBox.textIconGap"), gap);
checkBox.setIconTextGap( gap );
}
});
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new SSCCE());
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater( () -> createAndShowGUI() );
/*
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
*/
}
}
You can separate the label and checkbox in a suitable layout. I've made the enclosing frame wider by an arbitrary factor to show the effect.
Addendum: As noted here, "clicking the label doesn't check the box." A suitable MouseListener can toggle the check box in response to a mouse press anywhere in the enclosing panel.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
* #see https://stackoverflow.com/a/36369035/230513
* #see http://stackoverflow.com/a/2933256/230513
*/
public class Test {
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.setLayout(new GridLayout(0, 1));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createPanel("Some label"));
frame.add(createPanel("Another label"));
frame.add(createPanel("Yet another label"));
frame.pack();
frame.setSize(frame.getWidth() * 2, frame.getHeight());
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createPanel(String s) {
JPanel panel = new JPanel(new BorderLayout());
JCheckBox check = new JCheckBox();
panel.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
check.setSelected(!check.isSelected());
}
});
panel.add(new JLabel(s, JLabel.LEFT), BorderLayout.WEST);
panel.add(check, BorderLayout.EAST);
panel.setBorder(BorderFactory.createLineBorder(Color.blue));
return panel;
}
});
}
}
you can also use method in AbstractButton.java setIconTextGap(int)
Related
I am writing in a notepad. And I want to implement text scaling in my notepad. But I don't know how to do it. I'm trying to find it but everyone is suggesting to change the font size. But I need another solution.
I am create new project and add buttons and JTextArea.
package zoomtest;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JTextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class zoom {
private JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
zoom window = new zoom();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public zoom() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.NORTH);
JButton ZoomIn = new JButton("Zoom in");
ZoomIn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//Code here...
}
});
panel.add(ZoomIn);
JButton Zoomout = new JButton("Zoom out");
Zoomout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//Code here...
}
});
panel.add(Zoomout);
JTextArea jta = new JTextArea();
frame.getContentPane().add(jta, BorderLayout.CENTER);
}
}
Introduction
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section. Pay close attention to the Laying Out Components Within a Container section.
I reworked your GUI. Here's how it looks when the application starts. I typed some text so you can see the font change.
Here's how it looks after we zoom out.
Here's how it looks after we zoom in.
Stack Overflow scales the images, so it's not as obvious that the text is zooming.
Explanation
Swing was designed to be used with layout managers. I created two JPanels, one for the JButtons and one for the JTextArea. I put the JTextArea in a JScrollPane so you could type more than 10 lines.
I keep track of the font size in an int field. This is a simple application model. Your Swing application should always have an application model made up of one or more plain Java getter/setter classes.
Code
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class ZoomTextExample {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
new ZoomTextExample();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private int pointSize;
private Font textFont;
private JFrame frame;
private JTextArea jta;
private JTextField pointSizeField;
public ZoomTextExample() {
this.pointSize = 16;
this.textFont = new Font(Font.DIALOG, Font.PLAIN, pointSize);
initialize();
}
private void initialize() {
frame = new JFrame("Text Editor");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createButtonPanel(), BorderLayout.NORTH);
frame.add(createTextAreaPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
JButton zoomIn = new JButton("Zoom in");
zoomIn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
incrementPointSize(+2);
updatePanels();
}
});
panel.add(zoomIn);
panel.add(Box.createHorizontalStrut(20));
JLabel label = new JLabel("Current font size:");
panel.add(label);
pointSizeField = new JTextField(3);
pointSizeField.setEditable(false);
pointSizeField.setText(Integer.toString(pointSize));
panel.add(pointSizeField);
panel.add(Box.createHorizontalStrut(20));
JButton zoomOut = new JButton("Zoom out");
zoomOut.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
incrementPointSize(-2);
updatePanels();
}
});
panel.add(zoomOut);
return panel;
}
private JPanel createTextAreaPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
jta = new JTextArea(10, 40);
jta.setFont(textFont);
JScrollPane scrollPane = new JScrollPane(jta);
panel.add(scrollPane, BorderLayout.CENTER);
return panel;
}
private void updatePanels() {
pointSizeField.setText(Integer.toString(pointSize));
textFont = textFont.deriveFont((float) pointSize);
jta.setFont(textFont);
frame.pack();
}
private void incrementPointSize(int increment) {
pointSize += increment;
}
}
So I have tried to turn my JLabel with an Image to a clickable button. But I ran into some problems.
Here's what I used:
Icon image = new ImageIcon("Image Path");
JLabel button = new JLabel(image);
button.setBounds(250, 100, 128, 64); //used a 500x200 window
frame.add(button);
button.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
System.out.print("Hello");
}
});
So when I run the code I can click anywhere and I always get the Hello message.
But I only want the message to be printed out only when I click the image and not anywhere else.
How can I do this?
Thanks!
**Edit:
Heres what I really mean:
As you can see, there should be a blue box saying Hello.
and when I click it, I do get the message Hello but when I click outside the blue box(the white spots) I still get the message. Is there a way that I can disable that? So that when I only click the blue spot I get the message?**
You could just define a Rectangle, in whichs range a click on the JLabel should print your text. You can get the coordinates of your click relative to the JLabel with getX and getY. To check if the click is inside the rectangle you can use the method contains.
See JLabel and Rectangle. A working example:
package labelbutton;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.*;
public class LabelButton {
private static final Rectangle CLICK_FIELD = new Rectangle(140, 140, 200, 200);
public static void main(String[] args) throws MalformedURLException {
JFrame jf = new JFrame();
jf.add(createLabelButton());
jf.setVisible(true);
jf.pack();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private static JLabel createLabelButton() throws MalformedURLException {
Icon image = new ImageIcon(new URL("https://images.assetsdelivery.com/compings_v2/4zevar/4zevar1509/4zevar150900035.jpg"));
JLabel button = new JLabel(image);
button.setPreferredSize(new Dimension(500, 500));
button.setBorder(BorderFactory.createLineBorder(Color.RED, 3));
button.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if(CLICK_FIELD.contains(e.getX(), e.getY())) {
System.out.println("Hello");
}
}
});
return button;
}
}
You can also add the JLabel into a JPanel with GridBagLayout and then add the panel to the frame. This way, the JPanel is going to occupy the extra space, while the JLabel is going to always be centered in it.
Here's a working example:
import java.awt.Color;
import java.awt.GridBagLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Main {
public static void main(final String[] args) {
SwingUtilities.invokeLater(() -> {
final JLabel button = new JLabel("Hello");
button.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(final MouseEvent mevt) {
System.out.println("Hello label/button!");
}
});
button.setBorder(BorderFactory.createLineBorder(Color.CYAN.darker()));
final JPanel panel = new JPanel(new GridBagLayout());
panel.add(button);
final JFrame frame = new JFrame("Label button");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}
I am making a dating game in the style of the Japanese dating game with pictures and responses for fun and practice. I am trying to have a JOptionPane message dialog show up for each button in a grid layout as a response to each option. In this way it's like a logic tree. I am not used to using action listener as I am somewhat of a beginner. Here is my code. I am just not used to the syntax of doing this.
Can anyone help me?
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.*;
//Implementations of packages
public class NestedPanels extends JPanel {
private static final String[] BTN_TEXTS = { "Say Hello", "Say You Look Good", "Say Sorry I'm Late" }; //three buttons
private static final int TITLE_POINTS = 3; //number of objects in text box
public NestedPanels() { //implemeted class
JPanel southBtnPanel = new JPanel(new GridLayout(3, 2, 1, 1)); //grid layout of buttons and declaration of panel SoutbtnPanel
for (String btnText : BTN_TEXTS) { //BTN TEXT button titles linked to string btnText label
southBtnPanel.add(new JButton(btnText)); //add btnText label
}
setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1)); //layout of buttons "Button text"
setLayout(new BorderLayout());
add(Box.createRigidArea(new Dimension(600, 600))); //space size of text box webapp over all
add(southBtnPanel, BorderLayout.SOUTH);
}
private static void createAndShowGui() {//class to show gui
NestedPanels mainPanel = new NestedPanels(); //mainPanel new class of buttons instantiation
JFrame frame = new JFrame("Date Sim 1.0");//title of webapp on top
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setVisible(true);
ImageIcon icon = new ImageIcon("C:/Users/wchri/Pictures/10346538_10203007241845278_2763831867139494749_n.jpg");
JLabel label = new JLabel(icon);
mainPanel.add(label);
frame.setDefaultCloseOperation
(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
System.out.println("Welcome to Date Sim 1.0 with we1. Are you ready to play? Yes/No?");
Scanner in = new Scanner(System.in);
String confirm = in.nextLine();
if (confirm.equalsIgnoreCase("Yes")) {
System.out.println("Ok hot stuff... Let's start.");
NestedPanels mainPanel = new NestedPanels();
} else {
System.out.println("Maybe some other time!");
return;
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Review the following to get an idea of how to add action listener to buttons.
Please note the comments:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class NestedPanels extends JPanel {
private static final String[] BTN_TEXTS = { "Say Hello", "Say You Look Good", "Say Sorry I'm Late" }; //three buttons
//never used : private static final int TITLE_POINTS = 3;
public NestedPanels() {
JPanel southBtnPanel = new JPanel(new GridLayout(3, 2, 1, 1));
for (String btnText : BTN_TEXTS) {
JButton b = new JButton(btnText);
//add action listener
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
buttonClicked(e);//when button clicked, invoke method
}
});
//alternative much shorter way to add action listener:
//b.addActionListener(e -> buttonClicked());
southBtnPanel.add(b);
}
setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
setLayout(new BorderLayout());
//this adds Box to the default BorderLayout.CENTER position
add(Box.createRigidArea(new Dimension(600, 600)));
add(southBtnPanel, BorderLayout.SOUTH);
}
//respond to button clicked
private void buttonClicked(ActionEvent e) {
String msg = ((JButton)e.getSource()).getActionCommand()+" pressed" ;
JOptionPane.showMessageDialog(this, msg ); //display button Action
}
private static void createAndShowGui() {
NestedPanels mainPanel = new NestedPanels();
JFrame frame = new JFrame("Date Sim 1.0");
//no need to invoke twice frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
//no need to invoke twice frame.pack();
//no need to invoke twice frame.setVisible(true);
frame.getContentPane().add(mainPanel);
/*
* when posting images, use web resources that anyone can access
*
ImageIcon icon = new ImageIcon("C:/Users/wchri/Pictures/10346538_10203007241845278_2763831867139494749_n.jpg");
JLabel label = new JLabel(icon);
*this adds label to the default BorderLayout.CENTER position, which is already taken by
*the Box. Only one (last) component will be added
mainPanel.add(label);
*
*/
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//remove all code which is not essential to the question
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGui();
}
});
}
}
but I have already instantiated a parent class of extending the jpanel
Did you look at the example code provided in the tutorial???
The example there "
... extends JFrame implements ActionListener
So all you need is:
... extends JPanel implements ActionListener
Or in case you need multiple ActionListeners the more flexible approach to create a custom class.
You can use an "annonymous inner class" for the ActionListener. Something like:
ActionListener al = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JButton button = (JButton)e.getSource();
String text = button.getText();
Window window = SwingUtilities.windowForComponent(button);
JOptionPane.showMessageDialog(window, text);
}
};
Then when you create the button you would do:
for (String btnText : BTN_TEXTS)
{
JButton button = new JButton( btnText );
button.addActionListener( al );
southBtnPanel.add( button );
}
I have a JTextArea in a JScrollPane, to which I append messages with display.append(). I am trying to make it scroll automatically by setting the value of the scroll bar to the maximum after appending the text. However, the value of getVerticalScrollBar().getMaximum()doesn't get updated immediately after a line is appended. I have tried to force an update with revalidate(), repaint() and updateUI(), but seem unable to find the right function.
MWE:
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class MessageDisplayPane extends JScrollPane {
private static final long serialVersionUID = 2025745714938834689L;
public static final int NUM_LINES = 5;
private JTextArea display;
private JScrollBar vertical = getVerticalScrollBar();
public MessageDisplayPane() {
display = createTextArea();
setViewportView(display);
}
private JTextArea createTextArea() {
JTextArea ta = new JTextArea(NUM_LINES, 0);
ta.setEditable(false);
ta.setLineWrap(true);
ta.setWrapStyleWord(true);
ta.setFont(new Font("Arial", Font.PLAIN, 12));
ta.setBorder(BorderFactory.createEtchedBorder());
return ta;
}
class EventListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
new Thread() {
#Override
public void run() {
System.out.println(vertical.getMaximum());
display.append("test\r\n");
revalidate();
repaint();
updateUI();
System.out.println(vertical.getMaximum());
System.out.println();
//vertical.setValue(vertical.getMaximum());
}
}.start();
}
}
public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
MessageDisplayPane messagePane = new MessageDisplayPane();
JButton button = new JButton("Display another line");
frame.setSize(800, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.getContentPane().add(button, BorderLayout.CENTER);
frame.getContentPane().add(messagePane, BorderLayout.SOUTH);
button.addActionListener(messagePane.new EventListener());
frame.setVisible(true);
}
});
}
}
A possible solution could be to set the caret position to the end (or the beginning) of your text, something like :
textArea.setCaretPosition (textArea.getText ().length ()); // to scroll to the bottom
textArea.setCaretPosition (0); // to scroll to the top
I used a similar instruction to set caret position to 0, and the scrollbar did automatically scroll to the top, so it should work for you.
in my project i have a scrollpane which can contains various panel, depending by user action.
By the way, i'd like to have each panel of a fixed height, and on add, they should be shown one below the previous. Instead they change their height depending to the number of existing panels.
I wrote a main class with the goal of reproducing current behaviour, and an image which should explain what am I aiming for.
image:
code:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingUtilities;
public class MyClass {
static JScrollPane myScrollPaneContent;
static Box panelContainer;
static int i=0;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run(){
int i=0;
//mainWindow
JFrame mainWindow = new JFrame("MyFrame");
mainWindow.setLayout(new BorderLayout());
mainWindow.setMinimumSize(new Dimension(1050,300));
//panel to be placed in mainwindow (borderlayout.Center)
//contains a menu + scrollpane
JPanel centerPanel = new JPanel();
//Box for myScrollPaneContent
panelContainer = Box.createVerticalBox();
//button for centerPanel
JButton button = new JButton("addPanel");
button.setBackground(Color.green);
button.addMouseListener(new MouseListener() {
#Override
public void mouseReleased(MouseEvent e) {
//nothing
}
#Override
public void mousePressed(MouseEvent e) {
//nothing
}
#Override
public void mouseExited(MouseEvent e) {
//nothing
}
#Override
public void mouseEntered(MouseEvent e) {
//nothing
}
#Override
public void mouseClicked(MouseEvent e) {
addPanel();
}
});
centerPanel.add(button);
myScrollPaneContent = new JScrollPane(panelContainer);
myScrollPaneContent.setPreferredSize(new Dimension(600,250));
myScrollPaneContent.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
//all panels are added to the Box
//the box do not need to be added to scroll pane since it has been given into it s constructor
//the scrollpane is added to the centralpanel
centerPanel.add(myScrollPaneContent);
mainWindow.add(centerPanel,BorderLayout.CENTER);
mainWindow.add(Box.createVerticalGlue(),BorderLayout.SOUTH);
mainWindow.setVisible(true);
}
});
}
public static void addPanel(){
switch(i++){
case 0:
//panel 1 for Box
JPanel one = new JPanel();
JLabel labOne = new JLabel("hello");
one.add(labOne);
one.setPreferredSize(new Dimension(1000,25));
one.setBackground(Color.white);
panelContainer.add(one);
break;
case 1:
//panel 2 for Box
JPanel two = new JPanel();
JLabel labTwo = new JLabel("i am a label");
two.add(labTwo);
two.setPreferredSize(new Dimension(1000,30));
two.setBackground(Color.yellow);
panelContainer.add(two);
break;
case 2:
//panel 3 for Box
JPanel three = new JPanel();
JLabel labThree = new JLabel("Bye bye");
three.add(labThree);
three.setPreferredSize(new Dimension(1000,30));
three.setBackground(Color.gray);
panelContainer.add(three);
break;
case 3:
//panel 4 for Box
JPanel four = new JPanel();
JLabel labFour = new JLabel("boyz");
four.add(labFour);
four.setPreferredSize(new Dimension(1000,30));
four.setBackground(Color.blue);
panelContainer.add(four);
break;
default:
i=0;
break;
}
myScrollPaneContent.revalidate();
myScrollPaneContent.repaint();
}
}
You want something like:
JPanel scrollPaneContainer = new JPanel( new BorderLayout() );
Box panelContainer = Box.createVerticalBox();
scrollPaneContainer.add(panelContainer, BorderLayout.PAGE_START);
JScrollPane myScrollPaneContent = new JScrollPane(scrollPaneContainer);
Now the preferred height of your panelContainer will be respected. If there is any extra spaces it will go to the CENTER. If there is not enough space, the scrollbars will appear.
Also, you should NOT be using static variables. This is the sign of a poorly designed GUI. You should NOT be creating your GUI components in main() method. Look at the demos from the Swing tutorial. They show you how to create a panel to hold the Swing components and then add the panel to the frame.