scroll bar appears but content won't wrap vertically - java

I have a JPanel that I want to dynamically fill with other jpanels, Like this: result
If I use a gridLayout it works unless it's not filled, in which case it will stretch the panels inside, like this gridlayout, stretched
If I use GridBagLayout it doesn't stretch them when there's few of them, but then it will not scroll when the panel is filled, like this gridbag, noscroll
I just can't get it to do both things: only vertical scroll AND no stretching when the panel is not filled.
The blue squares are JPanels with a borderLayout that I create passing labels and color as parameters. I tried making them absoluteLayout, gridBagLayout, fix their size, but the JPanel I add them to seems to overrule their settings.
public class Gbmapper extends JFrame {
/**
* Create the frame.
*/
public Gbmapper() {
//main window
setTitle("Gbmapper");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 600);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panelParagrafi = new JPanel(new BorderLayout(4, 4));
panelParagrafi.setBounds(10, 67, 760, 180);
panelParagrafi.setBorder(new TitledBorder("Paragrafi"));
// here's the problem
JPanel listaNodi = new JPanel(new GridLayout(0,20,2,2));
//JPanel listaNodi = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(2,2,2,2);
/* flowlayout also will display a single row
JPanel listaNodi = new JPanel();
listaNodi.setBounds(10, 67, 764, 180);
listaNodi.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5)); */
// init the jpanel with some items
for (int i = 0; i < 10; i++) {
// for use with gridlayout
listaNodi.add( new GbmParNode(Integer.toString(50), Integer.toString(i), 'b') );
// for use with gridbaglayout, passes insets
//listaNodi.add( new GbmParNode(Integer.toString(50), Integer.toString(i), 'b'), gbc );
}
JScrollPane scrollPane = new JScrollPane(listaNodi,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
panelParagrafi.add(scrollPane);
contentPane.add(panelParagrafi);
}}
// My JPanel class
package gbmapper;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.SwingConstants;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.BorderLayout;
public class GbmParNode extends JPanel {
// COLORI
Color myGreen = new Color(173, 255, 47);
Color myRed = new Color(255, 80, 50);
Color myBlue = new Color(0, 204, 255);
Color myYellow = new Color(255, 255, 0);
Color myWhite = new Color(255, 255, 255);
JLabel lblParNum; // = new JLabel(parNum);
/**
* Create the panel.
*/
public GbmParNode(String parNum, String parDesc, char parColor) {
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
}
});
Color myColor;
switch(parColor) {
case 'g':
myColor = myGreen;
break;
case 'r':
myColor = myRed;
break;
case 'b':
myColor = myBlue;
break;
case 'y':
myColor = myYellow;
break;
default:
myColor = myWhite;
}
setBackground(myColor);
setLayout(new BorderLayout(0, 0));
//setLayout(new GridBagLayout());
//setSize(50,50);
lblParNum = new JLabel(parNum);
lblParNum.setHorizontalAlignment(SwingConstants.CENTER);
lblParNum.setFont(new Font("Tahoma", Font.PLAIN, 18));
//lblParNum.setBounds(14, 5, 100, 22);
add(lblParNum, BorderLayout.CENTER);
JLabel lblParDesc = new JLabel(parDesc);
lblParDesc.setHorizontalAlignment(SwingConstants.CENTER);
//lblParDesc.setBounds(14, 25, 100, 14);
add(lblParDesc, BorderLayout.SOUTH);
}
}

Related

JPanel layout - adding text box and rearranging components

I am having some issues with my Swing GUI.
It currently looks like this:
But I would like to move a couple things around.
Firstly I want the buttons underneath the keyboard
I want to add a text field on top of the keyboard with the submit button on the right hand side.
How can I accomplish this? I've tried to create a GridLayout and slot things by row,column coordinate but it doesn't seem to work.
private class Display extends JPanel {
Display() {
setPreferredSize(new Dimension(620, 420));
setBackground(new Color(250, 230, 180));
setFont(new Font("Serif", Font.BOLD, 20));
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
((Graphics2D) g).setStroke(new BasicStroke(3));
if (message != null) {
g.setColor(Color.RED);
g.drawString(message, 30, 40);
g.drawString("00:00", 30, 410);
}
}
}
private void createWindow() {
setJMenuBar(menuBarCreator());
// The ActionListener that will respond to button clicks.
ButtonHandler buttonHandler = new ButtonHandler();
// Create the subpanels and add them to the main panel.
display = new Display();
setLayout(new BorderLayout(3, 3));
add(display, BorderLayout.CENTER);
JPanel bottom = new JPanel();
bottom.setLayout(new GridLayout(1,1));
add(bottom, BorderLayout.NORTH);
// Add keyboard
JPanel keyboard = new JPanel();
JPanel keyboardHolder = new JPanel();
keyboard.setLayout(new GridLayout(2, 13));
keyboardHolder.setLayout(new GridLayout(1, 2));
for (char alphabet = 'a'; alphabet <= 'z'; alphabet++) {
JButton button = new JButton(String.valueOf(alphabet));
button.addActionListener(buttonHandler);
keyboard.add(button);
alphabetButtons.add(button);
}
keyboardHolder.add(keyboard, 0,0);
add(keyboardHolder, BorderLayout.SOUTH);
// Create three buttons, register the ActionListener to respond to clicks on the
// buttons, and add them to the bottom panel.
JButton submitButton = new JButton("Submit");
submitButton.addActionListener(buttonHandler);
keyboard.add(submitButton);
JButton startButton = new JButton(GuiText.START.toString());
startButton.addActionListener(buttonHandler);
bottom.add(startButton);
JButton nextButton = new JButton(GuiText.NEXT.toString());
nextButton.addActionListener(buttonHandler);
bottom.add(nextButton);
JButton skipButton = new JButton(GuiText.SKIP.toString());
skipButton.addActionListener(buttonHandler);
bottom.add(skipButton);
JButton quit = new JButton(GuiText.QUIT.toString());
quit.addActionListener(buttonHandler);
bottom.add(quit);
setBackground(new Color(100, 0, 0));
nextButton.setEnabled(false);
skipButton.setEnabled(false);
}
Below is a concrete example of what camickr wrote in his comment to the original question. Note that this is not the only possibility. There are many layout managers. I recommend visiting Laying Out Components Within a Container
The purpose of the code is only to show you how to achieve your desired layout.
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
public class GuesGame implements Runnable {
private JFrame frame;
public void run() {
showGui();
}
private JPanel createBottomPanel() {
JPanel bottomPanel = new JPanel(new GridLayout(3, 1));
bottomPanel.add(createSubmitPanel());
bottomPanel.add(createKeyboardPanel());
bottomPanel.add(createButtonsPanel());
return bottomPanel;
}
private JPanel createButtonsPanel() {
JPanel buttonsPanel = new JPanel();
JButton startButton = new JButton("Start");
buttonsPanel.add(startButton);
JButton nextButton = new JButton("Next");
buttonsPanel.add(nextButton);
JButton skipButton = new JButton("Skip");
buttonsPanel.add(skipButton);
JButton quitButton = new JButton("Quit");
buttonsPanel.add(quitButton);
return buttonsPanel;
}
private JPanel createKeyboardPanel() {
JPanel keyboardPanel = new JPanel(new GridLayout(2, 13));
for (char c = 'a'; c <= 'z'; c++) {
JButton button = new JButton(String.valueOf(c));
keyboardPanel.add(button);
}
return keyboardPanel;
}
private JPanel createSubmitPanel() {
JPanel submitPanel = new JPanel();
JTextField txtFld = new JTextField(20);
submitPanel.add(txtFld);
JButton submitButton = new JButton("Submit");
submitPanel.add(submitButton);
return submitPanel;
}
private void showGui() {
frame = new JFrame("Guess Game");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(new Display(), BorderLayout.CENTER);
frame.add(createBottomPanel(), BorderLayout.PAGE_END);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new GuesGame());
}
}
class Display extends JPanel {
private String message;
Display() {
message = "Starting game";
setPreferredSize(new Dimension(620, 420));
setBackground(new Color(250, 230, 180));
setFont(new Font("Serif", Font.BOLD, 20));
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
((Graphics2D) g).setStroke(new BasicStroke(3));
if (message != null) {
g.setColor(Color.RED);
g.drawString(message, 30, 40);
g.drawString("00:00", 30, 410);
}
}
}
You want three "rows" below the Display panel as follows
Text field and "submit" button.
Keyboard
Other buttons.
Hence the "bottom" panel contains three panels laid out one above the other.
The first panel is the text field and "submit" panel.
Underneath that is the "keyboard".
And underneath the keyboard are the other buttons.
Note that the default layout manager for JPanel is java.awt.FlowLayout and this layout manager is suitable for the panel containing the "submit" button and also suitable for the panel containing the other buttons.
Here is a screen capture of the running app.

Java JTable column header not showing using DefaultModel

Like the title said, the hearder name is just not showing up. i tried many options like using a JScrollPane. and fallowed many guide on this forum but no help. I really wanted to get resolve problem by myself but i have tried everything and out of option.
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.ScrollPane;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.awt.event.ActionEvent;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.JScrollPane;
import javax.swing.JScrollBar;
public class Adminpage extends JPanel {
private JFrame frame;
static String ID[]={"name","Username","Password"};
static DefaultTableModel model;
private JTextField NametextField;
private JTextField UsertextField;
private JTextField PasstextField;
private JTable table;
private JScrollPane scroll;
/**
* Create the panel.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 497, 545);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblAdminstratorPortal = new JLabel("Adminstrator Portal");
lblAdminstratorPortal.setFont(new Font("Tahoma", Font.BOLD, 20));
lblAdminstratorPortal.setBounds(109, 26, 218, 25);
frame.getContentPane().add(lblAdminstratorPortal);
JButton btnNewButton = new JButton("Add Librarian");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//model= (DefaultTableModel)table.getModel();
//model.addColumn("name");
//model.addColumn("Username");
//model.addColumn("Password");
model.addRow(new Object[]{NametextField.getText(),UsertextField.getText(),PasstextField.getText()});
}
});
btnNewButton.setBounds(10, 62, 108, 35);
frame.getContentPane().add(btnNewButton);
JButton btnDelete = new JButton("Delete");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnDelete.setBounds(130, 62, 108, 35);
frame.getContentPane().add(btnDelete);
JButton btnViewLibrarian = new JButton("View Librarian");
btnViewLibrarian.setBounds(245, 62, 108, 35);
frame.getContentPane().add(btnViewLibrarian);
JButton btnLogout = new JButton("Logout");
btnLogout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
frame.dispose();
}
});
btnLogout.setBounds(363, 62, 108, 35);
frame.getContentPane().add(btnLogout);
//model= (DefaultTableModel)table.getModel();
JLabel lblName = new JLabel("Name");
lblName.setBounds(21, 144, 60, 14);
frame.getContentPane().add(lblName);
JLabel lblUsername = new JLabel("Username");
lblUsername.setBounds(21, 195, 60, 14);
frame.getContentPane().add(lblUsername);
JLabel lblPassword = new JLabel("Password");
lblPassword.setBounds(21, 250, 60, 14);
frame.getContentPane().add(lblPassword);
NametextField = new JTextField();
NametextField.setBounds(119, 141, 119, 20);
frame.getContentPane().add(NametextField);
NametextField.setColumns(10);
UsertextField = new JTextField();
UsertextField.setColumns(10);
UsertextField.setBounds(119, 192, 119, 20);
frame.getContentPane().add(UsertextField);
PasstextField = new JTextField();
PasstextField.setColumns(10);
PasstextField.setBounds(119, 247, 119, 20);
frame.getContentPane().add(PasstextField);
table = new JTable();
table.setBounds(10, 304, 461, 189);
frame.getContentPane().add(table);
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Adminpage() {
database();
setLayout(null);
initialize();
model= (DefaultTableModel)table.getModel();
model.addColumn("name");
model.addColumn("Username");
model.addColumn("Password");
}
public void database(){
try {
Class.forName("sun.jdbc.odbc.JdbsOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:Games");
Statement st = con.createStatement();
String getquery = ("Select* from Games");
ResultSet rs= st.executeQuery(getquery);
while(rs.next()){
System.out.println(rs.getString(2));
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
You're adding the JTable directly to the GUI. Instead, yes you need to embed the JTable into the viewport of a JScrollPane and then add the JScrollPane to the GUI.
For example:
table = new JTable();
JScrollPane scrollPane = new JScrollPane(table);
// table.setBounds(10, 304, 461, 189);
scrollPane.setBounds(10, 304, 461, 189); // This is bad, but will leave for now
// frame.getContentPane().add(table);
frame.getContentPane().add(scrollPane);
Also, you're harming your GUI by using null layouts and absolute positioning, as this can interfere with a component's ability to show itself fully and correctly, to achieve its own preferred size. Much better is to learn and use the layout managers.
For instance, when I run your program on my platform, I see:
Note how the buttons do not show their full texts due to their not being allowed to achieve their preferred sizes.
For example, using BoxLayout with some nested JPanels, one using GridLayout(1, 0, 5, 0) for one row, variable number of columns, and a 5 point horizontal gap between components, and another nested JPanel using GridBagLayout, for placement of JTextFields and JLabels, and some "wrapper" JPanels using default FlowLayout to center components within them...
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class AdminPage2 extends JPanel {
private static final long serialVersionUID = 1L;
public static final String TITLE = "Administrator Portal";
private static final Font TITLE_FONT = new Font("Tahoma", Font.BOLD, 20);
private static final String[] COL_NAMES = {"Name", "User Name", "Password"};
private int txtFieldCols = 20;
private JTextField nameField = new JTextField(txtFieldCols);
private JTextField userNameField = new JTextField(txtFieldCols);
private JPasswordField passwordField = new JPasswordField(txtFieldCols);
private DefaultTableModel tableModel = new DefaultTableModel(COL_NAMES, 0);
private JTable table = new JTable(tableModel);
private JScrollPane tableScrollPane = new JScrollPane(table);
public AdminPage2() {
JLabel titleLabel = new JLabel(TITLE, SwingConstants.CENTER);
titleLabel.setFont(TITLE_FONT);
JPanel titlePanel = new JPanel();
titlePanel.add(titleLabel);
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 0));
// of course you'd add ActionListeners or Actions to your buttons
buttonPanel.add(new JButton("Add Library"));
buttonPanel.add(new JButton("Delete"));
buttonPanel.add(new JButton("View Library"));
buttonPanel.add(new JButton("Logout"));
JPanel textFieldPanel = new JPanel(new GridBagLayout());
textFieldPanel.add(new JLabel("Name:"), createGbc(0, 0));
textFieldPanel.add(nameField, createGbc(1, 0));
textFieldPanel.add(new JLabel("User Name:"), createGbc(0, 1));
textFieldPanel.add(userNameField, createGbc(1, 1));
textFieldPanel.add(new JLabel("Password:"), createGbc(0, 2));
textFieldPanel.add(passwordField, createGbc(1, 2));
JPanel wrapTfPanel = new JPanel();
wrapTfPanel.add(textFieldPanel);
Dimension scrollPanePrefSz = tableScrollPane.getPreferredSize();
int w = scrollPanePrefSz.width;
int h = scrollPanePrefSz.height / 2;
scrollPanePrefSz = new Dimension(w, h);
tableScrollPane.setPreferredSize(scrollPanePrefSz);
// put together main JPanel components
int ebGap = 4;
setBorder(BorderFactory.createEmptyBorder(ebGap, ebGap, ebGap, ebGap));
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(Box.createVerticalStrut(5));
add(titlePanel);
add(Box.createVerticalStrut(5));
add(buttonPanel);
add(Box.createVerticalStrut(5));
add(wrapTfPanel);
add(Box.createVerticalStrut(5));
add(tableScrollPane);
}
// create constraints to use when adding component to GridBagLayout
private GridBagConstraints createGbc(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.anchor = x == 0 ? GridBagConstraints.WEST : GridBagConstraints.EAST;
gbc.fill = GridBagConstraints.HORIZONTAL;
int in = 10;
int leftIn = x == 0 ? 4 * in : in;
gbc.insets = new Insets(in, leftIn, in, in);
return gbc;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
private static void createAndShowGui() {
AdminPage2 mainPanel = new AdminPage2();
JFrame frame = new JFrame("Administrator Page");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Which displays as:
Regarding your questions:
but new question why give the scrollpane a bound instead of the table itself
The JScrollPane holds the JTable within it, and so if you use null layouts (which you shouldn't), and you're adding this JTable-containing JScrollPane to the GUI, you must set its bounds. Much better though is to use layout managers as I've outlined above. It makes it much easier to modify the GUI later and to debug it now.
and why adding the scrollpane into the panel instead of the table.
Because that's how JScrollPanes work. They don't add scrollbars to a component but rather nest the component itself, here the JTable, within the JScrollPane's viewport. Please read the JScrollPane Tutorial (see link) to see the details on this.
A further note on the power of layout managers. Say you want to add a new JLabel / JTextField combination, one that accepts a password hint, and say the JTextField's name is passwordHint. If you were using null layouts and absolute positioning, you'd have to set the bounds of your new JLabel and JTextField, but you'd also have to change the bounds of all components below and to the right of it, and would have to re-set the size of the GUI manually. If your GUI is very complex, this can lead to bugs and a lot of frustration.
If you used the layout managers above however, all you'd need to do would be to add two lines of code to the textFieldPanel JPanel creational code as shown below with the obvious comments:
// original textFieldPanel creational code
JPanel textFieldPanel = new JPanel(new GridBagLayout());
textFieldPanel.add(new JLabel("Name:"), createGbc(0, 0));
textFieldPanel.add(nameField, createGbc(1, 0));
textFieldPanel.add(new JLabel("User Name:"), createGbc(0, 1));
textFieldPanel.add(userNameField, createGbc(1, 1));
textFieldPanel.add(new JLabel("Password:"), createGbc(0, 2));
textFieldPanel.add(passwordField, createGbc(1, 2));
// !! ****** these lines added ******
textFieldPanel.add(new JLabel("Password Hint:"), createGbc(0, 3));
textFieldPanel.add(passwordHint, createGbc(1, 3));
This results in a perfect placement of the new components without adversely affecting the old:

What layout should I use to make this work for Java?

Here's what I want the end result to look like...
I am trying to use a GridBagLayout for this but not sure if its the right choice because it's coming out all over the place. I know I shouldn't write all my code in a single constructor but here's what I have so far...
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.Font;
import java.awt.event.*;
import static java.lang.Math.*;
public class HomeStylePizza extends JFrame{
private static final int WIDTH = 500;
private static final int HEIGHT = 400;
//GUI components
private JLabel lblEachTopping, lblPizzaSize, lblPizzaType, lblWelcome, lblYourOrder;
private JButton btnProcessSelection;
private JCheckBox cbPepproni, cbSausage, cbMushrooms, cbPineapple, cbOnion, cbBellPepper;
private JRadioButton rbSmall, rbMedium, rbLarge, rbThinCrust, rbMediumCrust, rbPan;
private ButtonGroup grp1, grp2;
private JTextArea textArea;
private CalculateButtonHandler cbHandler;
public HomeStylePizza()
{
//Create new labels
lblEachTopping = new JLabel("Each Topping: $1.50");
lblPizzaSize = new JLabel("Pizza Size");
lblPizzaType = new JLabel("Pizza Type");
lblWelcome = new JLabel("Welcome to Home Style Pizza Shop");
lblYourOrder = new JLabel("Your order:");
//Create new buttons
btnProcessSelection = new JButton("Process Selection");
cbHandler = new CalculateButtonHandler();
btnProcessSelection.addActionListener(cbHandler);
//Create new JCheckBoxes
cbPepproni = new JCheckBox("Pepproni");
cbSausage = new JCheckBox("Sausage");
cbMushrooms = new JCheckBox("Mushrooms");
cbPineapple = new JCheckBox("Pineapple");
cbOnion = new JCheckBox("Onion");
cbBellPepper = new JCheckBox("Bell Pepper");
//Create radio buttons
rbSmall = new JRadioButton("Small: $6.50");
rbMedium = new JRadioButton("Medium: $8.50");
rbLarge = new JRadioButton("Large: $10.00");
rbThinCrust = new JRadioButton("Thin Crust");
rbMediumCrust = new JRadioButton("Medium Crust");
rbPan = new JRadioButton("Pan");
//Create new TextArea
textArea = new JTextArea(6, 10);
//Set title
setTitle("Pizza Shop");
//Create new font layout
Font font = new Font("New Times Roman", Font.BOLD, 18);
//get the container
Container pane = getContentPane();
JPanel thePanel = new JPanel();
thePanel.setLayout(new GridBagLayout());
//set the layout
pane.setLayout(new GridBagLayout());
GridBagConstraints gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 1;
gridConstraints.gridy = 1;
gridConstraints.gridwidth = 1;
gridConstraints.gridheight = 1;
gridConstraints.weightx = 50;
gridConstraints.weighty = 100;
gridConstraints.insets = new Insets(5,5,5,5);
gridConstraints.anchor = GridBagConstraints.CENTER;
gridConstraints.fill = GridBagConstraints.BOTH;
//Place components in the pane
thePanel.add(lblWelcome, gridConstraints);
gridConstraints.anchor = GridBagConstraints.FIRST_LINE_START;
gridConstraints.gridwidth = 20;
gridConstraints.gridx = 15;
lblWelcome.setFont(new Font("New Times Roman", Font.BOLD, 18));
lblWelcome.setForeground(Color.RED);
//Create new vertical box and place a titled border around it
Box optionBox1 = Box.createVerticalBox();
optionBox1.setBorder(BorderFactory.createTitledBorder(null, "Toppings", 0, 0, new Font("times new roman", Font.PLAIN, 14), Color.RED));
//add components to optionBox1
optionBox1.add(lblEachTopping);
lblEachTopping.setForeground(Color.RED);
optionBox1.add(cbPepproni);
optionBox1.add(cbSausage);
optionBox1.add(cbMushrooms);
optionBox1.add(cbPineapple);
optionBox1.add(cbOnion);
optionBox1.add(cbBellPepper);
//add optionBox1 to WEST quadrant
thePanel.add(optionBox1, gridConstraints);
gridConstraints.anchor = GridBagConstraints.LINE_START;
gridConstraints.gridwidth = 1;
gridConstraints.gridx = 1;
gridConstraints.gridy = 10;
//Create new vertical box and place a titled border around it
Box optionBox2 = Box.createVerticalBox();
optionBox2.setBorder(BorderFactory.createTitledBorder(null, "Pizza Size", 0, 0, new Font("times new roman", Font.PLAIN, 14), Color.RED));
//Create new ButtonGroup
grp1 = new ButtonGroup();
//add components to optionBox2 and grp1
grp1.add(rbSmall);
grp1.add(rbMedium);
grp1.add(rbLarge);
optionBox2.add(rbSmall);
optionBox2.add(rbMedium);
optionBox2.add(rbLarge);
//add optionBox2 to CENTER
thePanel.add(optionBox2, gridConstraints);
gridConstraints.anchor = GridBagConstraints.CENTER;
gridConstraints.gridx = 3;
gridConstraints.gridy = 10;
Box btnBox = Box.createHorizontalBox();
btnBox.setBorder(BorderFactory.createEmptyBorder());
btnBox.add(btnProcessSelection);
thePanel.add(btnBox);
gridConstraints.anchor = GridBagConstraints.LAST_LINE_END;
gridConstraints.gridwidth = 5;
gridConstraints.gridx = 3;
gridConstraints.gridy = 12;
//Create new vertical box and place a titled border around it
Box optionBox3 = Box.createVerticalBox();
optionBox3.setBorder(BorderFactory.createTitledBorder(null, "Pizza Type", 0, 0, new Font("times new roman", Font.PLAIN, 14), Color.RED));
//Create new ButtonGroup
grp2 = new ButtonGroup();
//add components to optionBox2 and grp1
grp2.add(rbThinCrust);
grp2.add(rbMediumCrust);
grp2.add(rbPan);
optionBox3.add(rbThinCrust);
optionBox3.add(rbMediumCrust);
optionBox3.add(rbPan);
//add optionBox3 to EAST
thePanel.add(optionBox3, gridConstraints);
gridConstraints.anchor = GridBagConstraints.LINE_END;
gridConstraints.gridwidth = 1;
gridConstraints.gridx = 5;
gridConstraints.gridy = 10;
//Create box for lblYourOrder and textArea and
//add them to pane in SOUTH quadrant
Box orderBox = Box.createVerticalBox();
orderBox.setBorder(null);
orderBox.add(lblYourOrder);
orderBox.add(textArea);
thePanel.add(orderBox, gridConstraints);
gridConstraints.anchor = GridBagConstraints.LAST_LINE_START;
gridConstraints.gridwidth = 30;
gridConstraints.gridx = 1;
gridConstraints.gridy = 13;
pane.add(thePanel);
//set window size and display it
setSize(WIDTH, HEIGHT);
setVisible(true);
//Center frame
this.setLocationRelativeTo(null);
this.pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
}//End of constructor
public static void main(String[] args)
{
HomeStylePizza menuTest = new HomeStylePizza();
}//End of main
private class CalculateButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
}
}
}//End of class
Its a bit ugly and you can ignore most of my comments I've been changing things around trying to fix it. I was using a different layout.
Edited: I went ahead and created the Pizza Shop GUI.
I used a combination of BorderLayouts and GridBagLayouts.
I grouped together the code to make it easier to follow. Grouping the code does not mean putting all of the JCheckBox initializations together. Grouping the code means that all of the elements that make up a JPanel are there, right next to each other. This way, you don't have to jump all over the code looking for the lines that define the JRadioButton rbMedium.
I used a separate GridBagConstraints for each Swing component to make it easier for me to debug the GUI.
I've left the action listener for you to code.
Here's the GUI code:
package com.ggl.testing;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
public class HomeStylePizza implements Runnable {
private static final Insets bottomInsets = new Insets(10, 10, 10, 10);
private static final Insets normalInsets = new Insets(10, 10, 0, 10);
// GUI components
private JCheckBox cbPepproni, cbSausage, cbMushrooms, cbPineapple, cbOnion,
cbBellPepper;
private JRadioButton rbSmall, rbMedium, rbLarge, rbThinCrust,
rbMediumCrust, rbPan;
private JTextArea textArea;
public static void main(String[] args) {
SwingUtilities.invokeLater(new HomeStylePizza());
} // End of main
#Override
public void run() {
JFrame frame = new JFrame("Pizza Shop");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridBagLayout());
int gridy = 0;
addComponent(mainPanel, createTitlePanel(), 0, gridy++, 2, 1,
normalInsets, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL);
addComponent(mainPanel, createToppingPanel(), 0, gridy, 1, 1,
normalInsets, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL);
JPanel eastPanel = new JPanel();
eastPanel.setLayout(new BorderLayout());
eastPanel.add(createSizePanel(), BorderLayout.WEST);
eastPanel.add(new JLabel(" "), BorderLayout.CENTER);
eastPanel.add(createTypePanel(), BorderLayout.EAST);
eastPanel.add(createButtonPanel(), BorderLayout.SOUTH);
addComponent(mainPanel, eastPanel, 1, gridy++, 1, 1, normalInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
addComponent(mainPanel, createTextAreaPanel(), 0, gridy++, 2, 1,
bottomInsets, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL);
frame.add(mainPanel);
frame.pack();
frame.setVisible(true);
}
private JPanel createTitlePanel() {
JPanel panel = new JPanel();
JLabel lblWelcome = new JLabel("Welcome to Home Style Pizza Shop");
Font titleFont = lblWelcome.getFont().deriveFont(20F);
lblWelcome.setFont(titleFont);
lblWelcome.setForeground(Color.RED);
panel.add(lblWelcome);
return panel;
}
private JPanel createToppingPanel() {
Border redBorder = BorderFactory.createLineBorder(Color.RED, 2);
Border emptyBorder = BorderFactory.createEmptyBorder(4, 10, 4, 10);
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createCompoundBorder(redBorder,
emptyBorder));
panel.setLayout(new GridLayout(0, 1));
JLabel lblEachTopping = new JLabel("Each Topping: $1.50");
lblEachTopping.setForeground(Color.RED);
panel.add(lblEachTopping);
cbPepproni = new JCheckBox("Pepperoni");
cbSausage = new JCheckBox("Sausage");
cbMushrooms = new JCheckBox("Mushrooms");
cbPineapple = new JCheckBox("Pineapple");
cbOnion = new JCheckBox("Onion");
cbBellPepper = new JCheckBox("Bell Pepper");
// add components to optionBox1
panel.add(cbPepproni);
panel.add(cbSausage);
panel.add(cbMushrooms);
panel.add(cbPineapple);
panel.add(cbOnion);
panel.add(cbBellPepper);
return panel;
}
private JPanel createSizePanel() {
Border redBorder = BorderFactory.createLineBorder(Color.RED, 2);
Border emptyBorder = BorderFactory.createEmptyBorder(4, 10, 4, 10);
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createCompoundBorder(redBorder,
emptyBorder));
panel.setLayout(new GridLayout(0, 1));
JLabel lblPizzaSize = new JLabel("Pizza Size");
lblPizzaSize.setForeground(Color.RED);
panel.add(lblPizzaSize);
rbSmall = new JRadioButton("Small: $6.50");
rbMedium = new JRadioButton("Medium: $8.50");
rbLarge = new JRadioButton("Large: $10.00");
// Create new ButtonGroup
ButtonGroup group = new ButtonGroup();
group.add(rbSmall);
group.add(rbMedium);
group.add(rbLarge);
panel.add(rbSmall);
panel.add(rbMedium);
panel.add(rbLarge);
return panel;
}
private JPanel createTypePanel() {
Border redBorder = BorderFactory.createLineBorder(Color.RED, 2);
Border emptyBorder = BorderFactory.createEmptyBorder(4, 10, 4, 10);
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createCompoundBorder(redBorder,
emptyBorder));
panel.setLayout(new GridLayout(0, 1));
JLabel lblPizzaType = new JLabel("Pizza Type");
lblPizzaType.setForeground(Color.RED);
panel.add(lblPizzaType);
rbThinCrust = new JRadioButton("Thin Crust");
rbMediumCrust = new JRadioButton("Medium Crust");
rbPan = new JRadioButton("Pan");
// Create new ButtonGroup
ButtonGroup group = new ButtonGroup();
// add components to optionBox2 and grp1
group.add(rbThinCrust);
group.add(rbMediumCrust);
group.add(rbPan);
panel.add(rbThinCrust);
panel.add(rbMediumCrust);
panel.add(rbPan);
return panel;
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel();
JButton btnProcessSelection = new JButton("Process Selection");
btnProcessSelection.addActionListener(new CalculateButtonHandler());
panel.add(btnProcessSelection);
return panel;
}
private JPanel createTextAreaPanel() {
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
JLabel lblYourOrder = new JLabel("Your order:");
panel.add(lblYourOrder, BorderLayout.NORTH);
textArea = new JTextArea(6, 12);
JScrollPane scrollPane = new JScrollPane(textArea);
panel.add(scrollPane, BorderLayout.CENTER);
return panel;
}
private void addComponent(Container container, Component component,
int gridx, int gridy, int gridwidth, int gridheight, Insets insets,
int anchor, int fill) {
GridBagConstraints gbc = new GridBagConstraints(gridx, gridy,
gridwidth, gridheight, 1.0D, 1.0D, anchor, fill, insets, 0, 0);
container.add(component, gbc);
}
private class CalculateButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
}
}
} // End of HomeStylePizza class
Use GridBagLayout, or use netbeans it will make it easy for you, other option use GridLayout(2,1)
in it 2 panel
panel 1 will have grid layout of 1,2 in it you first list and other pnael has grid layout of 2,1 first row is your second list and the second row will be the button finally put the order info in the second row of your base layout.

Resizing and icon on a jpanel with card layout

I'm trying to create an application where a list of numbers are listed on the WEST region of BorderLayout and corresponding panels in the CENTER. The problem is that
I need the WEST region to be wider. Right now, it contains JList in a JPanel which resizes it to its default size. Preferred size? Not sure!
I need to have an icon or alphabet character 'x' towards the right end of 1 or 2. So, that when I close it, I can close the corresponding panel on the CENTER.
CODE:
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.border.MatteBorder;
import java.awt.Color;
public class Sample1 extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Sample1 frame = new Sample1();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Sample1() {
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);
JPanel panel = new JPanel();
panel.setBorder(new MatteBorder(1, 1, 1, 1, (Color) new Color(0, 0, 0)));
contentPane.add(panel, BorderLayout.WEST);
Vector<String> str = new Vector<>();
str.add("1");
str.add("2");
final JList list = new JList();
list.setListData(str);
panel.add(list);
final JPanel panel_1 = new JPanel();
panel_1.setBorder(new MatteBorder(1, 1, 1, 1, (Color) new Color(0, 0, 0)));
contentPane.add(panel_1, BorderLayout.CENTER);
panel_1.setLayout(new CardLayout(0, 0));
JPanel panel_2 = new JPanel();
panel_1.add(panel_2, "1");
JLabel lblNewLabel = new JLabel("First");
panel_2.add(lblNewLabel);
JPanel panel_3 = new JPanel();
panel_1.add(panel_3, "2");
JLabel lblNewLabel_1 = new JLabel("Second");
panel_3.add(lblNewLabel_1);
list.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e){
CardLayout layout = (CardLayout) panel_1.getLayout();
layout.show(panel_1, list.getSelectedValue().toString());
}
});
}
}
Maybe use a JTable with two columns. The second column can contain a close button. See Table Button Column for an example of this approach.
Otherwise you would need to add a panel to the WEST. The panel would contain the JList and some other component beside the JList to act as the close button. The problem with this approach is getting the components to line up and for the button to know which panel to close.
Have you tried using a GridLayout or BoxLayout also try setting up your GUI with a separate methods.
Setup GUI Code:
private void setupGUI() {
JPanel westP = setupWestPane();
getContentPane().add(westPa, BorderLayout.WEST);
}
Setup West Pane Code:
private JPanel setupWestPane() {
JPanel westP = setupWestPanel();
JPanel p = new JPanel(new GridLayout(1, 2, 20, 0));
p.setOpaque(false);
p.add(westP);
return p;
}
Setup West Panel Code :
private JPanel setupPlayerPanel() {
list1 = new JList();
list1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
// If you want to add a listener to the listbox
// list1.addListSelectionListener(this);
JScrollPane jsp = new JScrollPane(playerList);
JPanel p = new JPanel(new BorderLayout());
p.setOpaque(false);
p.add(new JLabel("List"), BorderLayout.NORTH);
p.add(jsp, BorderLayout.CENTER);
return p;
}
The code above is just an example.

Trouble creating JLabel inside JPanel

I don't understand why the last part doesn't add to my interface. I tried different approaches, but none of them seems to work. I can't add 1024 labels to my panel this way. Did I do something wrong, or is there an alternative to this?
Can tell me what could be wrong with the code? Thanks!
Full code here:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.border.TitledBorder;
import javax.swing.UIManager;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.border.LineBorder;
public class CacheGUI extends JFrame {
private static final int LEN = 1024;
private static final long serialVersionUID = 1L;
private JTextField textField;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
CacheGUI frame = new CacheGUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public CacheGUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 700, 500);
getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Lista de referinte", TitledBorder.LEADING, TitledBorder.TOP, null, null));
panel.setBounds(6, 16, 124, 364);
getContentPane().add(panel);
panel.setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(6, 16, 108, 340);
panel.add(scrollPane);
JTextPane txtpnDasd = new JTextPane();
txtpnDasd.setToolTipText("Lista curenta de adrese");
txtpnDasd.setEnabled(false);
txtpnDasd.setEditable(false);
scrollPane.setViewportView(txtpnDasd);
txtpnDasd.setText("<generate first>");
JButton btnGenerate = new JButton("GENERATE");
btnGenerate.setToolTipText("Incepe generarea listei de adrese.");
btnGenerate.setBounds(6, 422, 124, 23);
getContentPane().add(btnGenerate);
JButton btnStart = new JButton("START");
btnStart.setToolTipText("Ruleaza simularea");
btnStart.setBounds(550, 422, 124, 23);
getContentPane().add(btnStart);
JLabel lblBlockSize = new JLabel("Block size:");
lblBlockSize.setFont(new Font("Tahoma", Font.BOLD, 12));
lblBlockSize.setBounds(6, 394, 85, 14);
getContentPane().add(lblBlockSize);
textField = new JTextField();
textField.setToolTipText("");
textField.setHorizontalAlignment(SwingConstants.CENTER);
textField.setText("4");
textField.setBounds(79, 391, 51, 20);
getContentPane().add(textField);
textField.setColumns(10);
int blocksize = Integer.parseInt(textField.getText());
int nrofblocks = LEN/blocksize; // LEN is 1024
JPanel block_panel = new JPanel();
block_panel.setBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null));
block_panel.setBounds(140, 16, 534, 398);
getContentPane().add(block_panel);
block_panel.setLayout(new GridLayout(blocksize,nrofblocks,2,0));
// THIS IS THE PART THAT DOES NOT ADD TO THE PANEL I CREATED BEFORE --->
JLabel[] lbl=new JLabel[LEN];
for(int i=0;i<LEN;i++)
{
lbl[i]=new JLabel("TEST");
lbl[i].setBackground(Color.YELLOW);
lbl[i].setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
block_panel.add(lbl[i]); // i want to create yellow blocks inside my panel as labels to modyfy the color afterwards
}//<----
}
}
The issue is the ridiculous number of labels you have; they're there.
Set the bounds of the block panel to something larger, reduce LEN, etc. and you'll see them.
First things first: Your labels won't have a yellow background color. JLabels are not opaque by default. Setting it to true will show the yellow background as before:
lbl[i].setOpaque(true);
The second thing is the sheer number of labels you have. Reduce the number to 100 say, and you'll see you labels.
for(int i=0;i<100;i++)
{
lbl[i]=new JLabel("TEST");
lbl[i].setBackground(Color.YELLOW);
lbl[i].setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
lbl[i].setOpaque(true);
block_panel.add(lbl[i]);
}
Use a JScrollPane, set opaque, grid layout 1.rows, 2.columns, set fixed size for label,
use BorderFactory.
JPanel block_panel = new JPanel();
block_panel.setBorder(new TitledBorder(null, "", TitledBorder.LEADING,
TitledBorder.TOP, null, null));
block_panel.setBounds(140, 16, 534, 398);
JScrollPane block_scrollpane = new JScrollPane(block_panel);
block_scrollpane.setBounds(140, 16, 534, 398);
getContentPane().add(block_scrollpane);
//block_panel.setLayout(new GridLayout(blocksize, nrofblocks, 2, 0));
block_panel.setLayout(new GridLayout(nrofblocks, blocksize, 2, 0));
// THIS IS THE PART THAT DOES NOT ADD TO THE PANEL I CREATED BEFORE --->
JLabel[] lbl = new JLabel[LEN];
Dimension lblSize = new Dimension(85, 16);
for (int i = 0; i < LEN; i++) {
lbl[i] = new JLabel("TEST" + i);
lbl[i].setOpaque(true);
lbl[i].setBackground(Color.YELLOW);
lbl[i].setBorder(BorderFactory.createLineBorder(Color.BLACK, 1, true));
lbl[i].setPreferredSize(lblSize);
lbl[i].setMinimumSize(lblSize);
block_panel.add(lbl[i]); // i want to create yellow blocks
// inside my panel as labels to modyfy the color afterwards
}//<----

Categories