I'm building a Java GUI calculator. UI is complex and I'm doing it using Layouts instead of drag and drop. Everything is working fine except
1.mode_error_label.setPreferredSize(new Dimension(46, 55)); 2.backButton.setPreferredSize(new Dimension(45, 55));
Why is height not set to 55?
What am I missing?
Look at the top left and top right corner of the image.
My Result:
Desired Result:
public class CalculatorViewController extends JPanel {
private JTextField display1;
private JTextField display2;
private JLabel mode_error_label;
private JButton dotButton;
public CalculatorViewController() {
this.setLayout(new BorderLayout());
this.setBorder(BorderFactory.createMatteBorder(5, 5, 5, 5, Color.BLACK));
mode_error_label = new JLabel("F", JLabel.CENTER);
mode_error_label.setPreferredSize(new Dimension(46, 55));
mode_error_label.setBackground(Color.YELLOW);
mode_error_label.setOpaque(true);
mode_error_label.setBorder(BorderFactory.createMatteBorder(0, 0, 0, 5, Color.BLACK));
JButton backButton = new JButton(Character.toString('\u21DA'));
backButton.setPreferredSize(new Dimension(45, 55));
backButton.setBackground(Color.YELLOW);
backButton.setBorder(BorderFactory.createMatteBorder(0, 5, 0, 0, Color.BLACK));
backButton.setToolTipText("Backspace (Alt-B)");
display1 = new JTextField(16);
display1.setEditable(false);
display1.setHorizontalAlignment(JTextField.RIGHT);
display1.setBackground(Color.WHITE);
display1.setBorder(BorderFactory.createEmptyBorder());
display2 = new JTextField(16);
display2.setEditable(false);
display2.setHorizontalAlignment(JTextField.RIGHT);
display2.setBackground(Color.WHITE);
display2.setBorder(BorderFactory.createEmptyBorder());
display2.setText("0.0");
Box displayBox = Box.createVerticalBox();
displayBox.add(display1);
displayBox.add(display2);
Box upperBox = Box.createHorizontalBox();
upperBox.add(mode_error_label);
upperBox.add(displayBox);
upperBox.add(backButton);
upperBox.setBorder(BorderFactory.createMatteBorder(0, 0, 5, 0, Color.black));
JCheckBox modeCheckBox = new JCheckBox("int");
modeCheckBox.setPreferredSize(new Dimension(40, 0));
modeCheckBox.setBackground(Color.green);
JRadioButton _0RadioButton = new JRadioButton(".0", false);
_0RadioButton.setBackground(Color.YELLOW);
JRadioButton _00RadioButton = new JRadioButton(".00", true);
_00RadioButton.setBackground(Color.YELLOW);
JRadioButton sciRadioButton = new JRadioButton("Sci", false);
sciRadioButton.setBackground(Color.YELLOW);
ButtonGroup radioButtonGroup = new ButtonGroup();
radioButtonGroup.add(_0RadioButton);
radioButtonGroup.add(_00RadioButton);
radioButtonGroup.add(sciRadioButton);
Box lowerBox = Box.createHorizontalBox();
lowerBox.add(modeCheckBox);
lowerBox.add(Box.createGlue());
lowerBox.add(_0RadioButton);
lowerBox.add(_00RadioButton);
lowerBox.add(sciRadioButton);
lowerBox.setBackground(Color.BLACK);
lowerBox.setOpaque(true);
lowerBox.setBorder(BorderFactory.createMatteBorder(5, 0, 5, 0, Color.black));
JPanel lowerPanel = new JPanel();
lowerPanel.add(lowerBox);
lowerPanel.setBackground(Color.BLACK);
lowerPanel.setOpaque(true);
lowerPanel.setBorder(BorderFactory.createEmptyBorder());
Box superBox = Box.createVerticalBox();
superBox.add(upperBox);
superBox.add(lowerBox);
this.add(superBox, BorderLayout.PAGE_START);
}
}
I searched for it but found no luck. Any help would be appreciated. Thanks
For the top bar where you have the back button and label, set the container layout a border layout. Border layout should resize the component to its container. Or you can post a code that shows the problem and we can try to solve your problem. Good luck.
public class CalculatorViewController extends JPanel {
private JTextField display1;
private JTextField display2;
private JLabel mode_error_label;
private JButton dotButton;
private JPanel topPanel;
public CalculatorViewController() {
this.setLayout(new BorderLayout());
this.setBorder(BorderFactory.createMatteBorder(5, 5, 5, 5, Color.BLACK));
mode_error_label = new JLabel("F", JLabel.CENTER);
mode_error_label.setPreferredSize(new Dimension(46, 55));
mode_error_label.setBackground(Color.YELLOW);
mode_error_label.setOpaque(true);
mode_error_label.setBorder(BorderFactory.createMatteBorder(0, 0, 0, 5, Color.BLACK));
JButton backButton = new JButton(Character.toString('\u21DA'));
backButton.setPreferredSize(new Dimension(45, 55));
backButton.setBackground(Color.YELLOW);
backButton.setBorder(BorderFactory.createMatteBorder(0, 5, 0, 0, Color.BLACK));
backButton.setToolTipText("Backspace (Alt-B)");
display1 = new JTextField(16);
display1.setEditable(false);
display1.setHorizontalAlignment(JTextField.RIGHT);
display1.setBackground(Color.WHITE);
display1.setBorder(BorderFactory.createEmptyBorder());
display2 = new JTextField(16);
display2.setEditable(false);
display2.setHorizontalAlignment(JTextField.RIGHT);
display2.setBackground(Color.WHITE);
display2.setBorder(BorderFactory.createEmptyBorder());
display2.setText("0.0");
Box displayBox = Box.createVerticalBox();
displayBox.add(display1);
displayBox.add(display2);
Box upperBox = Box.createHorizontalBox();
topPanel.add(mode_error_label, BorderLayout.WEST);
topPanel.add(displayBox, BorderLayout.CENTER);
topPanel.add(backButton, BorderLayout.EAST);
upperBox.add(topPanel);
upperBox.setBorder(BorderFactory.createMatteBorder(0, 0, 5, 0, Color.black));
JCheckBox modeCheckBox = new JCheckBox("int");
modeCheckBox.setPreferredSize(new Dimension(40, 0));
modeCheckBox.setBackground(Color.green);
JRadioButton _0RadioButton = new JRadioButton(".0", false);
_0RadioButton.setBackground(Color.YELLOW);
JRadioButton _00RadioButton = new JRadioButton(".00", true);
_00RadioButton.setBackground(Color.YELLOW);
JRadioButton sciRadioButton = new JRadioButton("Sci", false);
sciRadioButton.setBackground(Color.YELLOW);
ButtonGroup radioButtonGroup = new ButtonGroup();
radioButtonGroup.add(_0RadioButton);
radioButtonGroup.add(_00RadioButton);
radioButtonGroup.add(sciRadioButton);
Box lowerBox = Box.createHorizontalBox();
lowerBox.add(modeCheckBox);
lowerBox.add(Box.createGlue());
lowerBox.add(_0RadioButton);
lowerBox.add(_00RadioButton);
lowerBox.add(sciRadioButton);
lowerBox.setBackground(Color.BLACK);
lowerBox.setOpaque(true);
lowerBox.setBorder(BorderFactory.createMatteBorder(5, 0, 5, 0, Color.black));
JPanel lowerPanel = new JPanel();
lowerPanel.add(lowerBox);
lowerPanel.setBackground(Color.BLACK);
lowerPanel.setOpaque(true);
lowerPanel.setBorder(BorderFactory.createEmptyBorder());
Box superBox = Box.createVerticalBox();
superBox.add(upperBox);
superBox.add(lowerBox);
this.add(superBox, BorderLayout.PAGE_START);
}
}
Related
I am trying to create a small swing application using Zulu JDK 11. In the bottom right part of it I am having an image (logo). My problem is that the logo is displayed poorly when the user changes the scaling to a value greater than 100% (125%, 150%, 175% etc.)
Here is my source code.
Main class:
public class Main {
public static void main(String[] args) {
FrameServer frameServer = new FrameServer();
frameServer.setVisible(true);
}}
FrameServer class:
public class FrameServer extends JFrame {
private JPanel contentPane;
private JPanel centerPane = new JPanel();
private JPanel southPane = new JPanel();
private JPanel rightPane = new JPanel();
private JButton btnOK = new JButton("OK");
private JTabbedPane jTabbedPane1 = new JTabbedPane();
private Tab1 tab1Page = new Tab1();
private Tab2 tab2Page = new Tab2();
public FrameServer() {
enableEvents(AWTEvent.WINDOW_EVENT_MASK);
jbInit();
pack();
centerFrame();
this.repaint();
}
private void jbInit() {
setTitle("Test Scaling App");
contentPane = (JPanel) this.getContentPane();
contentPane.setLayout(new BorderLayout());
centerPane.setLayout(new BorderLayout());
centerPane.add(jTabbedPane1, BorderLayout.CENTER);
southPane.setLayout(new BorderLayout());
rightPane.setLayout(new FlowLayout(FlowLayout.RIGHT, 5, 5));
rightPane.add(btnOK);
CustomStatusBar statusBar = new CustomStatusBar();
southPane.add(statusBar, BorderLayout.CENTER);
southPane.add(rightPane, BorderLayout.EAST);
jTabbedPane1.addTab("Tab 1", tab1Page);
jTabbedPane1.addTab("Tab 2", tab2Page);
contentPane.add(centerPane, BorderLayout.CENTER);
contentPane.add(southPane, BorderLayout.SOUTH);
}
private void centerFrame() {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = this.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
this.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
}
class Tab2 extends JScrollPane {
public Tab2() {
super(new JTextArea(10, 60));
super.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
super.getViewport().setPreferredSize(new Dimension(500, 300));
}
}
class Tab1 extends JPanel {
public Tab1() {
contentPane = this;
JScrollPane centerScrollPane = new JScrollPane(new JTable());
centerScrollPane.getViewport().setBackground(Color.white);
JPanel eastPane = new JPanel();
eastPane.setLayout(new FlowLayout());
JPanel topPane = new JPanel();
topPane.setLayout(new BoxLayout(topPane, BoxLayout.Y_AXIS));
eastPane.add(topPane, FlowLayout.LEFT);
contentPane.setLayout(new BorderLayout());
contentPane.add(centerScrollPane, BorderLayout.CENTER);
contentPane.add(eastPane, BorderLayout.EAST);
}
}
class CustomStatusBar extends JPanel {
JLabel label0 = new JLabel("", SwingConstants.CENTER);
JLabel label1 = new JLabel();
JLabel label2 = new JLabel();
JLabel label3 = new JLabel("", SwingConstants.CENTER);
JLabel labelLogo = new JLabel();
private static final int HEIGHT = 21;
public CustomStatusBar() {
setCommonFeatures(label0, 40, "Stuff 0");
setCommonFeatures(label1, 120, "Stuff 1");
setCommonFeatures(label2, 120, "Stuff 2");
setCommonFeatures(label3, 90, "Stuff 3");
labelLogo.setFont(new java.awt.Font("Dialog", 3, 12));
labelLogo.setForeground(Color.black);
labelLogo.setBorder(BorderFactory.createLoweredBevelBorder());
ImageIcon image = new ImageIcon("small.png");
labelLogo.setIcon(image);
labelLogo.setPreferredSize(new Dimension(40, HEIGHT));
labelLogo.setHorizontalAlignment(SwingConstants.CENTER);
setLayout(new GridBagLayout());
setMaximumSize(new Dimension(800, 40));
add(label0, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 50, 0));
add(label1, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 50, 0));
add(label2, new GridBagConstraints(2, 0, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 50, 0));
add(label3, new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 50, 0));
add(labelLogo, new GridBagConstraints(4, 0, GridBagConstraints.REMAINDER, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 50, 0));
}
private void setCommonFeatures(JLabel label, int width, String msg) {
label.setBackground(UIManager.getColor("ScrollBar.track"));
label.setForeground(Color.black);
label.setBorder(BorderFactory.createLoweredBevelBorder());
label.setPreferredSize(new Dimension(width, HEIGHT));
label.setText(" " + msg);
}
}}
Small.png image file:
When opened at scaling 100%, it looks good:
But when changing the scaling to 175%:
the pixels start to show up (open link to the picture to see better)
Now, what I have done is to replace the logo with one with a higher resolution:
Now, I am struck as I do not know how to make it fit in the space available for it and display properly when scaled. If i redimension the image from the java code as seen here, it will display properly for 100%, but for 175% scaling the pixels become visible again, like using the small.png file.
Which is the correct way of solving this?
Thank you.
The workaround is the following (only tested on Windows 10):
Locate the javaw.exe that the application is using (it very important to apply the following to javaw.exe, not java.exe)
Right click -> Properties -> Compatibility tab
Click button Change high DPI settings
Check Override high DPI scaling behavior. Scaling performed by: Select System in the combobox.
Press OK twice and restart the application
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.
I am new in Java and am doing some window application for my college.
I am trying to do some kind of menu with three buttons in start, and when one of buttons is clicked it's supposed to create a JPanel with two more buttons, but my code doesn't work.
Here is the code:
import java.awt.*;
public class mainScreen extends JFrame {
private JPanel contentPane;
public mainScreen() {
super("Aplikacija za atletska natjecanja");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(0, 0, screenSize.width, screenSize.height);
contentPane = new JPanel();
contentPane.setBackground(SystemColor.info);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
setContentPane(contentPane);
JPanel top = new JPanel();
top.setBounds(200, 11, screenSize.width - 400, screenSize.height - (screenSize.height - 100));
contentPane.add(top);
JPanel mainMenu = new JPanel();
mainMenu.setBounds(200, 110, screenSize.width - 400, screenSize.height - (screenSize.height - 30));
contentPane.add(mainMenu);
mainMenu.setLayout(new GridLayout(1, 0, 0, 0));
JButton btnTrkacke = new JButton("Trka\u010Dke");
btnTrkacke.setBackground(SystemColor.text);
mainMenu.add(btnTrkacke);
btnTrkacke.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JPanel panTrk = new JPanel();
panTrk.setBounds(201, 140, (screenSize.width - 400) / 3, 30);
contentPane.add(panTrk);
panTrk.setLayout(new GridLayout(1, 0, 0, 0));
JButton btnTrkAtl = new JButton("Atleti\u010Dari");
btnTrkAtl.setBackground(SystemColor.text);
panTrk.add(btnTrkAtl);
JButton btnTrkDisc = new JButton("Discipline");
btnTrkDisc.setBackground(SystemColor.text);
panTrk.add(btnTrkDisc);
}
});
JButton btnSkakacke = new JButton("Skaka\u010Dke");
btnSkakacke.setBackground(SystemColor.text);
mainMenu.add(btnSkakacke);
JButton btnBacacke = new JButton("Baca\u010Dke");
btnBacacke.setBackground(SystemColor.text);
mainMenu.add(btnBacacke);
}
}
That same panel should also be created when I click on the other two buttons, but on other the position... Is it better to create class for that pane and then call it when button is clicked?
You're forgetting to call revalidate and repaint on the contentPane after changing its components:
contentPane.revalidate();
contentPane.repaint();
e.g.,
#Override
public void actionPerformed(ActionEvent e) {
JPanel panTrk = new JPanel();
panTrk.setBounds(201, 140, (screenSize.width - 400) / 3, 30);
contentPane.add(panTrk);
panTrk.setLayout(new GridLayout(1, 0, 0, 0));
JButton btnTrkAtl = new JButton("Atleti\u010Dari");
btnTrkAtl.setBackground(SystemColor.text);
panTrk.add(btnTrkAtl);
JButton btnTrkDisc = new JButton("Discipline");
btnTrkDisc.setBackground(SystemColor.text);
panTrk.add(btnTrkDisc);
contentPane.revalidate(); // ***** added *****
contentPane.repaint(); // ***** added *****
}
revalidate tells the container to re-lay out its components.
repaint requests to the paint manager that the component and any children should be re-drawn.
As an aside: you're using null layout manager and absolute positioning with setBounds(...), and you really don't want to do this. While to a newbie this seems the best way to create complex GUI's, the more you deal with Swing GUI creation, the more you will find that doing this will put your GUI in a straight-jacket, painting it in a very tight corner and making it very hard to extend or enhance. Just don't do this.
will ask here, coz its same project
so it shuld work like this.... 3 buttons, and under each button is hiden panel with two button, so whan some button is clicked under him shuld show panel, whan some ather button is clicked under him shuld show panel, but ather two panels shuld hide.... and this works great until some button is clicked 2 time in a row, after that whan i click some ather button panel under that button dont wont to hide..
here is the code
JPanel mainMenu = new JPanel();
mainMenu.setBounds(200, 110, screenSize.width - 400, screenSize.height - (screenSize.height - 30));
contentPane.add(mainMenu);
mainMenu.setLayout(new GridLayout(1, 0, 0, 0));
JButton btnTrkacke = new JButton("Trka\u010Dke");
btnTrkacke.setBackground(SystemColor.text);
mainMenu.add(btnTrkacke);
btnTrkacke.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
panTrk = new JPanel();
panTrk.setBounds(201, 140, (screenSize.width - 400) / 3, 30);
contentPane.add(panTrk);
panTrk.setLayout(new GridLayout(1, 0, 0, 0));
JButton btnTrkAtl = new JButton("Atleti\u010Dari");
btnTrkAtl.setBackground(SystemColor.text);
panTrk.add(btnTrkAtl);
JButton btnTrkDisc = new JButton("Discipline");
btnTrkDisc.setBackground(SystemColor.text);
panTrk.add(btnTrkDisc);
contentPane.revalidate();
contentPane.repaint();
panSka.setVisible(false);
panBac.setVisible(false);
}
});
JButton btnSkakacke = new JButton("Skaka\u010Dke");
btnSkakacke.setBackground(SystemColor.text);
mainMenu.add(btnSkakacke);
btnSkakacke.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
panSka = new JPanel();
panSka.setBounds(201 + (screenSize.width - 400) / 3, 140, (screenSize.width - 400) / 3, 30);
contentPane.add(panSka);
panSka.setLayout(new GridLayout(1, 0, 0, 0));
JButton btnSkaAtl = new JButton("Atleti\u010Dari");
btnSkaAtl.setBackground(SystemColor.text);
panSka.add(btnSkaAtl);
JButton btnSkaDisc = new JButton("Discipline");
btnSkaDisc.setBackground(SystemColor.text);
panSka.add(btnSkaDisc);
contentPane.revalidate();
contentPane.repaint();
panTrk.setVisible(false);
panBac.setVisible(false);
}
});
JButton btnBacacke = new JButton("Baca\u010Dke");
btnBacacke.setBackground(SystemColor.text);
mainMenu.add(btnBacacke);
btnBacacke.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
panBac = new JPanel();
panBac.setBounds(201 + (screenSize.width - 400) / 3 * 2, 140, (screenSize.width - 400) / 3, 30);
contentPane.add(panBac);
panBac.setLayout(new GridLayout(1, 0, 0, 0));
JButton btnBacAtl = new JButton("Atleti\u010Dari");
btnBacAtl.setBackground(SystemColor.text);
panBac.add(btnBacAtl);
JButton btnBacDisc = new JButton("Discipline");
btnBacDisc.setBackground(SystemColor.text);
panBac.add(btnBacDisc);
contentPane.revalidate();
contentPane.repaint();
panSka.setVisible(false);
panTrk.setVisible(false);
}
});
I use SpringLayout on my form, But as you see, its look isn't good (large and bad size)!
public class t8 extends JFrame {
JButton okButton, cancellButton;
JTextField idTF, nameTf;
JLabel idlbl, namelbl;
public t8() {
add(createPanel(), BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 500);
setLocation(400, 100);
setVisible(true);
}
public static void main(String[] args) {
new t8();
}
public JPanel createPanel() {
JPanel panel = new JPanel();
okButton = new JButton("Ok");
cancellButton = new JButton("Cancel");
idTF = new JTextField(10);
nameTf = new JTextField(10);
idlbl = new JLabel("ID");
namelbl = new JLabel("Name");
panel.add(idlbl);
panel.add(idTF);
panel.add(namelbl);
panel.add(nameTf);
panel.add(okButton);
panel.add(cancellButton);
panel.setLayout(new SpringLayout());
SpringUtilities.makeCompactGrid(panel, 3, 2, 20, 50, 50, 100);
return panel;
}
}
I change makeCompactGrid numbers, But was not success!
(The width of JTextFields are large, and my button's size are different)
If you don't care about the layout manager, but only care about the layout, then you should use a GridLayout, or if you don't want all component to be the same size, a GridBagLayout. Here's how with a grid layout (only the modified method is shown):
public JPanel createPanel() {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout());
okButton = new JButton("Ok");
cancellButton = new JButton("Cancel");
idTF = new JTextField(10);
nameTf = new JTextField(10);
idlbl = new JLabel("ID");
namelbl = new JLabel("Name");
panel.add(idlbl);
panel.add(idTF);
panel.add(namelbl);
panel.add(nameTf);
panel.add(okButton);
panel.add(cancellButton);
return panel;
}
And with a GridBagLayout:
public JPanel createPanel() {
JPanel panel = new JPanel();
GridBagLayout gb = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
panel.setLayout(gb);
okButton = new JButton("Ok");
cancellButton = new JButton("Cancel");
idTF = new JTextField(10);
nameTf = new JTextField(10);
idlbl = new JLabel("ID");
namelbl = new JLabel("Name");
add(panel, idlbl, 0, 0, 1, 1, gb, gbc, false);
add(panel, idTF, 0, 1, 1, 1, gb, gbc, true);
add(panel, namelbl, 1, 0, 1, 1, gb, gbc, false);
add(panel, nameTf, 1, 1, 1, 1, gb, gbc, true);
add(panel, okButton, 2, 0, 1, 1, gb, gbc, false);
add(panel, cancellButton, 2, 1, 1, 1, gb, gbc, true);
return panel;
}
private void add(Container outer, Component c, int x, int y, int w, int h, GridBagLayout gb, GridBagConstraints gbc, boolean wide) {
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = w;
gbc.gridheight = h;
if (wide) {
gbc.weightx = 100;
} else {
gbc.weightx = 0;
}
gb.setConstraints(c, gbc);
outer.add(c);
}
I believe that the extra GridBagLayout complexity just might be worth it.
I would suggest you to use Netbeans drag and drop tool which will allow you to set the components physically and will also give you the preview.
If you want to do it with code just use the free layout and set the location and size of every component manually By setSize() and setLocation() methods, although this will require more lines of code but will ensure you that all the components are in their correct position.
Here is my code:
final JTextArea textArea = new JTextArea();
textArea.setFont(new Font("MS UI Gothic", Font.PLAIN, 13));
textArea.setLineWrap(true);
textArea.setBounds(77, 310, 474, 136);
//contentPane.add(textArea); (edited...still the same problem persists..)
JScrollPane sbrText = new JScrollPane(textArea);
sbrText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
contentPane.add(sbrText);
When ever I try with this,the text area is not visible..(I am using Eclipse's Window Builder plugin and layout as "Absolute Layout")..
Here I have done, the same thingy using Nested Layout, have a look at the code example :
import java.awt.*;
import javax.swing.*;
public class WelcomeExample
{
private JPanel headerPanel;
private JButton logoutButton;
private JPanel leavePanel;
private JRadioButton casualRButton;
private JRadioButton specialRButton;
private JRadioButton sickRButton;
private JRadioButton privilegeRButton;
private ButtonGroup radioButtonGroup;
private JTextField leaveDaysField;
private JButton checkLeaveButton;
private JTextArea notesArea;
private JScrollPane notesScroller;
private JButton applyLeaveButton;
private String headerText = "<html><body><h1><font " +
"color=\"red\">Welcome : </font><font color" +
"=\"blue\">Code Zero</font></h1></body></html>";
private void displayGUI()
{
JFrame frame = new JFrame("Welcome");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(5, 5));
contentPane.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
headerPanel = getHeaderPanel();
leavePanel = getLeavePanel();
contentPane.add(headerPanel, BorderLayout.PAGE_START);
contentPane.add(leavePanel, BorderLayout.CENTER);
contentPane.add(getApplyPanel(), BorderLayout.PAGE_END);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel getHeaderPanel()
{
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout(5, 5));
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JLabel headerLabel = new JLabel(headerText, JLabel.CENTER);
JPanel buttonPanel = new JPanel();
logoutButton = new JButton("Logout");
buttonPanel.add(logoutButton);
panel.add(headerLabel, BorderLayout.CENTER);
panel.add(buttonPanel, BorderLayout.LINE_END);
panel.add(new JSeparator(
SwingConstants.HORIZONTAL), BorderLayout.PAGE_END);
return panel;
}
private JPanel getLeavePanel()
{
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout(5, 5));
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JPanel leaveHeaderPanel = new JPanel();
leaveHeaderPanel.setLayout(new GridLayout(0, 1, 5, 5));
leaveHeaderPanel.setBorder(
BorderFactory.createTitledBorder("Choose a leave type : "));
JPanel leaveTypePanel = new JPanel();
leaveTypePanel.setLayout(new FlowLayout(
FlowLayout.LEFT, 5, 5));
casualRButton = new JRadioButton("Casual Leave");
specialRButton = new JRadioButton("Special Leave");
sickRButton = new JRadioButton("Sick Leave");
privilegeRButton = new JRadioButton("Privilege Leave");
radioButtonGroup = new ButtonGroup();
radioButtonGroup.add(casualRButton);
radioButtonGroup.add(specialRButton);
radioButtonGroup.add(sickRButton);
radioButtonGroup.add(privilegeRButton);
leaveTypePanel.add(casualRButton);
leaveTypePanel.add(specialRButton);
leaveTypePanel.add(sickRButton);
leaveTypePanel.add(privilegeRButton);
JPanel applyLeavePanel = new JPanel();
applyLeavePanel.setLayout(new FlowLayout(
FlowLayout.LEFT, 5, 5));
JLabel applyLeaveLabel = new JLabel(
"Apply for (No. of days) : ", JLabel.CENTER);
leaveDaysField = new JTextField(5);
checkLeaveButton = new JButton("Check Leave Availability");
applyLeavePanel.add(applyLeaveLabel);
applyLeavePanel.add(leaveDaysField);
applyLeavePanel.add(checkLeaveButton);
leaveHeaderPanel.add(leaveTypePanel);
leaveHeaderPanel.add(applyLeavePanel);
notesArea = new JTextArea(10, 10);
notesScroller = new JScrollPane();
notesScroller.setBorder(
BorderFactory.createTitledBorder(
"Leave Note (Max. 200 Characters) : "));
notesScroller.setViewportView(notesArea);
panel.add(leaveHeaderPanel, BorderLayout.PAGE_START);
panel.add(notesScroller, BorderLayout.CENTER);
return panel;
}
private JPanel getApplyPanel()
{
JPanel panel = new JPanel();
applyLeaveButton = new JButton("Apply");
panel.add(applyLeaveButton);
return panel;
}
public static void main(String[] args)
{
Runnable runnable = new Runnable()
{
#Override
public void run()
{
new WelcomeExample().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
OUTPUT :
I don't think you need to do contentPane.add(textArea);. It is this line that is causing the problem. Comment out this and your code should work fine.
See this answer, it might help you.
The following code runs fine at my place :
final JTextArea textArea = new JTextArea();
textArea.setFont(new Font("MS UI Gothic", Font.PLAIN, 13));
textArea.setLineWrap(true);
textArea.setBounds(77, 310, 474, 136);
JScrollPane sbrText = new JScrollPane(textArea);
sbrText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
frame.getContentPane().add(sbrText);//contentPane.add(sbrText);
frame.setVisible(true);
If your code is not running fine then you must have some other error probably related to your contentpane.
Ok...I finally got it to work...I specified the same set bounds in the scroll pane instead of the text area.. Here is the code.!!! ^_^
final JTextArea textArea = new JTextArea();
textArea.setFont(new Font("MS UI Gothic", Font.PLAIN, 13));
textArea.setLineWrap(true);
//textArea.setBounds(77, 310, 474, 136);
JScrollPane scroll = new JScrollPane (textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scroll.setBounds(77, 310, 474, 136);
contentPane.add(scroll);
Here are the screenshots:
Previous: http://oi40.tinypic.com/11jyum0.jpg
Now: http://oi44.tinypic.com/2s9vdvt.jpg