JFrame background not changing [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I've got a simple program to change the background of a JFrame and the foreground of a JLabel. The JFrame has a JLabel and 2 JButtons on it, one to change the words and the other to change the background.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class ColorChooserDemo extends JPanel {
static JFrame frame;
JLabel label;
JButton button1, button2;
public ColorChooserDemo() {
this.setBackground(new Color(255, 0, 255));
setLayout(null);
label = new JLabel("This is Text");
button1 = new JButton("Set Word Color");
button2 = new JButton("Set Background Color");
add(label);
add(button1);
add(button2);
label.setBounds(130, 10, 111, 15);
button1.setBounds(100, 40, 200, 35);
button2.setBounds(70, 90, 250, 35);
button1.addActionListener(buttonPressed);
button2.addActionListener(buttonPressed);
button1.setActionCommand("words");
button2.setActionCommand("back");
label.setFont(new Font("Helvetica", Font.BOLD, 20));
button1.setFont(new Font("Helvetica", Font.BOLD, 20));
button2.setFont(new Font("Helvetica", Font.BOLD, 20));
}
AbstractAction buttonPressed = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("words")) {
Color c = JColorChooser.showDialog(null, "Choose a Color", label.getForeground());
if (c != null)
label.setForeground(c);
}
if (e.getActionCommand().equals("back")) {
Color c = JColorChooser.showDialog(null, "Choose a Color", label.getForeground());
if (c != null)
frame.getContentPane().setBackground(c);
}
repaint();
}
};
public static void main(String[] args) {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
frame = new JFrame("ColorChooserDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ColorChooserDemo());
frame.setSize(400, 200);
frame.setLocation((int) (screenSize.getWidth() - 400) / 2, (int) (screenSize.getHeight() - 200) / 2);
frame.setResizable(false);
frame.setVisible(true);
}
}
For whatever reasonframe.getContentPane().setBackground(c); doesn't work.
I've looked for solutions but nothing is working and I don't understand why. Please help.
--EDIT--
I tried repaint(); and it still doesn't work. Could it have to do with frame being static?

This is a good example of where something like static can stab you in the back...
So, in your code, you are doing...
frame.getContentPane().setBackground(c);
when you want to change the background color, but you have to ask yourself the question, what is the contentPane? Since your component extends from JPanel (which is opaque) and sets it's own background color (this.setBackground(new Color(255, 0, 255));) (and because by default JFrame uses a BorderLayout) you component is covering the entire content area of the frame, so any calls to frame.getContentPane().setBackground(c) are simply not visible (because your panel is covering it).
Instead, you should simple use...
setBackground(c);
For clarification...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class ColorChooserDemo extends JPanel {
JLabel label;
JButton button1, button2;
public ColorChooserDemo() {
this.setBackground(new Color(255, 0, 255));
setLayout(new GridBagLayout());
label = new JLabel("This is Text");
button1 = new JButton("Set Word Color");
button2 = new JButton("Set Background Color");
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(label, gbc);
add(button1, gbc);
add(button2, gbc);
button1.addActionListener(buttonPressed);
button2.addActionListener(buttonPressed);
button1.setActionCommand("words");
button2.setActionCommand("back");
label.setFont(new Font("Helvetica", Font.BOLD, 20));
button1.setFont(new Font("Helvetica", Font.BOLD, 20));
button2.setFont(new Font("Helvetica", Font.BOLD, 20));
}
AbstractAction buttonPressed = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("words")) {
Color c = JColorChooser.showDialog(null, "Choose a Color", label.getForeground());
if (c != null) {
label.setForeground(c);
}
}
if (e.getActionCommand().equals("back")) {
System.out.println("...");
Color c = JColorChooser.showDialog(null, "Choose a Color", getBackground());
if (c != null) {
setBackground(c);
}
}
repaint();
}
};
public static void main(String[] args) {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
JFrame frame = new JFrame("ColorChooserDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ColorChooserDemo());
frame.setSize(400, 200);
frame.setLocation((int) (screenSize.getWidth() - 400) / 2, (int) (screenSize.getHeight() - 200) / 2);
frame.setResizable(false);
frame.setVisible(true);
}
}
I would also strongly suggest you have a look at Laying Out Components Within a Container, How to Use GridBagLayout and How to Use BorderLayout for more details about how the layou management API works

Related

Why doesn't a panel with GridBagLayout show the content?

I wrote a little something here. It's working if I don't backPanel.setLayout(new GridBagLayout);
But without the grid bag, the content stays in the top left I maximise the screen.
With the grid bag I only get the red backPanel in the frame. Well, there is a gray pixel in the middle of the screen. I'm assuming that's my panel, but I can't make it bigger. I tried setSize but it doesn't change. Also, I had the panel.setBounds(0, 0, getWidth(),getHeight());. I'm not sure why I removed it.
My main is in the other file. The only thing it does at the moment is to call the LoginFrame.
Here is the code:
package first;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
public class LoginFrame extends JFrame implements ActionListener {
private JTextField textField;
private JPasswordField passwordField;
public LoginFrame() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(500, 300);
JPanel backPanel = new JPanel(new GridBagLayout());
backPanel.setBackground(Color.RED);
JPanel panel = new JPanel();
panel.setSize(500, 300);
panel.setBackground(Color.LIGHT_GRAY);
panel.setLayout(null);
JLabel label;
panel.add(label = new JLabel("Username:"));
label.setBounds(20, 100, 100, 25);
panel.add(textField = new JTextField());
textField.setBounds(140, 100, 200, 25);
panel.add(label = new JLabel("Password:"));
label.setBounds(20, 145, 100, 25);
panel.add(passwordField = new JPasswordField());
passwordField.setBounds(140, 145, 200, 25);
panel.add(label = new JLabel("CTC Bank"));
label.setFont(new Font("New Times Roman", Font.BOLD, 50));
label.setBounds(0, 0, getWidth(), 100);
label.setHorizontalAlignment(JLabel.CENTER);
JButton button;
panel.add(button = new JButton("Login"));
button.setBounds(140, 200, 100, 25);
button.addActionListener(this);
button = defaultActionKeyEnter(button, KeyEvent.VK_ENTER);
panel.add(button = new JButton("Register"));
button.setBounds(240, 200, 100, 25);
button.addActionListener(this);
button = defaultActionKeyEnter(button, KeyEvent.VK_ENTER);
//add(panel);
backPanel.add(panel);
add(backPanel, BorderLayout.CENTER);
revalidate();
repaint();
setLocationRelativeTo(null);
setVisible(true);
}
public static JButton defaultActionKeyEnter(JButton button, int desiredKeyCode) {
InputMap inputMap = button.getInputMap(JComponent.WHEN_FOCUSED);
KeyStroke spaceKeyPressed = KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, false);
KeyStroke spaceKeyReleased = KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, true);
KeyStroke desiredKeyPressed = KeyStroke.getKeyStroke(desiredKeyCode, 0, false);
KeyStroke desiredKeyReleased = KeyStroke.getKeyStroke(desiredKeyCode, 0, true);
inputMap.put(desiredKeyPressed, inputMap.get(spaceKeyPressed));
inputMap.put(desiredKeyReleased, inputMap.get(spaceKeyReleased));
inputMap.put(spaceKeyPressed, "none");
inputMap.put(spaceKeyReleased, "none");
return button;
}
// Unfinished code dont worry bout it...
#Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Login")) {
if (textField.getText().equals("Heinz")
&& (new String(passwordField.getPassword()).equals("password123"))) {
// color = Color.GREEN;
} else {
JOptionPane.showMessageDialog(this, "Wrong Username or Password", "Error", JOptionPane.WARNING_MESSAGE);
// color = Color.RED;
}
} else {
JOptionPane.showMessageDialog(this, "Cya");
dispose();
setVisible(false);
}
// panel.setBackground(color);
}
}
I have seen questions about this but none of the answers were helpful in my case.
Calling the following didn't help.
revalidate();
repaint();
Did I maybe add it in the wrong order?
And how does the code look like to you? Would you consider this clean?
The layout of backPanel will mis-calculate the dimensions of "panel" because "panel" does not participate in layout management properly, without a layout manager of its own.
One solution to this is to use setLayout(null) also on the "backPanel", or add "panel" directly to the JFrame.
With the first suggestion ("backPanel.setLayout(null);" just after it is created), plus the following main method:
public static void main(String[] args) {
new LoginFrame();
}
I get this:

JPanel gets compressed and disappears when trying to move to the bottom

I have to do a project in Java and thought a GUI Text Adventure would be cool. My Problem is that when I create a JPanel and move it further down on the screen, the panel first changes its size and then disappears completely at one point.
On the GameScreen there should be a panel for choice Options to be put on but it refuses to go further down than about half the size of the Screen.
Here's the code:
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class Yeet {
JFrame epicOfYeet;
Container con;
JPanel titleNamePanel, startButtonPanel, mainTextPanel, choiceButtonPanel;
JLabel titleNameLabel;
Font titleFont = new Font("Times New Roman", Font.PLAIN, 90);
Font normalFont = new Font ("Times New Roman", Font.PLAIN, 55);
JButton startButton;
JButton choice1;
JButton choice2;
JButton choice3;
JButton choice4;
JTextArea mainTextArea;
TitleScreenHandler tsHandler = new TitleScreenHandler();
public static void main(String[] args) {
new Yeet();
}
public Yeet() {
epicOfYeet = new JFrame();
epicOfYeet.setSize(1200, 1000);
epicOfYeet.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
epicOfYeet.getContentPane().setBackground(Color.black);
epicOfYeet.setLayout(null);
con = epicOfYeet.getContentPane();
titleNamePanel = new JPanel();
titleNamePanel.setBounds(190, 100, 800, 230);
titleNamePanel.setBackground(Color.black);
titleNameLabel = new JLabel("EPIC OF YEET");
titleNameLabel.setForeground(Color.red);
titleNameLabel.setFont(titleFont);
startButtonPanel = new JPanel();
startButtonPanel.setBounds(400, 500, 400, 100);
startButtonPanel.setBackground(Color.black);
startButton = new JButton("START");
startButton.setBackground(Color.black);
startButton.setForeground(Color.white);
startButton.setFont(normalFont);
startButton.addActionListener(tsHandler);
startButton.setFocusPainted(false);
titleNamePanel.add(titleNameLabel);
startButtonPanel.add(startButton);
con.add(titleNamePanel);
con.add(startButtonPanel);
epicOfYeet.setVisible(true);
}
public void createGameScreen(){
titleNamePanel.setVisible(false);
startButtonPanel.setVisible(false);
mainTextPanel = new JPanel();
mainTextPanel.setBounds(100, 100, 1000, 400);
mainTextPanel.setBackground(Color.green);
con.add(mainTextPanel);
mainTextArea = new JTextArea("You come to your senses again.\nThe dewy grass you're laying on is gleaming with moonlight.\nYour body aches as you get up and catch a \nglimpse of your surroundings.\n");
mainTextArea.setBounds(100, 100, 1000, 250);
mainTextArea.setBackground(Color.blue);
mainTextArea.setForeground(Color.white);
mainTextArea.setFont(normalFont);
mainTextArea.setLineWrap(true);
mainTextPanel.add(mainTextArea);
choiceButtonPanel = new JPanel();
choiceButtonPanel.setBounds(300, 500, 600, 550);
choiceButtonPanel.setBackground(Color.red);
con.add(choiceButtonPanel);
}
public class TitleScreenHandler implements ActionListener{
#Override
public void actionPerformed(ActionEvent event) {
createGameScreen();
}
}
}
Here is a basic implementation using layout mangers, avoiding the bad practice of null layout manager.
It is not an optimal one, but should get you started:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class Yeet {
JFrame epicOfYeet;
Container con;
JPanel titleNamePanel, startButtonPanel, mainTextPanel, choiceButtonPanel;
JLabel titleNameLabel;
Font titleFont = new Font("Times New Roman", Font.PLAIN, 90);
Font normalFont = new Font ("Times New Roman", Font.PLAIN, 55);
JButton startButton, coice1, choice2, choice3, choice4;
JTextArea mainTextArea;
TitleScreenHandler tsHandler = new TitleScreenHandler();
public static void main(String[] args) {
SwingUtilities.invokeLater(()->new Yeet());
}
public Yeet() {
epicOfYeet = new JFrame();
//epicOfYeet.setSize(1200, 1000); // do not set size. let layout manager calcualte it
epicOfYeet.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
epicOfYeet.getContentPane().setBackground(Color.black);
//epicOfYeet.setLayout(null); //aviod null layouts Jframe uses BorderLayout by default
con = epicOfYeet.getContentPane();
titleNamePanel = new JPanel();
//titleNamePanel.setBounds(190, 100, 800, 230);
titleNamePanel.setPreferredSize(new Dimension(800, 230));//set preferred size to be used by layout manager
titleNamePanel.setBackground(Color.black);
titleNameLabel = new JLabel("EPIC OF YEET");
titleNameLabel.setForeground(Color.red);
titleNameLabel.setFont(titleFont);
startButtonPanel = new JPanel();
//startButtonPanel.setBounds(400, 500, 400, 100);
startButtonPanel.setPreferredSize(new Dimension(400, 100));
startButtonPanel.setBackground(Color.black);
startButton = new JButton("START");
startButton.setBackground(Color.black);
startButton.setForeground(Color.white);
startButton.setFont(normalFont);
startButton.addActionListener(tsHandler);
startButton.setFocusPainted(false);
titleNamePanel.add(titleNameLabel);
startButtonPanel.add(startButton);
con.add(titleNamePanel, BorderLayout.PAGE_START); //set to top
con.add(startButtonPanel, BorderLayout.PAGE_END); //set to bottom
epicOfYeet.pack();
epicOfYeet.setVisible(true);
}
public void createGameScreen(){
//titleNamePanel.setVisible(false);
//startButtonPanel.setVisible(false);
con.remove(titleNamePanel);
con.remove(startButtonPanel);
mainTextPanel = new JPanel();
//mainTextPanel.setBounds(100, 100, 1000, 400);
mainTextPanel.setBackground(Color.green);
con.add(mainTextPanel); // added to center position of the BorderLayout (the default)
mainTextArea = new JTextArea(10, 20); //size in rows, cols
mainTextArea.setText("You come to your senses again.\nThe dewy grass you're laying on is gleaming with moonlight.\nYour body aches as you get up and catch a \nglimpse of your surroundings.\n");
//mainTextArea.setBounds(100, 100, 1000, 250);
mainTextArea.setBackground(Color.blue);
mainTextArea.setForeground(Color.white);
mainTextArea.setFont(normalFont);
mainTextArea.setLineWrap(true);
mainTextPanel.add(mainTextArea);
choiceButtonPanel = new JPanel();
//choiceButtonPanel.setBounds(300, 500, 600, 550);
choiceButtonPanel.setPreferredSize(new Dimension(600, 550));
choiceButtonPanel.setBackground(Color.red);
con.add(choiceButtonPanel, BorderLayout.PAGE_END);//add to bottom
epicOfYeet.pack();
}
public class TitleScreenHandler implements ActionListener{
#Override
public void actionPerformed(ActionEvent event) {
createGameScreen();
}
}
}

Java swing gui change background of jlabel and make it reset

I have a gui that has:
a label at the top
a JFrame at the bottom with 2 Buttons called left and right
a panel in center that is gridlayout with 2 JLabel to either display an image or change the back ground color. (currently the background color is set to black for both jLabels).
*what I would like to happen.
When you click on button "left" the image appears on lblPicture1 and lblPicture2 has a black background and no image. and vise versa for the right button. and when you click on the left again, it repeats this cycle.
I accomplish that however, when i click the left and right button I just have two images and neither one has a black background.
I belive this is due to the image not resetting.
Can you direct me to the right place on how I can get this to work?
Thank you
package gui;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.GridLayout;
import javax.swing.ImageIcon;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class ExampleGUI extends JFrame {
private JPanel contentPane;
private JLabel lblPicture1;
private JLabel lblPicture2;
private int change;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ExampleGUI frame = new ExampleGUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ExampleGUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JLabel lblExampleGui = new JLabel("Example GUI");
lblExampleGui.setBorder(new EmptyBorder(8, 0, 8, 0));
lblExampleGui.setFont(new Font("Lucida Grande", Font.PLAIN, 24));
lblExampleGui.setHorizontalAlignment(SwingConstants.CENTER);
contentPane.add(lblExampleGui, BorderLayout.NORTH);
JPanel panelButton = createPanelButton();
contentPane.add(panelButton, BorderLayout.SOUTH);
JButton btnLeft = createBtnLeft();
panelButton.add(btnLeft);
JButton btnRight = createBtnRight();
panelButton.add(btnRight);
JPanel panelCenter = createPanelCenter();
contentPane.add(panelCenter, BorderLayout.CENTER);
JLabel lblPicture1 = createLblPicture1();
panelCenter.add(lblPicture1);
JLabel lblPicture2 = createPicture2();
panelCenter.add(lblPicture2);
}
public JLabel createPicture2() {
lblPicture2 = new JLabel();
lblPicture2.setOpaque(true);
lblPicture2.setBackground(Color.BLACK);
return lblPicture2;
}
public JLabel createLblPicture1() {
lblPicture1 = new JLabel();
lblPicture1.setOpaque(true);
lblPicture1.setBackground(Color.BLACK);
//lblPicture1.setIcon(new ImageIcon(ExampleGUI.class.getResource("/gui/schlange.gif")));
return lblPicture1;
}
public JPanel createPanelCenter() {
JPanel panelCenter = new JPanel();
panelCenter.setLayout(new GridLayout(0, 2, 8, 0));
return panelCenter;
}
public JButton createBtnRight() {
JButton btnRight = new JButton("right");
btnRight.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//TODO
lblPicture1.setBackground(Color.BLACK);
lblPicture2.setIcon(new ImageIcon(ExampleGUI.class.getResource("/gui/schlange.gif")));
}
});
btnRight.setFont(new Font("Lucida Grande", Font.PLAIN, 14));
return btnRight;
}
public JButton createBtnLeft() {
JButton btnLeft = new JButton("left");
btnLeft.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//TODO
lblPicture2.setBackground(Color.BLACK);
lblPicture1.setIcon(new ImageIcon(ExampleGUI.class.getResource("/gui/schlange.gif")));
}
});
btnLeft.setFont(new Font("Lucida Grande", Font.PLAIN, 14));
return btnLeft;
}
public JPanel createPanelButton() {
JPanel panelButton = new JPanel();
return panelButton;
}
}
The background is painted beneath the icon, so if the icon is not reset, then it will continue to be displayed.
You can simply set the icon property by passing it null, for example
public JButton createBtnLeft() {
JButton btnLeft = new JButton("left");
btnLeft.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//TODO
lblPicture2.setIcon(null);
lblPicture2.setBackground(Color.BLACK);
lblPicture1.setIcon(new ImageIcon(ExampleGUI.class.getResource("/gui/schlange.gif")));
}
});
btnLeft.setFont(new Font("Lucida Grande", Font.PLAIN, 14));
return btnLeft;
}

Having a JTextField popup at a certain location after clicking a JButton

I have my three JButtons located where I want them (at the top center of the frame), and when the user clicks one, a JTextField pops up in the BoxLayout like wanted.
The problem is, when the JTextField shows up, it is to the left of the buttons, and it moves them.
I tried setting the alignment of the JTextField and using various glues, but the JTextField doesn't move.
If I want to have the JTextField pop up below my JButtons and in the center of the screen, what should I use?
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
public class Library extends JFrame implements ActionListener {
private JFrame jf1;
private JPanel jp1;
private JTextField jtf1;
private JButton jb1;
private JButton jb2;
private JButton jb3;
public Library() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(Exception q) {
q.printStackTrace();
}
JFrame.setDefaultLookAndFeelDecorated(false);
jf1 = new JFrame("Library");
jf1.setVisible(true);
jf1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf1.setSize(1080, 900);
jf1.setResizable(true);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
jf1.setLocation(dim.width/2-jf1.getSize().width/2, dim.height/2-jf1.getSize().height/2);
jp1 = (JPanel) jf1.getContentPane();
jp1.setLayout(new BoxLayout(jp1, BoxLayout.LINE_AXIS));
jb1 = new JButton("Genre");
jb1.addActionListener(this);
jb1.setMinimumSize(new Dimension(140, 60));
jb1.setPreferredSize(new Dimension(150, 60));
jb1.setMaximumSize(new Dimension(150, 60));
jb1.setAlignmentY(-70.0f);
jb2 = new JButton("Author");
jb2.addActionListener(this);
jb2.setMinimumSize(new Dimension(140, 60));
jb2.setPreferredSize(new Dimension(150, 60));
jb2.setMaximumSize(new Dimension(150, 60));
jb2.setAlignmentY(-70.0f);
jb3 = new JButton("Title");
jb3.addActionListener(this);
jb3.setMinimumSize(new Dimension(140, 60));
jb3.setPreferredSize(new Dimension(150, 60));
jb3.setMaximumSize(new Dimension(150, 60));
jb3.setAlignmentY(-70.0f);
jp1.add(Box.createHorizontalGlue());
jp1.add(jb1);
jp1.add(jb2);
jp1.add(jb3);
jp1.add(Box.createHorizontalGlue());
jf1.validate();
}
#Override
public void actionPerformed(ActionEvent e) {
Object code = e.getSource();
if (code == jb1) {
jtf1 = new JTextField("Enter Text");
jtf1.setPreferredSize(new Dimension(200,20));
jtf1.setMaximumSize(new Dimension(200,20));
jtf1.setMinimumSize(new Dimension(10,10));
jp1.add(jtf1);
jp1.validate();
}
else if (code == jb2) {
}
else if (code == jb3) {
}
}
public static void main(String[] args) {
Library shoe = new Library();
}
}
Suggestion: do not add/remove UI elements dynamically. Just add all of those things initially, and simply call setVisible(false) on your text field then.
(instead of adding/removing fields using your action listener)
A good and easy solution may be to use another JPanel to hold your dynamically created text fields. This may be what you wanted:
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
public class Library extends JFrame implements ActionListener {
private JFrame jf1;
private JPanel jp1;
private JPanel jp2;
private JTextField jtf1;
private JButton jb1;
private JButton jb2;
private JButton jb3;
public Library() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(Exception q) {
q.printStackTrace();
}
JFrame.setDefaultLookAndFeelDecorated(false);
jf1 = new JFrame("Library");
jf1.setVisible(true);
jf1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf1.setSize(1080, 900);
jf1.setResizable(true);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
jf1.setLocation(dim.width/2-jf1.getSize().width/2, dim.height/2-jf1.getSize().height/2);
jp1 = new JPanel();
jp1.setLayout(new BoxLayout(jp1, BoxLayout.LINE_AXIS));
jp2 = new JPanel();
jp2.setLayout(new BoxLayout(jp2, BoxLayout.LINE_AXIS));
jb1 = new JButton("Genre");
jb1.addActionListener(this);
jb1.setMinimumSize(new Dimension(140, 60));
jb1.setPreferredSize(new Dimension(150, 60));
jb1.setMaximumSize(new Dimension(150, 60));
jb1.setAlignmentY(-70.0f);
jb2 = new JButton("Author");
jb2.addActionListener(this);
jb2.setMinimumSize(new Dimension(140, 60));
jb2.setPreferredSize(new Dimension(150, 60));
jb2.setMaximumSize(new Dimension(150, 60));
jb2.setAlignmentY(-70.0f);
jb3 = new JButton("Title");
jb3.addActionListener(this);
jb3.setMinimumSize(new Dimension(140, 60));
jb3.setPreferredSize(new Dimension(150, 60));
jb3.setMaximumSize(new Dimension(150, 60));
jb3.setAlignmentY(-70.0f);
jp1.add(Box.createHorizontalGlue());
jp1.add(jb1);
jp1.add(jb2);
jp1.add(jb3);
jp1.add(Box.createHorizontalGlue());
jf1.getContentPane().add(jp1);
jp1.setBounds(0, 0, 1080, 900);
jf1.getContentPane().add(jp2);
jp2.setBounds(0, 0, 1080, 900);
validate();
}
public void actionPerformed(ActionEvent e) {
Object code = e.getSource();
if (code == jb1) {
jtf1 = new JTextField("Enter Text");
jtf1.setPreferredSize(new Dimension(200,20));
jtf1.setMaximumSize(new Dimension(200,20));
jtf1.setMinimumSize(new Dimension(10,10));
jp2.add(Box.createHorizontalGlue());
jp2.add(jtf1);
jp2.add(Box.createHorizontalGlue());
jp2.validate();
}
else if (code == jb2) {
}
else if (code == jb3) {
}
}
public static void main(String[] args) {
Library shoe = new Library();
}
}
I gave it a quick try to solve the issue. Hope it helps. Do more tweaking in your code to perfectly match the layout.

Adding 2 JLists to a JPanel using BorderLayout

I need to add 2 JLists inside a JPanel for a crossword. The JPanel is located SOUTH and I'm using BorderLayout in the constructor to locate the JPanel.
The problem is, I can't see the 2 JLists inside the JPanel
package crossword;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Main extends JFrame implements MouseListener {
Container container;
//this is the constructor
public Main(){
super("Crossword");
container = getContentPane();
container.setLayout(new BorderLayout(1, 1));
container.setBackground(new Color(91,119,162));
container.add(login(),BorderLayout.NORTH);
container.add(buttons(),BorderLayout.WEST);
container.add(clues(),BorderLayout.SOUTH);
container.add(createMatrix(crosswordPanel()),BorderLayout.CENTER);
container.add(eastPanel(),BorderLayout.EAST);
}
public JPanel login(){
JPanel loginPanel = new JPanel();
loginPanel.setLayout(new FlowLayout(1, 15, 5));
loginPanel.setPreferredSize(new Dimension(8, 40));
loginPanel.setBackground(new Color(47,47,47));
loginPanel.setVisible(true);
JTextField inputUserName = new JTextField(15);
loginPanel.add(inputUserName);
JButton btnEnter = new JButton("Play!");
btnEnter.setPreferredSize(new Dimension(80,25));
loginPanel.add(btnEnter);
return loginPanel;
}
public JPanel buttons(){
JPanel buttonsPanel = new JPanel();
buttonsPanel.setLayout(new FlowLayout(5, 45, 15));
buttonsPanel.setPreferredSize(new Dimension(250, 200));
buttonsPanel.setBackground(new Color(91,119,162));
buttonsPanel.setVisible(true);
JButton newGame = new JButton("New game");
newGame.setPreferredSize(new Dimension(130,27));
newGame.setFont(new Font("Tahoma", Font.PLAIN, 11));
buttonsPanel.add(newGame);
JButton showChar = new JButton("Reveal letter");
showChar.setPreferredSize(new Dimension(130,27));
showChar.setFont(new Font("Tahoma", Font.PLAIN, 11));
buttonsPanel.add(showChar);
JButton showWord = new JButton("Reveal word");
showWord.setPreferredSize(new Dimension(130,27));
showWord.setFont(new Font("Tahoma", Font.PLAIN, 11));
buttonsPanel.add(showWord);
JButton verifyWord = new JButton("Verify");
verifyWord.setPreferredSize(new Dimension(130,27));
verifyWord.setFont(new Font("Tahoma", Font.PLAIN, 11));
buttonsPanel.add(verifyWord);
JButton revealAll = new JButton("Solution");
revealAll.setPreferredSize(new Dimension(130,27));
revealAll.setFont(new Font("Tahoma", Font.PLAIN, 11));
buttonsPanel.add(revealAll);
JLabel labelScore = new JLabel("Score:");
labelScore.setFont(new Font("Arial", Font.BOLD, 13));
buttonsPanel.add(labelScore);
return buttonsPanel;
}
public JPanel clues(){
JPanel clues = new JPanel();
clues.setLayout(new FlowLayout(3, 1, 1));
clues.setPreferredSize(new Dimension(200, 200));
clues.setBackground(new Color(91,119,162));
clues.setVisible(true);
JList horizontalList = new JList();
horizontalList.setBackground(Color.BLUE);
horizontalList.setBorder(BorderFactory.createEtchedBorder(1));
clues.add(horizontalList);
JList verticalList = new JList();
verticalList.setBackground(Color.ORANGE);
verticalList.setBorder(BorderFactory.createEtchedBorder(1));
clues.add(verticalList);
return clues;
}
public JPanel eastPanel(){
JPanel fill = new JPanel();
fill.setLayout(new FlowLayout(5, 25, 15));
fill.setPreferredSize(new Dimension(50, 200));
fill.setBackground(new Color(91,119,162));
fill.setVisible(true);
return fill;
}
public JPanel crosswordPanel(){
JPanel crosswordPanel = new JPanel();
crosswordPanel.setLayout(new GridLayout(10,10,0,0));
crosswordPanel.setBackground(Color.white);
//crosswordPanel.setPreferredSize(new Dimension(200, 200));
crosswordPanel.setBackground(new Color(91,119,162));
crosswordPanel.setVisible(true);
return crosswordPanel;
}
public JPanel createMatrix(JPanel crosswordPanel){
JPanel crosswordMatrix [][] = new JPanel [10][10];
for (int i = 0; i < crosswordMatrix.length ; i++) {
for (int j = 0; j < crosswordMatrix[0].length; j++) {
crosswordMatrix[i][j] = new JPanel();
crosswordMatrix[i][j].setBackground(Color.lightGray);
crosswordMatrix[i][j].setBorder(BorderFactory.createLineBorder(Color.black, 1));
crosswordMatrix[i][j].addMouseListener(this);
//crosswordMatrix[i][j].add(label);
crosswordPanel.add(crosswordMatrix[i][j]);
}
}
return crosswordPanel;
}
public static void main(String[] args) {
Main guiWindow = new Main();
Toolkit screenSize = Toolkit.getDefaultToolkit();
int width = screenSize.getScreenSize().width * 4/5;
int height = screenSize.getScreenSize().height * 4/5;
guiWindow.setSize(width, height);
guiWindow.setLocationRelativeTo(null);
guiWindow.setVisible(true);
guiWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Its not an MCVE, but based upon the limited code you posted: in the clues method a JPanel is constructed, yet nothing is ever added to it. Rather, you add the JLists directly to the object which contains the method (which I presume this extends JFrame). Perhaps try adding the components to the JPanel
public JPanel clues(){
JPanel clues = new JPanel();
...
clues.add(horizontalList);
....
clues.add(verticalList);
}

Categories

Resources