setVgap(0), setHgap(0) not working in gridlayout? - java

I am trying to build an app that has some components such as buttons, labels, text fields, a menu bar and a picture (I didn't tackle the image problem yet so there is no code for that).
So I made a grid layout for my frame and constructed 6 panels with their respective components as explained in the code bellow. But when I run it it doesn't show anything at first, just a blank frame, unless I maximize the window. Because when I do that everything appears to be working fine. Except for 2 things.
I have setVgap() and setHgap() to zero but there are still gaps between the components. and the 2nd thing is that the BorderLayout.NORTH, (..).SOUTH etc don't seem to work either.
public class Window extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel menupanel = new JPanel();
public Window() {
super("Image Application");
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
requestFocus();
// Setting Layout
GridLayout grid = new GridLayout(6, 0, 0, 0);
//grid.setVgap(0);
//grid.setHgap(0);
this.setLayout(grid);
// Menu
JMenuBar menubar = new JMenuBar();
JMenu menu = new JMenu("Options");
JButton button = new JButton("Reset");
// Buttons
menupanel.add(new JButton("Allign Left"));
menupanel.add(new JButton("Allign Center"));
menupanel.add(new JButton("Allign Right"));
// Picture
JPanel p1 = new JPanel();
// 2x JLabels and ComboBoxes to get the preferred dimensions
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
JLabel b2 = new JLabel("Width: ");
JLabel b3 = new JLabel("Height: ");
JTextField box1 = new JTextField(25);
JTextField box2 = new JTextField(25);
// Resize Button
JPanel p4 = new JPanel();
JButton b4 = new JButton("Resize");
// Adding Components to their panels
p2.add(b2);
p2.add(box1);
p3.add(b3);
p3.add(box2);
p4.add(b4);
menu.add(button);
menubar.add(menu);
// add all of the panels to JFrame
this.add(menupanel);
this.add(p1, BorderLayout.NORTH);
this.add(p2, BorderLayout.SOUTH);
this.add(p3, BorderLayout.WEST);
this.add(p4, BorderLayout.EAST);
this.setJMenuBar(menubar);
pack();
setVisible(true);
}
public static void main(String args[]) {
Window w = new Window();
}
}
Any ideas?
~EDIT1 changed according to first 2 comments, the pack(); seems to fix the problem that i needed to maximise the window to see the comp's ( -Thanks ), but the setVgap() problem remains.
~EDIT2 when I run it this window is shown:
While I want it to look more like this:
AGAIN Ignore the picture
~EDIT3 Well, I changed the value that was passed in the constructor for the Hgap and it does change accordingly for different values but it seems that zero Hgap is still ~10 pixels wide?! Also I noted that the gap doesn't change between the menubar and the first Jbuttons, but only for the ret of the components.
~EDIT4 It also works for negative int's..?! I am lost here..

please to compare, you should using second parameter for GridLayout, then setVgap() will works (frame.setLayout(new GridLayout(6, 0, 5, 5));), here is only zero value,
Window is reserved word in Java for awt.Window, don't to use this Object name as class name
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class MyWindow {
private static final long serialVersionUID = 1L;
private JPanel menupanel = new JPanel();
private JFrame frame = new JFrame("Image Application");
public MyWindow() {
// Menu
JMenuBar menubar = new JMenuBar();
JMenu menu = new JMenu("Options");
JButton button = new JButton("Reset");
// Buttons
menupanel.add(new JButton("Allign Left"));
menupanel.add(new JButton("Allign Center"));
menupanel.add(new JButton("Allign Right"));
// Picture
JPanel p1 = new JPanel();
p1.setBackground(Color.RED);
// 2x JLabels and ComboBoxes to get the preferred dimensions
JPanel p2 = new JPanel();
p2.setBackground(Color.ORANGE);
JLabel b2 = new JLabel("Width: ");
p2.add(b2);
JTextField box1 = new JTextField(25);
p2.add(box1);
JPanel p3 = new JPanel();
p3.setBackground(Color.BLUE);
JLabel b3 = new JLabel("Height: ");
JTextField box2 = new JTextField(25);
p3.add(b3);
p3.add(box2);
// Resize Button
JPanel p4 = new JPanel();
p4.setBackground(Color.MAGENTA);
JButton b4 = new JButton("Resize");
// Adding Components to their panels
p4.add(b4);
menu.add(button);
menubar.add(menu);
// add all of the panels to JFrame
frame.setLayout(new GridLayout(6, 0, 5, 5));
frame.add(menupanel);
frame.add(p1);
frame.add(p2);
frame.add(p3);
frame.add(p4);
frame.setJMenuBar(menubar);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
MyWindow w = new MyWindow();
}
});
}
}

Related

How do I put two Jpanels/Jbuttons in the borderlayout north section?

How do I display two JPanels in the 'North' in borderlayout?
Here's and example code that outputs a GUI with three distinct rows, Top, Middle, Bottom. There's one button covering the first row, 3 buttons covering the second row, and one covering the bottom row.
package borderLayoutDemo;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
public class BorderLayoutDemo {
public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame fj = new JFrame("Demonstration of Border Layout");
fj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton jbtn1 = new JButton("UP");
JButton jbtn2 = new JButton("DOWN");
JButton jbtn3 = new JButton("LEFT");
JButton jbtn4 = new JButton("RIGHT");
JButton jbtn5 = new JButton("MIDDLE");
JPanel pnl = new JPanel();
pnl.setLayout(new BorderLayout());
pnl.add(jbtn1, BorderLayout.NORTH);
pnl.add(jbtn2, BorderLayout.SOUTH);
pnl.add(jbtn3, BorderLayout.WEST);
pnl.add(jbtn4, BorderLayout.EAST);
pnl.add(jbtn5, BorderLayout.CENTER);
fj.add(pnl);
fj.pack();
fj.setVisible(true);
}
}
Output of above code:
output of above code
However, I'd like there to be two jpanels in the North section so it'd make 4 "rows" like this:
|---------------button--------------| //north
|---------------button2-------------| //north
----------------center--------------- //center
|---------------button3-------------| //south
I've tried simply just adding it as follows:
pnl.add(jbtn1, BorderLayout.NORTH);
pnl.add(jbtn2, BorderLayout.NORTH);
But what happens here is the second button just replaces the first one:
|---------------button2-------------| //north
----------------center--------------- //center
|---------------button3-------------| //south
How would I get two rows in the north layout area?
Creating a more complex GUI is straightforward when you think of a GUI as a JFrame with as many JPanels as necessary to define the GUI.
Here's the GUI you were looking for.
I created a JPanel for each section of the JFrame (NORTH, CENTER, and SOUTH). Each of those JPanels used a BorderLayout so that when you expand the GUI, the NORTH and SOUTH buttons stay the same height.
Here's the complete runnable example code.
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class BorderLayoutDemo implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new BorderLayoutDemo());
}
#Override
public void run() {
JFrame fj = new JFrame("Demonstration of Border Layout");
fj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fj.add(createNorthPanel(), BorderLayout.NORTH);
fj.add(createCenterPanel(), BorderLayout.CENTER);
fj.add(createSouthPanel(), BorderLayout.SOUTH);
fj.pack();
fj.setLocationByPlatform(true);
fj.setVisible(true);
}
private JPanel createNorthPanel() {
JPanel panel = new JPanel(new BorderLayout());
JButton button1 = new JButton("North Button");
panel.add(button1, BorderLayout.NORTH);
JButton button2 = new JButton("North Button 2");
panel.add(button2, BorderLayout.SOUTH);
return panel;
}
private JPanel createCenterPanel() {
JPanel panel = new JPanel(new BorderLayout());
JButton button = new JButton("Center Button");
panel.add(button, BorderLayout.CENTER);
return panel;
}
private JPanel createSouthPanel() {
JPanel panel = new JPanel(new BorderLayout());
JButton button = new JButton("South Button");
panel.add(button, BorderLayout.SOUTH);
return panel;
}
}

How can I get the contents of my GUI to look a certain way? (Java)

So, I'm brand spankin' new to programming, so thanks in advance for your help. I'm trying to put this base 2 to base 10/base 10 to base 2 calculator I have made into a GUI. For the life of me I can't figure out how to nicely format it. I'm trying to make it look like the following: The two radio buttons on top, the input textfield bellow those, the convert button bellow that, the output field bellow that, and the clear button bellow that. Any ideas on how I can accomplish this?
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.*;
#SuppressWarnings("serial")
public class GUI extends JFrame implements ActionListener
{
private JTextField input;
private JTextField output;
private JRadioButton base2Button;
private JRadioButton base10Button;
private JButton convert;
private JButton clear;
private Container canvas = getContentPane();
private Color GRAY;
public GUI()
{
this.setTitle("Base 10-2 calc");
this.setLayout(new FlowLayout(FlowLayout.LEFT));
//this.setLayout(new GridLayout(2,2));
base2Button = new JRadioButton( "Convert to base 2");
base10Button = new JRadioButton( "Convert to base 10");
ButtonGroup radioGroup = new ButtonGroup();
radioGroup.add(base2Button);
radioGroup.add(base10Button);
JPanel radioButtonsPanel = new JPanel();
radioButtonsPanel.setLayout( new FlowLayout(FlowLayout.LEFT) );
radioButtonsPanel.add(base2Button);
radioButtonsPanel.add(base10Button);
canvas.add(radioButtonsPanel);
base2Button.setSelected( true );
base10Button.setSelected( true );
input = new JTextField(18);
//input = new JFormattedTextField(20);
canvas.add(input);
output = new JTextField(18);
//output = new JFormattedTextField(20);
canvas.add(output);
convert = new JButton("Convert!");
convert.addActionListener(this);
canvas.add(convert);
clear = new JButton("Clear");
clear.addActionListener(this);
canvas.add(clear);
output.setBackground(GRAY);
output.setEditable(false);
this.setSize(300, 200);
this.setVisible(true);
this.setLocation(99, 101);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
GUI app = new GUI();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();
if(s.equals("Convert!"))
{
String numS = input.getText();
int numI = Integer.parseInt(numS);
if(base2Button.isSelected())
{
output.setText(Integer.toBinaryString(Integer.valueOf(numI)));
}
if(base10Button.isSelected())
{
output.setText("" + Integer.valueOf(numS,2));
}
}
if(s.equals("Clear"))
{
input.setText("");
output.setText("");
}
}
}
For a simple layout, you could use a GridLayout with one column and then use a bunch of child panels with FlowLayout which align the components based on the available space in a single row. If you want more control, I'd suggest learning about the GridBagLayout manager which is a more flexible version of GridLayout.
public class ExampleGUI {
public ExampleGUI() {
init();
}
private void init() {
JFrame frame = new JFrame();
// Set the frame's layout to a GridLayout with one column
frame.setLayout(new GridLayout(0, 1));
frame.setPreferredSize(new Dimension(300, 300));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Child panels, each with FlowLayout(), which aligns the components
// in a single row, until there's no more space
JPanel radioButtonPanel = new JPanel(new FlowLayout());
JRadioButton button1 = new JRadioButton("Option 1");
JRadioButton button2 = new JRadioButton("Option 2");
radioButtonPanel.add(button1);
radioButtonPanel.add(button2);
JPanel inputPanel = new JPanel(new FlowLayout());
JLabel inputLabel = new JLabel("Input: ");
JTextField textField1 = new JTextField(15);
inputPanel.add(inputLabel);
inputPanel.add(textField1);
JPanel convertPanel = new JPanel(new FlowLayout());
JButton convertButton = new JButton("Convert");
convertPanel.add(convertButton);
JPanel outputPanel = new JPanel(new FlowLayout());
JLabel outputLabel = new JLabel("Output: ");
JTextField textField2 = new JTextField(15);
outputPanel.add(outputLabel);
outputPanel.add(textField2);
// Add the child panels to the frame, in order, which all get placed
// in a single column
frame.add(radioButtonPanel);
frame.add(inputPanel);
frame.add(convertPanel);
frame.add(outputPanel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
ExampleGUI example = new ExampleGUI();
}
}
The end result:

Adding an action listener to JButtons created by a loop

I am having trouble finding a way to invoke an action listener that returns the value of the button clicked in the text area at the bottom.
I made the buttons using a for loop and did not expressly give the buttons a name so I do not know how to reference them when trying to incorporate an ActionListener.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class buttoner implements ActionListener {
//JFrame
JFrame frame = new JFrame("Button Game");
//Make JPanels
JPanel panelLabel = new JPanel();
JPanel buttonGrid = new JPanel(new GridLayout(0,10));
JPanel bottomPanel = new JPanel();
//JLabel
private JLabel label1 = new JLabel("The Button Game");
public buttoner() {
//set layout
frame.setLayout(new BorderLayout());
frame.add(panelLabel, BorderLayout.NORTH);
frame.add(buttonGrid, BorderLayout.CENTER);
frame.add(bottomPanel, BorderLayout.SOUTH);
//Set stuff
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,700);
frame.setVisible(true);
//Change label color
label1.setForeground(Color.RED);
//add Label
panelLabel.add(label1);
//add Buttons
for (int i = 1; i <= 60; i++) {
String val = Integer.toString(i);
buttonGrid.add(new JButton(val));
}
//Add JText Area to bottom JPanel
String num = "value";
JTextArea jta = new JTextArea(num, 1, 1);
bottomPanel.add(jta);
frame.pack();
}
public static void main(String args[]){
buttoner gui = new buttoner();
}
public void actionPerformed(ActionEvent a) {
}
}
I created an action listener to put the value in the text area at the bottom of the GUI.
I fixed a few problems with your code.
In the main method, I called the SwingUtilities invokeLater method to put the Swing GUI on the Event Dispatch thread (EDT). Swing components must be created and updated on the EDT.
The name of a Java class must start with a capital letter.
It's safer to put your Swing components on a JPanel, rather than add them directly to a JFrame.
I separated the code that creates the JFrame from the code that creates the JPanels. It should be easier for any reader of your code, including yourself, to understand what's going on.
In the createMainPanel method, I grouped the code so that everything having to do with the buttonGrid JPanel, to take one instance, is in one place in the code.
I added the action listener to the code that creates the buttonGrid JPanel.
I wrote action listener code that updates the JTextArea with the left clicked button label.
Here's the corrected code.
package com.ggl.testing;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class Buttoner implements ActionListener {
// JFrame
private JFrame frame = new JFrame("Button Game");
// Make JPanels
private JPanel panelLabel = new JPanel();
private JPanel buttonGrid = new JPanel(new GridLayout(0, 10));
private JPanel bottomPanel = new JPanel();
// JLabel
private JLabel label1 = new JLabel("The Button Game");
private JTextArea jta;
public Buttoner() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
// Change label color
label1.setForeground(Color.RED);
// add Label
panelLabel.add(label1);
panel.add(panelLabel, BorderLayout.NORTH);
// add Buttons
for (int i = 1; i <= 60; i++) {
String val = Integer.toString(i);
JButton button = new JButton(val);
button.addActionListener(this);
buttonGrid.add(button);
}
panel.add(buttonGrid, BorderLayout.CENTER);
// Add JText Area to bottom JPanel
String num = "value";
jta = new JTextArea(num, 1, 1);
jta.setEditable(false);
bottomPanel.add(jta);
panel.add(bottomPanel, BorderLayout.SOUTH);
return panel;
}
public static void main(String args[]) {
Runnable runnable = new Runnable() {
#Override
public void run() {
new Buttoner();
}
};
SwingUtilities.invokeLater(runnable);
}
public void actionPerformed(ActionEvent a) {
JButton button = (JButton) a.getSource();
jta.setText(button.getText());
}
}
Try creating an array of buttons and add the newly created button to the array. See comments.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class buttoner implements ActionListener {
//JFrame
JFrame frame = new JFrame("Button Game");
//Make JPanels
JPanel panelLabel = new JPanel();
JPanel buttonGrid = new JPanel(new GridLayout(0,10));
JPanel bottomPanel = new JPanel();
//JLabel
private JLabel label1 = new JLabel("The Button Game");
private JButton buttons[] = new JButton[60]; //create an array of button for future reference
public buttoner() {
//set layout
frame.setLayout(new BorderLayout());
frame.add(panelLabel, BorderLayout.NORTH);
frame.add(buttonGrid, BorderLayout.CENTER);
frame.add(bottomPanel, BorderLayout.SOUTH);
//Set stuff
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,700);
frame.setVisible(true);
//Change label color
label1.setForeground(Color.RED);
//add Label
panelLabel.add(label1);
//add Buttons
for (int i = 1; i <= 60; i++) {
String val = Integer.toString(i);
JButton btn = new JButton(val);
btn.addActionListener(this); //add an actionListener right away
buttons[i] = btn; //add the button in the array for future reference
buttonGrid.add(btn);
}
//Add JText Area to bottom JPanel
String num = "value";
JTextArea jta = new JTextArea(num, 1, 1);
bottomPanel.add(jta);
frame.pack();
}
public static void main(String args[]){
buttoner gui = new buttoner();
}
public void actionPerformed(ActionEvent a) {
}
}

usage of BorderLayout

I am having a problem with BorderLayout, that was set to the green JPanel side. It does not display elements on the EAST in a row order. Do I have to combine this with GridBagLayout ? Could someone advice me how should I tackle this problem?
Basically the problem is of displaying objects inside green area below when I am using
Current layout:
My aim is to achieve this layout:
public class GUILayout {
public static void main(String[] args) {
JFrame jf = new JFrame();
JButton jbO = new JButton("CSIS0396");
JButton jbl = new JButton("Final");
JButton jb2 = new JButton("2010");
JButton jb3 = new JButton("Exam");
JPanel panel = new JPanel();
JPanel panel2 = new JPanel();
JButton object_btn = new JButton("Object");
JButton oriented_btn = new JButton("Oriented");
JButton programming_btn = new JButton("Programming");
JButton and_btn = new JButton("and");
JButton java_btn = new JButton("Java");
BorderLayout layout = new BorderLayout();
panel.setLayout(layout);
panel2.setLayout(layout);
panel.add(BorderLayout.CENTER,object_btn);
panel.add(BorderLayout.WEST,oriented_btn);
panel.add(BorderLayout.WEST,programming_btn);
panel.add(BorderLayout.WEST,and_btn);
panel.add(BorderLayout.WEST,java_btn);
panel2.add(BorderLayout.NORTH, jbO);
panel2.add(BorderLayout.SOUTH, jb2);
panel2.add(BorderLayout.WEST, jbl);
panel2.add(BorderLayout.EAST, jb3);
panel.setBackground(Color.GREEN);
panel2.setBackground(Color.RED);
jf.getContentPane().add(panel);
jf.getContentPane().add(panel2, BorderLayout.EAST);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(400, 300);
jf.setVisible(true);
}
}
don't share same layout for multiple component and use box layout for left panel to positioning buttons
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GUILayout {
public static void main(String[] args) {
JFrame jf = new JFrame();
JButton jbO = new JButton("CSIS0396");
JButton jbl = new JButton("Final");
JButton jb2 = new JButton("2010");
JButton jb3 = new JButton("Exam");
JPanel panel = new JPanel();
JPanel panel2 = new JPanel();
JButton object_btn = new JButton("Object");
JButton oriented_btn = new JButton("Oriented");
JButton programming_btn = new JButton("Programming");
JButton and_btn = new JButton("and");
JButton java_btn = new JButton("Java");
BorderLayout layout = new BorderLayout();
panel2.setLayout(layout);
panel.setLayout( new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.add(object_btn);
panel.add(oriented_btn);
panel.add(programming_btn);
panel.add(and_btn);
panel.add(java_btn);
panel2.add(BorderLayout.NORTH, jbO);
panel2.add(BorderLayout.SOUTH, jb2);
panel2.add(BorderLayout.WEST, jbl);
panel2.add(BorderLayout.EAST, jb3);
panel.setBackground(Color.GREEN);
panel2.setBackground(Color.RED);
jf.setLayout(new BorderLayout());
jf.getContentPane().add(panel ,BorderLayout.WEST);
jf.getContentPane().add(panel2, BorderLayout.EAST);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(400, 300);
jf.setVisible(true);
}
}
The first problem is that you're having your panels share a layout. You must use a new BorderLayout for each of them.
The second problem is that a BorderLayout can only have one component in each constraint position. When you try to add multiple components to the WEST position, each one replaces the one that was previously in that position:
panel.add(BorderLayout.WEST,oriented_btn);
// Implicitly removes oriented_btn from panel
panel.add(BorderLayout.WEST,programming_btn);
// Implicitly removes programming_btn from panel
panel.add(BorderLayout.WEST,and_btn);
// Implicitly removes and_btn from panel
panel.add(BorderLayout.WEST,java_btn);
The solution is to put them in their own container, such as a Box or a JPanel with a GridLayout:
Box box = Box.createVerticalBox();
// Or:
//JComponent box = new JPanel(new GridLayout(0, 1));
box.add(oriented_btn);
box.add(programming_btn);
box.add(and_btn);
box.add(java_btn);
panel.add(BorderLayout.WEST, box);

Changing background color of a ContentPane

I'm working on a GUI and I'm not having some trouble with panes.
My GUI is divided into two parts (topPane and bottomPane).
I have buttons and labels on both panes, but one of the button functions I wanted to change the background color, but it's not doing the job.
What I did is that I used a Container (called thisContentPane) to change the background color of my entire GUI.
Here is my current code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TempConverter extends JFrame
{
//Creating a contentPane down inside the inner class
Container thisContentPane;
//class scope variables : DO NOT CREATE THIS OBJECTS HERE.
JButton calculateButton, clearButton;
JTextField celsiusField, fahrenheitField, kelvinField;
//menu
JMenuBar menuBar = new JMenuBar();
JMenu backgroundColor = new JMenu("Background Color");
JMenu help = new JMenu("Help");
JMenuItem lightGray, white, black, blue, howToUse, about;
//constructor
TempConverter()
{
super("Temperature Converter App");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new BorderLayout());
this.setSize(400,200);;
this.setLocationRelativeTo(null);
//menuBar
this.setJMenuBar(menuBar);
menuBar.add(backgroundColor);
//adding JMenu to JMenuBar
menuBar.add(backgroundColor);
menuBar.add(help);
//adding JMenuItems
lightGray = backgroundColor.add("LIGHTGRAY");
white = backgroundColor.add("WHITE");
black = backgroundColor.add("BLACK");
blue = backgroundColor.add("BLUE");
howToUse = help.add("How To Use");
about = help.add("Help");
//babysitter
MaryPoppins babysitter = new MaryPoppins();
//adding action listener to the menu item
lightGray.addActionListener(babysitter);
white.addActionListener(babysitter);
black.addActionListener(babysitter);
blue.addActionListener(babysitter);
howToUse.addActionListener(babysitter);
about.addActionListener(babysitter);
//building JPanels
JPanel topPanel = new JPanel();
topPanel.setLayout(new GridLayout(3,2,0,20));
//add this to JFrame in centerzone
this.add(topPanel, BorderLayout.CENTER);
//bottom panel
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new FlowLayout());
//add this to JFrame in bottom
this.add(bottomPanel, BorderLayout.SOUTH);
//add components to the panels
//add the buttons
calculateButton = new JButton("Calculate");
clearButton = new JButton("Clear");
//add buttons
bottomPanel.add(calculateButton);
bottomPanel.add(clearButton);
//register listeners
calculateButton.addActionListener(babysitter);
clearButton.addActionListener(babysitter);
//add components to the top panel
JLabel labelOne = new JLabel("Celsius:");
JLabel secondOne = new JLabel("Fahrenheit:");
JLabel thirdOne = new JLabel("Kelvin:");
celsiusField = new JTextField("");
fahrenheitField = new JTextField("");
kelvinField = new JTextField("");
//add the label and text fields
topPanel.add(labelOne);
topPanel.add(celsiusField);
topPanel.add(secondOne);
topPanel.add(fahrenheitField);
topPanel.add(thirdOne);
topPanel.add(kelvinField);
this.setVisible(true);
} // end constructor
public static void main (String[] args) {
new TempConverter();
}
private class MaryPoppins implements ActionListener
{
//implement the abstract method from the interface
public void actionPerformed(ActionEvent ev)
{
thisContentPane = getContentPane();
if(ev.getActionCommand().equals("LIGHTGRAY"))
{
thisContentPane.setBackground(Color.lightGray);
}
else if (ev.getActionCommand().equals("BLUE"))
{
thisContentPane.setBackground(Color.BLUE);
}
else if(ev.getActionCommand().equals("WHITE") )
{
thisContentPane.setBackground(Color.WHITE);
}
else if (ev.getActionCommand().equals("BLACK"))
{
thisContentPane.setBackground(Color.BLACK);
}else if (ev.getActionCommand().equals("Clear"))
{
thisContentPane.setBackground(Color.BLACK);
}
else if (ev.getActionCommand().equals("BLACK"))
{
thisContentPane.setBackground(Color.BLACK);
}
}//end ActionPerformed()
}//end inner class
} // end class
When I click the buttons or menu items it doesn't do anything.
Your problem is that your contentPanel's background color is not "visible": your topPanel and your bottomPanel are on top of it :)
You should either do:
if (ev.getActionCommand().equals("LIGHTGRAY")) {
thisTopPanel.setBackground(Color.lightGray);
thisBottemPanel.setBackground(Color.lightGray);
}
... and do it for each of your if conditions (you know what I mean).
But that's not really the best way to go. An alternative that, in my opinion, makes perfect sense 'cause it reflects the exact behaviour you're looking for, would be:
topPanel.setOpaque(false);
bottomPanel.setOpaque(false);
I would obviously recommend the second option ;)
Also, since I'm at it, I prefer to use Color.LIGHTGRAY (and Color.BLACK, Color.WHITE, etc.) instead of Color.lightGrey, because these aliases respect the convention that states that constants must be upper-case.

Categories

Resources