How to make JLabel consume space when not visible? - java

I have a program which creates 2 Panels and then places a label and two buttons in them. The label is set to invisible setVisible(false) and then the two buttons are added and the frame is packed. When i click the first button, the label is shown, setVisible(true), and the seccond one hides it again, setVisible(false). When i click each button, they move to fill the space of the label as it hides, and move again to get out of the way of the label as it is shown. I want to stop this from happening and have the buttons stay in the same place even when the label is hidden.
Here is the code:
public class MainFrame extends JFrame{
public JLabel statusLabel;
public JButton show;
public JButton hide;
public MainFrame(){
super("MagicLabel");
JPanel topPanel = new JPanel(); //Create Top Panel
statusLabel = new JLabel(""); //Init label
statusLabel.setVisible(false); //Hide label at startup
topPanel.setSize(400, 150); //Set the size of the panel, Doesn't work
topPanel.add(statusLabel); //Add label to panel
JPanel middlePanel = new JPanel(); //Create Middle Panel
show= new JButton("Show"); //Create show button
hide= new JButton("Hide"); //Create hide button
middlePanel.setSize(400, 50); //Set the size of the panel, Doesn't work
middlePanel.add(show); //Add show button
middlePanel.add(hide); //Add hide button
this.add(topPanel, "North"); //Add Top Panel to North
this.add(middlePanel, "Center"); //Add Middle Panel to Center
addActionListeners(); //void:adds action listeners to buttons
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(100, 100, 512, 400);
this.setPreferredSize(new Dimension(400,200)); //Set size of frame, Does work
this.pack();
this.setVisible(true);
}
public void animateInstall(boolean var0){ //Void to show and hide label from action listeners
statusLabel.setVisible(var0);
sendWorkingMessage("Boo!");
}
public void sendWorkingMessage(String message){ //Void to set text of label
this.statusLabel.setForeground(new Color(225, 225, 0));
this.statusLabel.setText(message);
}
void addActionListeners(){
show.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
animateInstall(true);
}
});
hide.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
animateInstall(false);
}
});
}

this.setPreferredSize(new Dimension(400,200));
this.setMinimumSize(new Dimension(400,200));
So pack() cannot interfere.

Use CardLayout. Add the JLabel and empty JPanel. Instead of seting it visible/invisible swap the cards showing the JLabel or the JPanel when necesary.

Extending JFrame is not advisable, better extend JPanel put all your components inside and then add it to a JFrame
You need to learn how to use SwingUtilities.invokeLater(): See example how your should look like
You need to learn about Layout: Tutorial
Very dumb and easy approach in your code would be:
this.statusLabel.setForeground(bgColor); //background color
this.statusLabel.setText(" "); //some number of characters

By default for you frame you are using BorderLayout. You can try to have like:
this.add(topPanel, BorderLayout.NORTH); //Add Top Panel to North
this.add(middlePanel, BorderLayout.SOUTH); //Add Middle Panel to South
rather than at center.
Or you can create an intermediate container panel for these 2 panels, or consider other layout managers like BoxLayout, etc

Related

How to fix a JButton to not take up the whole JFrame

I am a beginner in coding and I am learning Java. I'm busy making a log in system, and I have made a JFrame, but when I add a JButton, it takes up the whole JFrame.
public class LogInSystem extends Application{
#Override
public void start(Stage primaryStage)
{
// Setting the JFrame
JFrame frame = new JFrame("Log in System");
frame.setSize(2000, 2000);
frame.setVisible(true);
// Setting the button
JPanel panel = new JPanel();
Button btn1 = new Button();
btn1.setText("1");
btn1.setBounds(50, 150, 100, 30);
frame.add(btn1);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
It seems like you declare a panel and not adding button into it as well as not adding the panel to the frame. You can try to add your button into panel and panel into frame,
panel.add(btn1);
frame.add(panel);
You can also use some useful layout for a particular panel. For example, BoxLayout, GridLayout and etc. By default, everything is set to be FlowLayout.

JFrame will not load new screen

I have a class that extends JFrame and works by adding in 2 panels with BoxLayout buttons, and one JTabbedPane in the center which displays graphs.
I want one of the buttons to remove all current components in the frame and add new ones.
Here are the methods used.
private void createAndShowGraphs() {
ImageIcon createImageIcon(lsuLettersPath); //simple png file to fill one tab
final JTabbedPane jtp = new JTabbedPane();
JLabel iconLabel = new JLabel();
iconLabel.setOpaque(true);
jtp.addTab(null, icon, iconLabel);
//Here is where the errors begin
JPanel menu = new JPanel();
menu.setLayout(new BoxLayout(menu, BoxLayout.Y_AXIS));
//I want this button to remove all components currently in the JFrame and replace them with new components specified in the createAndShowIntro() method
menu.add(new JButton(new AbstractAction("Intro Pane") {
public void actionPerformed(ActionEvent e) {
//I've also tried putting removeAll in the Intro method
removeAll();
createAndShowIntro();
}
}));
add(jtp, BorderLayout.CENTER);
add(menu, BorderLayout.WEST);
pack();
setVisible(true);
}
private void createAndShowIntro() {
System.out.println("Made it to Intro");
//all I want is a blank JLabel with the String "test" to show up
JPanel test = new JPanel();
test.setLayout(new BorderLayout());
JLabel label = new JLabel();
label.setText("test");
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setVerticalAlignment(SwingConstants.CENTER);
test.add(label);
add(test, BorderLayout.CENTER);
test.revalidate();
label.revalidate();
validate();
test.repaint();
label.repaint();
repaint();
pack();
setVisible(true);
}
When I call createAndShowGraphs() in main() and then hit the 'Intro' button, everything freezes and nothing is actually removed. I know it makes it the Intro method because of the "Made it to Intro" string output to the terminal.
I've tried all kinds of combinations of invalidate(), validate(), revalidate(), repaint() on the labels and on the frame itself. Really frustrated because I don't know how else I'm going to be able to display 3 different screens to switch back and forth between while only actually displaying one at a time.
Thanks for your time.

Toggling between JPanels (hide/show)

I have two JPanels that sit on top of one another. The 'top' panel holds many widgets (JButtons, JTextFields, etc.). One of the buttons will initiate an action to display a number of images.
These images are displayed on the other JPanel. So, when this button is clicked, I want to hide the control panel and display the images panel. Sounds pretty simple.
Here is the code (I've omitted a lot of stuff that I don't think is relevant). In the constructor, if I switch which panel is visible when the app launches, it looks fine either way. When I click the button, I should go from my dark gray control panel to my blue images panel. Except that what happens is my dark gray control panel becomes an empty white panel. Any ideas?
public GUI() {
JFrame frame = new JFrame();
...
JPanel imagesPanel = new ImagesPanel();
imagesPanel.setBackground(Color.BLUE);
imagesPanel.setVisible(false);
frame.getContentPane().add(imagesPanel, BorderLayout.CENTER);
// make a JPanel to hold all of the buttons and text fields
JPanel imagesPanel = new ImagesPanel();
controlPanel.setBackground(Color.DARK_GRAY);
controlPanel.setVisible(true);
frame.getContentPane().add(controlPanel, BorderLayout.CENTER);
...
JButton btnDisplayImages = new JButton("Display Images");
btnDisplayImages.setPreferredSize(standardButtonSize);
btnDisplayImages.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
imagesPanel.setVisible(true);
controlPanel.setVisible(false);
frame.repaint();
frame.setVisible(true);
}
});
// button added to control panel
...
}
Use CardLayout. (docs.oracle.com/javase/tutorial/uiswing/layout/card.html)
final String IMAGES_PANEL = "Images Panel";
final String CONTROL_PANEL = "Control Panel";
CardLayout cardLayout;
JPanel cards;
//Where the components controlled by the CardLayout are initialized:
//Create the "cards".
JPanel card1 = new JPanel();
...
JPanel card2 = new JPanel();
...
//Create the panel that contains the "cards".
cardLayout = new CardLayout();
cards = new JPanel(cardLayout);
cards.add(card1, IMAGES_PANEL);
cards.add(card2, CONTROL_PANEL);
...
//Show images panel
cardLayout.show(cards,IMAGES_PANEL);
...
//Show control panel
cardLayout.show(cards, CONTROL_PANEL);

How to add a ScrollBar at the bottom of the JPanel when using GridLayout?

Hello i wanted to know how to add a ScrollBar at the bottom of a JPanel if i use GridLayout in my desktop app, as far as i know GridLayout only accept as parameter quantity of colums, rows and the horizontal and vertical gap. So how can i add a scroll bar and use it to see the information that's in the JPanel?
Put the JPanel with GridLayout into a JScrollPane. E.G. as seen with the two column GridLayout that displays the labels added to the nested layout example.
If you want the JSrollBar to scroll the JPanel with the gridlayout, then put the grid layout into a scrollpane (remember to extend the scrollable interface)
Read this page of the tutorial to learn how to.
IF you want to use the events from the JScrollBar to change the visible area of your panel then put the panel inside another panel with a JScrollbar on the bottom.
This is an example with a green panel and a scrollbar at the bottom
public class Window extends JFrame {
public Window() {
setPreferredSize(new Dimension(500, 500));
setMinimumSize(new Dimension(500, 500));
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(100, 100));
panel.setBackground(Color.GREEN);
getContentPane().add(panel, BorderLayout.CENTER);
JScrollBar scrollBar = new JScrollBar(JScrollBar.HORIZONTAL);
scrollBar.setMinimum(0);
scrollBar.setMaximum(100);
scrollBar.setBlockIncrement(30);
scrollBar.addAdjustmentListener(new AdjustmentListener() {
#Override
public void adjustmentValueChanged(AdjustmentEvent e) {
System.out.println("Adjustment changed");
}
});
getContentPane().add(scrollBar, BorderLayout.SOUTH);
setVisible(true);
}
public static void main(String[] args) {
new Window();
}
}

JButtons are not resizing to match their preferred size

I am trying to make a menu screen for a game. I've added two buttons, play and exit, and am currently trying to figure out how to resize them. When I run my code the buttons are almost the exact same size (different I imagine because of the text). I'm using BoxLayout for my buttons, and I just read here Why will BoxLayout not allow me to change the width of a JButton but let me change the height? why it would only resize the width or height, but it's not resizing either right now. In my code I use BoxLayout.PAGE_AXIS, I don't know if that makes a difference, but it didn't resize vertically either with BoxLayout.Y_AXIS.
Here's my code:
public class Stage extends JFrame {
/* PRIVATE */
private JButton play, exit;
// Setup the Menu screen.
private void createMenuScreen() {
Container window = getContentPane();
// window.setBackground(Color.BLACK);
JPanel menuScreen = new JPanel();
menuScreen.setLayout(new BoxLayout(menuScreen, BoxLayout.PAGE_AXIS));
window.add(menuScreen, "Center");
play = new JButton("Play");
play.setPreferredSize(new Dimension(20, 20));
play.setAlignmentX(Component.CENTER_ALIGNMENT);
exit = new JButton("Exit");
exit.setPreferredSize(new Dimension(100, 100));
exit.setAlignmentX(Component.CENTER_ALIGNMENT);
menuScreen.add(play);
menuScreen.add(exit);
}
/* PUBLIC */
public Stage() {
// Setup the frame.
setSize(224, 288);
setLocationRelativeTo(null); // Centers the window.
setUndecorated(true); // Removes the Windows border.
setVisible(true);
createMenuScreen();
}
}
Try to use setMaximumSize() method
exit.setMaximumSize(new Dimension(100,100));
Or try to use BorderLayout instead of BoxLayout

Categories