Adding a JScrollPane to an existing JPanel - java

I am trying to add a JScrollPane (createTeamScrollPane) to a JPanel (createTeamPanel) that I have. I have a frame, with a BorderLayout with the NORTH portion being used by a JPanel called tabMenu, and then the CENTER portion I would like my 'createTeamPanel' to have this scrolling ability as it will have more content than what I can fit on the screen at once. I am then adding both panels to the frame. Currently the code as is runs but the window appears blank. Once resizing the window, I then see the 3 buttons in the NORTH portion of my frame (why is this happening?) and when I click on 'Create Team' it brings up the list of JLabels and JButtons I expect but I don't see any scrolling bars?
public static void main (String args[]) {
JFrame frame = new JFrame();
frame.setTitle("v0.01");
frame.setSize(800, 800);
//frame.setLayout(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
JPanel tabMenu = new JPanel();
JPanel createTeamPanel = new JPanel();
createTeamPanel.setLayout(new BoxLayout(createTeamPanel, BoxLayout.Y_AXIS));
createTeamPanel.setSize(800, 700);
createTeamPanel.setVisible(showCreateTeamPanel);
createTeamPanel.setBackground(Color.gray);
JScrollPane createTeamScrollPane = new JScrollPane(createTeamPanel);
createTeamScrollPane.setBounds(50, 50, 200, 500);
createTeamScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
createTeamScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
createTeamScrollPane.setPreferredSize(new Dimension(500,500));
//createTeamPanel.add(createTeamScrollPane);
List<Player> teamList = MockTeams.initTeam();
int xcoord = 100;
int ycoord = 50;
for(Player player : teamList) {
JLabel label = new JLabel(player.getName());
label.setBounds(xcoord, ycoord, Constants.buttonWidth, Constants.buttonHeight);
JButton addToTeamBtn = new JButton("Add to team");
addToTeamBtn.setBounds(xcoord + 100, ycoord, Constants.buttonWidth, Constants.buttonHeight);
addToTeamBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
myTeam.add(player);
addToTeamBtn.setEnabled(false);
}
});
createTeamPanel.add(label);
//createTeamFrame.add(label);
createTeamPanel.add(addToTeamBtn);
//createTeamFrame.add(addToTeamBtn);
ycoord += 50;
}
JButton createTeamBtn = new JButton("Create Team");
createTeamBtn.setBounds(0,0,150,20);
createTeamBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Hide/Show Create team panel
if (!showCreateTeamPanel) {
showCreateTeamPanel = true;
createTeamPanel.setVisible(showCreateTeamPanel);
} else {
showCreateTeamPanel = false;
createTeamPanel.setVisible(showCreateTeamPanel);
}
}
});
JButton manageTeamBtn = new JButton("Team Statistics");
manageTeamBtn.setBounds(100,150,150,40);
JButton resetBtn = new JButton("Reset Season");
resetBtn.setBounds(100,200,150,40);
tabMenu.add(createTeamBtn);
tabMenu.add(manageTeamBtn);
tabMenu.add(resetBtn);
mainPanel.add(tabMenu, BorderLayout.NORTH);
mainPanel.add(createTeamPanel, BorderLayout.CENTER);
frame.add(mainPanel);
}
Expected result is to see a scrolling ability on the createTeamPanel but it is not there.

Fixed: I was able to add the JScrollPane to the mainPanel with:
mainPanel.add(createTeamScrollPane, BorderLayout.CENTER);

Related

How to add JScrollPane to my JFrame? [duplicate]

I have following source code...Can someone please give me an advice how to add jscrollpane onto jframe? I tried several time to add it to jframe but without any progress. It is not even showing.
public class Form3 {
JFrame jframe = new JFrame("Etiket print.");
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
JScrollPane scrollFrame = new JScrollPane(panel2);
Color myBlue1Color = new Color(168, 175, 247);
Color myBlue2Color = new Color(139, 146, 255);
public Form3(){
jframe.setMinimumSize(new Dimension(1280, 1000));
panel2.setLayout(new BoxLayout(panel2, BoxLayout.Y_AXIS));
panel2.setAutoscrolls(true);
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//---------------------------------Header
panel1 = createSquareJPanel(Color.YELLOW, 600,200);
panel3 = createSquareJPanel(Color.GREEN, 400,200);
panel4 = createSquareJPanel(Color.white, 280,200);
JPanel container = new JPanel();
JPanel container1 = new JPanel();
JPanel container2 = new JPanel();
container.setLayout(new BoxLayout(container, BoxLayout.Y_AXIS));
container1.setLayout(new BoxLayout(container1, BoxLayout.Y_AXIS));
container2.setLayout(new BoxLayout(container2, BoxLayout.X_AXIS));
container1.add(panel1);
container2.add(container1);
container2.add(panel3);
container2.add(panel4);
container.add(container2);
container.add(panel2);
{
for (int i=0; i<25; i++){
JPanel harnessPanel= new JPanel();
harnessPanel.setMinimumSize(new Dimension(1280, 70));
harnessPanel.setMaximumSize(new Dimension(1280, 70));
harnessPanel.setPreferredSize(new Dimension(1280, 70));
if(i%2==0) {
harnessPanel.setBackground(myBlue1Color);
}
else {
harnessPanel.setBackground(myBlue2Color);
}
panel2.add(harnessPanel);
harnessPanel.repaint();
harnessPanel.validate();
}
panel2.repaint();
panel2.validate();
}
jframe.add(scrollFrame);
jframe.add(container);
jframe.pack();
jframe.setLocationRelativeTo(null);
jframe.setVisible(true);
}
private JPanel createSquareJPanel(Color color, int size1, int size2)
{
JPanel tempPanel = new JPanel();
tempPanel.setBackground(color);
tempPanel.setMinimumSize(new Dimension(size1, size2));
tempPanel.setMaximumSize(new Dimension(size1, size2));
tempPanel.setPreferredSize(new Dimension(size1, size2));
return tempPanel;
}
public static void main (String args[]){
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Form3 myF=new Form3();
}
});
};
}
picture of my app:
actual state:
JFrame uses a BorderLayout by default. It's default position (if you don't specify one) is CENTER.
BorderLayout will only allow one component to occupy any of it's 5 available positions.
So when you do...
jframe.add(scrollFrame);
jframe.add(container);
It adds the scrollFrame to the center position and effectively removes it when you add container (it doesn't actually remove it, but the result is just about the same).
Try supplying a position constraint. For example...
jframe.add(scrollFrame);
jframe.add(container, BorderLayout.SOUTH);
See How to use BorderLayout for more details

JButton not responsive - have to click twice

I created a GUI using java swing and in a specific situation, the JButton is unresponsive and I have to click it twice. On the click, it takes the info in the textArea and sends it to a TextParser class to be parsed. If I type more stuff in the area after, and click the evaluateButton, it doesn't respond and I have to click it again to work. Does anyone know if this is a known bug or how I can fix this?
The code for the class is as follows.
/**
* Add the components to the GUI.
* #param pane - the pane for the GUI
*/
public static void addComponentsToPane(Container pane) {
pane.setLayout(new BorderLayout());
JPanel instructionsPanel = new JPanel();
JLabel instructions = new JLabel("Enter the email text below");
instructionsPanel.setBackground(Color.LIGHT_GRAY);
instructionsPanel.add(instructions);
pane.add(instructionsPanel, BorderLayout.NORTH);
JPanel textAreaPanel = new JPanel();
textAreaPanel.setBackground(Color.LIGHT_GRAY);
final JTextArea textArea = new JTextArea();
textArea.setBackground(Color.WHITE);
textArea.setMinimumSize(new Dimension(400,350));
textArea.setMaximumSize(new Dimension(400,350));
textArea.setPreferredSize(new Dimension(400,350));
textArea.setLineWrap(true);
Border border = BorderFactory.createLineBorder(Color.BLACK);
textArea.setBorder(border);
textArea.setMinimumSize(new Dimension(500, 200));
textArea.setFont(new Font("Serif", Font.PLAIN, 16));
textAreaPanel.add(textArea);
pane.add(textAreaPanel, BorderLayout.CENTER);
JPanel scoringPanel = new JPanel();
JButton evaluateButton = new JButton("Evaluate Email");
final JLabel scoreLabel = new JLabel("");
JButton uploadFileBtn = new JButton("Upload File");
JButton importTermsBtn = new JButton("Import Terms");
scoringPanel.add(evaluateButton);
scoringPanel.add(uploadFileBtn);
scoringPanel.add(importTermsBtn);
scoringPanel.add(scoreLabel);
pane.add(scoringPanel, BorderLayout.SOUTH);
evaluateButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
try {
String email = textArea.getText();
TextParser textParser = new TextParser(email);
double score = textParser.parse();
scoreLabel.setText(score+"");
} catch (Exception ex) {
System.out.println(ex);
}
}
});
uploadFileBtn.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
scoreLabel.setText("Feature not yet available.");
}
});
importTermsBtn.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
DatabaseInput d = new DatabaseInput();
d.main(null);
}
});
}
/**
* Create the GUI and show it.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("EmailGUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.setLocationRelativeTo(null);
frame.setPreferredSize(new Dimension(500,500));
frame.setTitle("Email Text Input");
frame.setResizable(true);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
frame.setSize(screenSize.width, screenSize.height);
//Set up the content pane.
addComponentsToPane(frame.getContentPane());
//Display the window.
frame.pack();
frame.setVisible(true);
}
My main method just calls createAndShowGUI(). I am new to StackOverflow so if I need to give more or less information in my post please let me know!
As Reimeus and Jason C said in the comments, I should have been using ActionListener which works perfectly.

Layout Managers with icon (gif)

Essentially, I am trying to add a home screen with 4 buttons, 3 difficulty buttons and a play button. I add the buttons to a JPanel and add the JPanel with a BoxLayout of Center. Why does the buttons still go all the way off to the right? Setting the icon for a JLabel on and adding it to the home screen JPanel is a possible mess up the flow of components? I want the difficulty buttons to be on top of the of the gif with the Play button at the bottom. Thanks for your help.
//container
snake = new JFrame();
snake.setLayout(new BorderLayout());
//home screen panel
homeScreen = new JPanel();
homeScreen.setLayout(new BoxLayout(homeScreen, BoxLayout.X_AXIS));
homeScreen.setPreferredSize(new Dimension(320, 320));
JLabel bg = new JLabel();
ImageIcon icon = new ImageIcon("HomeBG.gif");
icon.getImage().flush();
bg.setIcon(icon);
homeScreen.add(bg);
easy = new JButton("Easy");
medium = new JButton("Medium");
hard = new JButton("Hard");
play = new JButton("Play");
//button listeners code here
homeScreen.add(easy);
homeScreen.add(medium);
homeScreen.add(hard);
homeScreen.add(play);
snake.add(homeScreen, BorderLayout.CENTER);
snake.setTitle("Snake Game");
snake.pack();
snake.setVisible(true);
snake.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
You need to change your code as shown below.
snake = new JFrame();
snake.setLayout(new BorderLayout());
//home screen panel
homeScreen = new JPanel(new BorderLayout());
//homeScreen.setLayout(new BoxLayout(homeScreen, BoxLayout.X_AXIS));
homeScreen.setPreferredSize(new Dimension(320, 320)); // probably you need to remove this line!
JLabel bg = new JLabel();
ImageIcon icon = new ImageIcon("HomeBG.gif");
icon.getImage().flush();
bg.setIcon(icon);
homeScreen.add(bg);
easy = new JButton("Easy");
medium = new JButton("Medium");
hard = new JButton("Hard");
play = new JButton("Play");
//button listeners code here
JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
buttonsPanel.add(easy);
buttonsPanel.add(medium);
buttonsPanel.add(hard);
buttonsPanel.add(play);
homeScreen.add(buttonsPanel, BorderLayout.NORTH);
snake.add(homeScreen, BorderLayout.CENTER);
snake.setTitle("Snake Game");
snake.pack();
snake.setVisible(true);
snake.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
I would use a compound layout for this. Put the level buttons in a (panel in a) FlowLayout. Put the play button in a 2nd FlowLayout. Add those panels to the PAGE_START and PAGE_END of a BorderLayout. Add a label containing the GIF to the CENTER of the same border layout.
BTW - the level buttons should be radio buttons (in a button group - BNI).
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class LayoutManagersWithIcon {
private JComponent ui = null;
LayoutManagersWithIcon() {
initUI();
}
public void initUI() {
if (ui!=null) return;
ui = new JPanel(new BorderLayout(4,4));
ui.setBorder(new EmptyBorder(4,4,4,4));
JPanel levelPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 5));
ui.add(levelPanel, BorderLayout.PAGE_START);
levelPanel.add(new JRadioButton("Easy"));
levelPanel.add(new JRadioButton("Medium"));
levelPanel.add(new JRadioButton("Hard"));
JPanel startPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 5));
ui.add(startPanel, BorderLayout.PAGE_END);
startPanel.add(new JButton("Play"));
JLabel label = new JLabel(new ImageIcon(
new BufferedImage(400, 100, BufferedImage.TYPE_INT_RGB)));
ui.add(label);
}
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) {
}
LayoutManagersWithIcon o = new LayoutManagersWithIcon();
JFrame f = new JFrame(o.getClass().getSimpleName());
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);
}
}

How to make a scrolling effect for a background image

I need to make a scrolling background for this platformer. It needs to scroll a 2400x500 image while the frame size is about 1440x900. If it could just gradually change over time that would be great. This is my code:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import javax.swing.*;
public class Main extends JFrame {
public Main() {
//Creates Title Image
JLabel title = new JLabel(" ");
ImageIcon tl = new ImageIcon("title.gif");
title.setIcon(tl);
//Creates Start Image
final JButton start = new JButton("");
ImageIcon st = new ImageIcon("start.gif");
start.setIcon(st);
//Creates Options Image
JButton options = new JButton("");
ImageIcon opt = new ImageIcon("options.gif");
options.setIcon(opt);
options.setBackground(Color.BLACK);
//Creates label for level 0 background image
JLabel background = new JLabel(" ");
ImageIcon back = new ImageIcon("level0.gif");
background.setIcon(back);
//Creates a panel for level 0
final JPanel p5 = new JPanel();
p5.setLayout (new BorderLayout(1, 1));
p5.add(background);
//Create first frame for "Start" button
final JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(1, 1));
p1.add(start, BorderLayout.CENTER);
//Create second panel for title label
final JPanel p2 = new JPanel(new BorderLayout());
p2.setLayout(new GridLayout(1, 3));
p2.add(title, BorderLayout.WEST);
//Create third panel for "Options" button
final JPanel p3 = new JPanel(new BorderLayout());
p3.setLayout(new GridLayout(1, 1));
p3.add(options, BorderLayout.SOUTH);
//Creates fourth panel to organize all other primary
final JPanel p4 = new JPanel(new BorderLayout());
p4.setLayout(new GridLayout(1, 3));
p4.add(p1, BorderLayout.WEST);
p4.add(p2, BorderLayout.CENTER);
p4.add(p3, BorderLayout.EAST);
//When button is clicked, it changes the level
start.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(start.isEnabled()) {
remove(p4);
add(p5, BorderLayout.CENTER);
invalidate();
validate();
}
else {
return;
}
}
});
//Adds fourth panel to frame
add(p4, BorderLayout.CENTER);
}
public static void main(String args[]) {
Main frame = new Main();
//Finds screen size of monitor
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
//Creates the frame
frame.setTitle("Cockadoodle Duty: Awakening");
frame.setSize(screenSize);
frame.setLocale(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
String background = "#000000";
frame.setBackground(Color.decode(background));
}
}
Add the label containing the icon to a scroll panel
Use a Swing Timer to schedule the scrolling
When the Timer fires you can scroll background.
The scrolling code might be something like:
JViewport viewport = scrollPane.getViewport();
Point position = viewport.getViewPosition();
position.x += 2;
viewport.setViiewPosition( position );

how to add jscrollpane to jframe?

I have following source code...Can someone please give me an advice how to add jscrollpane onto jframe? I tried several time to add it to jframe but without any progress. It is not even showing.
public class Form3 {
JFrame jframe = new JFrame("Etiket print.");
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
JScrollPane scrollFrame = new JScrollPane(panel2);
Color myBlue1Color = new Color(168, 175, 247);
Color myBlue2Color = new Color(139, 146, 255);
public Form3(){
jframe.setMinimumSize(new Dimension(1280, 1000));
panel2.setLayout(new BoxLayout(panel2, BoxLayout.Y_AXIS));
panel2.setAutoscrolls(true);
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//---------------------------------Header
panel1 = createSquareJPanel(Color.YELLOW, 600,200);
panel3 = createSquareJPanel(Color.GREEN, 400,200);
panel4 = createSquareJPanel(Color.white, 280,200);
JPanel container = new JPanel();
JPanel container1 = new JPanel();
JPanel container2 = new JPanel();
container.setLayout(new BoxLayout(container, BoxLayout.Y_AXIS));
container1.setLayout(new BoxLayout(container1, BoxLayout.Y_AXIS));
container2.setLayout(new BoxLayout(container2, BoxLayout.X_AXIS));
container1.add(panel1);
container2.add(container1);
container2.add(panel3);
container2.add(panel4);
container.add(container2);
container.add(panel2);
{
for (int i=0; i<25; i++){
JPanel harnessPanel= new JPanel();
harnessPanel.setMinimumSize(new Dimension(1280, 70));
harnessPanel.setMaximumSize(new Dimension(1280, 70));
harnessPanel.setPreferredSize(new Dimension(1280, 70));
if(i%2==0) {
harnessPanel.setBackground(myBlue1Color);
}
else {
harnessPanel.setBackground(myBlue2Color);
}
panel2.add(harnessPanel);
harnessPanel.repaint();
harnessPanel.validate();
}
panel2.repaint();
panel2.validate();
}
jframe.add(scrollFrame);
jframe.add(container);
jframe.pack();
jframe.setLocationRelativeTo(null);
jframe.setVisible(true);
}
private JPanel createSquareJPanel(Color color, int size1, int size2)
{
JPanel tempPanel = new JPanel();
tempPanel.setBackground(color);
tempPanel.setMinimumSize(new Dimension(size1, size2));
tempPanel.setMaximumSize(new Dimension(size1, size2));
tempPanel.setPreferredSize(new Dimension(size1, size2));
return tempPanel;
}
public static void main (String args[]){
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Form3 myF=new Form3();
}
});
};
}
picture of my app:
actual state:
JFrame uses a BorderLayout by default. It's default position (if you don't specify one) is CENTER.
BorderLayout will only allow one component to occupy any of it's 5 available positions.
So when you do...
jframe.add(scrollFrame);
jframe.add(container);
It adds the scrollFrame to the center position and effectively removes it when you add container (it doesn't actually remove it, but the result is just about the same).
Try supplying a position constraint. For example...
jframe.add(scrollFrame);
jframe.add(container, BorderLayout.SOUTH);
See How to use BorderLayout for more details

Categories