Problem with Border Layout component positioning - java

I really don't know how to make the south panel appear without make the buttons go up. Maybe i need to change the layout from border layout to another one, I don't know...
---------->My Code:
public class a1211 extends JFrame {
private final JButton OK;
private final JButton cancel;
private final JButton setup;
private final JButton help;
private final JPanel buttonPanel;
private final JLabel printQuality;
private final JComboBox<String> quality;
private final String[] qualityNames = { "High", "Low", "Medium" };
private final JCheckBox printToFile;
private final JPanel southPanel;
public a1211() {
super("Printer");
OK = new JButton("OK");
cancel = new JButton("Cancel");
setup = new JButton("Setup...");
help = new JButton("Help");
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 1, 5, 5));
buttonPanel.add(OK);
buttonPanel.add(cancel);
buttonPanel.add(setup);
buttonPanel.add(help);
printQuality = new JLabel("Print Quality:");
quality = new JComboBox<String>(qualityNames);
printToFile = new JCheckBox("Print To File");
southPanel = new JPanel();
southPanel.add(printQuality);
southPanel.add(quality);
southPanel.add(printToFile);
add(buttonPanel, BorderLayout.EAST);
add(southPanel, BorderLayout.SOUTH);
}
public static void main(String[] args) {
a1211 a1211 = new a1211();
a1211.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
a1211.setSize(400, 150);
a1211.setVisible(true);
}
}
---------->What this code make:
---------->What it should make:

Related

How can I switch JFrames by clicking a JButton in Java?

I am writing a program and am unable to figure this out but I have a JButton called nextDay and I need it set up so once I click it, it switches to the JFrame day2 as the program starts out on day1. Any help is appreciated.
Here is my code. I have a separate Main method which I wont include as it shouldn't need to be changed
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class SoldierSimTest extends JFrame {
private final JButton decision1;
private final JButton decision2;
private final JButton decision3;
private final JButton decision4;
private final JTextField situation;
private JFrame day1;
private JFrame day2;
private JFrame day3;
private JFrame day4;
private JFrame day5;
private JFrame day6;
private JFrame day7;
private final JButton nextDay;
private final JButton exitGame;
private final JButton newGame;
public SoldierSimTest() {
decision1 = new JButton("Storm it");
decision2 = new JButton("Sneak around the flank");
decision3 = new JButton("Sneak up and grenade spam 'em");
decision4 = new JButton("Just dont");
situation = new JTextField("You and your squad are ordered to take
an enemy fort. How will you do so?");
situation.setEditable(false);
nextDay = new JButton("Next Day");
exitGame = new JButton("Exit Game");
newGame = new JButton("New Game");
JPanel decisionsPanel = new JPanel();
decisionsPanel.setLayout(new GridLayout(2, 2));
decisionsPanel.add(decision1);
decisionsPanel.add(decision2);
decisionsPanel.add(decision3);
decisionsPanel.add(decision4);
JPanel optionsPanel = new JPanel();
optionsPanel.setLayout(new GridLayout(1, 3));
optionsPanel.add(newGame);
optionsPanel.add(exitGame);
optionsPanel.add(nextDay);
JPanel situationsPanel = new JPanel();
optionsPanel.setLayout(new GridLayout(1, 1));
situationsPanel.add(situation);
Container contentPane = getContentPane();
contentPane.add(decisionsPanel, "South");
contentPane.add(optionsPanel, "North");
contentPane.add(situationsPanel, "Center");
}
}
You can use card layout to switch panels. I used Jpanels as it seems to be the best option to use. For this example I used 2 panels.
public class SoldierSimTest extends JFrame
{
private final JButton decision1;
private final JButton decision2;
private final JButton decision3;
private final JButton decision4;
private final JTextField situation;
private JPanel day1Panel = new JPanel();
private JPanel day2Panel = new JPanel();
private final JButton nextDay;
private final JButton exitGame;
private final JButton newGame;
final static String DAY1 = "Day1";
final static String DAY2 = "Day2";
public SoldierSimTest()
{
decision1 = new JButton("Storm it");
decision2 = new JButton("Sneak around the flank");
decision3 = new JButton("Sneak up and grenade spam 'em");
decision4 = new JButton("Just dont");
situation = new JTextField("You and your squad are ordered to take an enemy fort. How will you do so?");
situation.setEditable(false);
JPanel decisionsPanel = new JPanel();
decisionsPanel.setLayout(new GridLayout(2, 2));
decisionsPanel.add(decision1);
decisionsPanel.add(decision2);
decisionsPanel.add(decision3);
decisionsPanel.add(decision4);
JPanel situationsPanel = new JPanel();
situationsPanel.add(situation);
day1Panel.setLayout(new GridLayout(2, 1));
day1Panel.add(situationsPanel);
day1Panel.add(decisionsPanel);
JPanel cards = new JPanel(new CardLayout());
cards.add(day1Panel, DAY1);
cards.add(day2Panel, DAY2);
nextDay = new JButton("Next Day");
exitGame = new JButton("Exit Game");
newGame = new JButton("New Game");
nextDay.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
CardLayout cl = (CardLayout) (cards.getLayout());
cl.show(cards, DAY2);
}
});
JPanel optionsPanel = new JPanel();
optionsPanel.setLayout(new GridLayout(1, 3));
optionsPanel.add(newGame);
optionsPanel.add(exitGame);
optionsPanel.add(nextDay);
Container contentPane = getContentPane();
contentPane.add(optionsPanel, "North");
contentPane.add(cards, "Center");
}
}
The best way to do this if you don't necessarily need a new JFrame is the way #pavithraCS described. What I want to add is that normally, when you want a new "window" with different components to appear, you don't use a new JFrame because that opens a new window. Instead, using a new JPanel is more useful because you can stack them without having to switch to another window.
I hope this helps for the future.

Jpanel is not appearing in JFrame

So I am trying to get a JFrame to display a JPanel that has 5 other JPanels in it. I dont have any syntax errors and all that displays is a very small screen. I have been at this all day and have yet to find a solution.
public class addressPanel extends JPanel {
private JTextField nameT;
private JTextField addressT;
private JTextField cityT;
private JTextField stateT;
private JTextField zipCodeT;
private JTextField phoneNumberT;
private JLabel Title;
private JLabel addressTitle;
private JLabel nameL;
private JLabel addressL;
private JLabel stateL;
private JLabel cityL;
private JLabel zipCodeL;
private JLabel phoneNumberL;
private JLabel orderType;
private JRadioButton takeOut;
private JRadioButton delivery;
private JButton clear;
private JButton submit;
private JPanel addressTextPanel;
private JPanel addressLabelPanel;
private JPanel orderTypePanel;
private JPanel titlePanel;
private JPanel buttonsPanel;
public JPanel addressTextPanel() {
nameT = new JTextField(1);
addressT = new JTextField(2);
cityT = new JTextField(3);
stateT = new JTextField(4);
zipCodeT = new JTextField(5);
phoneNumberT = new JTextField(6);
Font font = new Font(Font.SERIF, Font.PLAIN, 24);
nameT.setFont(font);
addressT.setFont(font);
cityT.setFont(font);
stateT.setFont(font);
zipCodeT.setFont(font);
phoneNumberT.setFont(font);
JPanel addressTextPanel = new JPanel();
addressTextPanel.setPreferredSize(new Dimension(125, 250));
addressTextPanel.setLayout(new BoxLayout(addressTextPanel, BoxLayout.Y_AXIS));
addressTextPanel.add(nameT);
addressTextPanel.add(addressT);
addressTextPanel.add(cityT);
addressTextPanel.add(stateT);
addressTextPanel.add(zipCodeT);
addressTextPanel.add(phoneNumberT);
return addressTextPanel;
}
public JPanel addressLabelPanel() {
nameL = new JLabel("Name:");
addressL = new JLabel("Address:");
cityL = new JLabel("City:");
zipCodeL = new JLabel("Zip Code:");
stateL = new JLabel("State:");
phoneNumberL = new JLabel("Phone Number:");
nameL.setFont(nameL.getFont().deriveFont(24.0f));
addressL.setFont(addressL.getFont().deriveFont(24.0f));
cityL.setFont(cityL.getFont().deriveFont(24.0f));
zipCodeL.setFont(zipCodeL.getFont().deriveFont(24.0f));
stateL.setFont(stateL.getFont().deriveFont(24.0f));
phoneNumberL.setFont(phoneNumberL.getFont().deriveFont(24.0f));
JPanel addressLabelPanel = new JPanel();
addressLabelPanel.setPreferredSize(new Dimension(125, 250));
addressLabelPanel.setLayout(new BoxLayout(addressLabelPanel, BoxLayout.Y_AXIS));
addressLabelPanel.add(nameL);
addressLabelPanel.add(addressL);
addressLabelPanel.add(cityL);
addressLabelPanel.add(stateL);
addressLabelPanel.add(zipCodeL);
addressLabelPanel.add(phoneNumberL);
return addressLabelPanel;
}
public JPanel orderTypePanel() {
orderType = new JLabel("Order Type:");
takeOut = new JRadioButton("Take Out");
delivery = new JRadioButton("Delivery");
orderType.setFont(takeOut.getFont().deriveFont(24.0f));
takeOut.setFont(takeOut.getFont().deriveFont(24.0f));
delivery.setFont(delivery.getFont().deriveFont(24.0f));
JPanel orderTypePanel = new JPanel();
orderTypePanel.setPreferredSize(new Dimension(250, 125));
orderTypePanel.setLayout(new BoxLayout(orderTypePanel, BoxLayout.Y_AXIS));
orderTypePanel.add(orderType);
orderTypePanel.add(takeOut);
orderTypePanel.add(delivery);
return orderTypePanel;
}
public JPanel titlePanel() {
Title = new JLabel("Pizza Order Form");
addressTitle = new JLabel("Address");
Title.setFont(Title.getFont().deriveFont(36.0f));
addressTitle.setFont(addressTitle.getFont().deriveFont(36.0f));
JPanel titlePanel = new JPanel();
titlePanel.setPreferredSize(new Dimension(500, 100));
titlePanel.setLayout(new BoxLayout(titlePanel, BoxLayout.Y_AXIS));
titlePanel.add(Title);
titlePanel.add(addressTitle);
return titlePanel;
}
public JPanel buttonsPanel() {
clear = new JButton("Clear");
submit = new JButton("Submit");
clear.setFont(clear.getFont().deriveFont(24.0f));
submit.setFont(submit.getFont().deriveFont(24.0f));
JPanel buttonsPanel = new JPanel();
buttonsPanel.setPreferredSize(new Dimension(500, 100));
buttonsPanel.setLayout(new BoxLayout(buttonsPanel, BoxLayout.X_AXIS));
buttonsPanel.add(clear);
buttonsPanel.add(submit);
return buttonsPanel;
}
public addressPanel() {
JPanel addressParent = new JPanel(new BorderLayout());
addressParent.add(new titlePanel(), BorderLayout.NORTH);
addressParent.add(new orderTypePanel(), BorderLayout.WEST);
addressParent.add(new addressLabelPanel(), BorderLayout.CENTER);
addressParent.add(new addressTextPanel(), BorderLayout.EAST);
addressParent.add(new buttonsPanel(), BorderLayout.SOUTH);
}
public static void main(String[] args) {
// Create Main Panel
JFrame frame = new JFrame("");
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.getContentPane().add(new addressPanel());
// Color background = new Color(238,233,191);
// frame.getContentPane().setBackground(background);
frame.pack();
frame.setVisible(true);
}
}
Read your code. The program creates a JFrame. It creates an instance of addressPanel (which should be named AddressPanel). ANd it adds this addressPanel instance to the frame conent pane.
Now what is added to the addressPanel? Nothing:
public addressPanel()
{
JPanel addressParent = new JPanel(new BorderLayout());
addressParent.add (new titlePanel(), BorderLayout.NORTH);
addressParent.add (new orderTypePanel(), BorderLayout.WEST);
addressParent.add (new addressLabelPanel(), BorderLayout.CENTER);
addressParent.add (new addressTextPanel(), BorderLayout.EAST);
addressParent.add (new buttonsPanel(), BorderLayout.SOUTH);
}
The constructor of addressPanel creates another panel (addressParent), adds plenty of things to this addressParent panel, but doesn't add anything to this, the addressPanel. So the addressPanel is empty.
Please respect the Java naming conventions to make your code readable. Classes start with an uppercase letter.

how to select JRadioButton depending on button

see my problem start form this piece of code i add all the addActionListener for the button
but when it come to the Radio button it use addItemListenet but i implements ActionListener only how i will implements ItemListener so i can set Law when ever the user Select sw form the radio button and click on add item~ it will add the item to the right array i made before
exitButton.addActionListener(new ButtonWatcher());
addButton.addActionListener(new ButtonWatcher());
copyButton.addActionListener(new ButtonWatcher());
showButton.addActionListener(new ButtonWatcher());
rButton.addItemListenet(new ButtonWatcher());
}
private class ButtonWatcher implements ActionListener{
public void actionPerformed(ActionEvent a){
Object buttonPressed=a.getSource();
if(buttonPressed.equals(exitButton))
{
System.exit(0);
}
if(buttonPressed.equals(addButton) && rButton1.isSelected())
{
//do the action
}
full code
package item;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
*
* #author isslam
*/
public class MyFrameMain extends JFrame{
Equipment newq = new Equipment();
private final JLabel iLabel;
private final JLabel nLabel;
private final JTextField iJTextField;
private final JTextField nJTextField;
private final JTextField swTextField;
private final JTextField hwTextField;
private final JLabel jItemCounter;
private final JTextArea reSoulte;
private final JButton addButton;
private final JButton showButton;
private final JButton copyButton;
private final JButton exitButton;
public MyFrameMain(String title){
setSize(500, 500);
setTitle(title);
setDefaultCloseOperation(MyFrameMain.EXIT_ON_CLOSE);
iJTextField = new JTextField();
nJTextField = new JTextField();
swTextField = new JTextField();
hwTextField = new JTextField();
nLabel = new JLabel("ID: ");
iLabel = new JLabel("Name: ");
jItemCounter = new JLabel("Number of current Item");
reSoulte = new JTextArea(15,20);
reSoulte.setEditable(false);
reSoulte.setText("Array is empty");
addButton = new JButton("Add an item into the Array");
showButton = new JButton("Show all items in the Array");
copyButton = new JButton("Copy Array into File");
exitButton = new JButton("Exite");
JRadioButton rButton1 = new JRadioButton("SW Version",false);
JRadioButton rButton2 = new JRadioButton("HW Type",false);
JRadioButton rButton3 = new JRadioButton("General",true);
ButtonGroup BGroup = new ButtonGroup();
BGroup.add(rButton1);
BGroup.add(rButton2);
BGroup.add(rButton3);
JPanel rbPanel = new JPanel(new GridLayout(5,1));
rbPanel.add(nLabel);
rbPanel.add(iLabel);
rbPanel.add(rButton1);
rbPanel.add(rButton2);
rbPanel.add(rButton3);
JPanel bpanel = new JPanel(new GridLayout(2,2));
bpanel.add(addButton);
bpanel.add(showButton);
bpanel.add(copyButton);
bpanel.add(exitButton);
JPanel jtfPanel = new JPanel(new GridLayout(5,1));
jtfPanel.add(iJTextField);
jtfPanel.add(nJTextField);
jtfPanel.add(swTextField);
jtfPanel.add(hwTextField);
jtfPanel.add(jItemCounter);
JPanel topPanel = new JPanel(new BorderLayout());
topPanel.add(rbPanel, BorderLayout.WEST);
topPanel.add(jtfPanel, BorderLayout.CENTER);
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(bpanel, BorderLayout.SOUTH);
mainPanel.add(reSoulte, BorderLayout.CENTER);
mainPanel.add(topPanel, BorderLayout.NORTH);
Container pane = getContentPane();
pane.add(mainPanel);
exitButton.addActionListener(new ButtonWatcher());
addButton.addActionListener(new ButtonWatcher());
copyButton.addActionListener(new ButtonWatcher());
showButton.addActionListener(new ButtonWatcher());
//rButton.addItemListenet(new ButtonWatcher());
}
private class ButtonWatcher implements ActionListener{
public void actionPerformed(ActionEvent a){
Object buttonPressed=a.getSource();
if(buttonPressed.equals(exitButton))
{
System.exit(0);
}
if(buttonPressed.equals(addButton) && rButton1.isSelected())
{
//do the action
}
}
}
}
I'm not sure what array you want to fill but get the text with getText()
if(buttonPressed.equals(addButton) && rButton1.isSelected())
{
String s1 = iJTextField.getText();
String s2 = nJTextField.getText();
String s3 = swTextField.getText();
String s4 = hwTextField.getText();
// something with these strings
}
If any of the inputs are numbers and you want the numerical value, you need to parse.
Also, these need to be declared as class memebers. You have them declared in the constructor
JRadioButton rButton1 = new JRadioButton("SW Version",false);
JRadioButton rButton2 = new JRadioButton("HW Type",false);
JRadioButton rButton3 = new JRadioButton("General",true);
Declared in the constructor, they are not within the scope of the listener class
public class MyFrameMain extends JFrame{
private final JLabel iLabel;
private final JLabel nLabel;
private final JTextField iJTextField;
private final JTextField nJTextField;
private final JTextField swTextField;
private final JTextField hwTextField;
private final JLabel jItemCounter;
private final JTextArea reSoulte;
private final JButton addButton;
private final JButton showButton;
private final JButton copyButton;
private final JButton exitButton;
JRadioButton rButton1 = new JRadioButton("SW Version",false);
JRadioButton rButton2 = new JRadioButton("HW Type",false);
JRadioButton rButton3 = new JRadioButton("General",true);
public MyFrameMain(String title){
Also, doesn't really look like you need a listener for the radio button, since an event is not necessary. The JButton listens for an event, and in the actionPerformed, it checks if the radio button is selected. Therefore no need for the radio button to listen for any event, the JButton does that.
Try following code. I ahve added a List item and adding values from swTextField TextFiled to item when user select rButton1 and click on addButton button
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
/**
*
* #author isslam
*/
public class Test extends JFrame {
private final JLabel iLabel;
private final JLabel nLabel;
private final JTextField iJTextField;
private final JTextField nJTextField;
private final JTextField swTextField;
private final JTextField hwTextField;
private final JLabel jItemCounter;
private final JTextArea reSoulte;
private final JButton addButton;
private final JButton showButton;
private final JButton copyButton;
private final JButton exitButton;
JRadioButton rButton1;
java.util.List<String> item = new ArrayList<String>();
public Test(String title) {
setSize(500, 500);
setTitle(title);
setDefaultCloseOperation(Test.EXIT_ON_CLOSE);
iJTextField = new JTextField();
nJTextField = new JTextField();
swTextField = new JTextField();
hwTextField = new JTextField();
nLabel = new JLabel("ID: ");
iLabel = new JLabel("Name: ");
jItemCounter = new JLabel("Number of current Item");
reSoulte = new JTextArea(15, 20);
reSoulte.setEditable(false);
reSoulte.setText("Array is empty");
addButton = new JButton("Add an item into the Array");
showButton = new JButton("Show all items in the Array");
copyButton = new JButton("Copy Array into File");
exitButton = new JButton("Exite");
rButton1 = new JRadioButton("SW Version", false);
JRadioButton rButton2 = new JRadioButton("HW Type", false);
JRadioButton rButton3 = new JRadioButton("General", true);
ButtonGroup BGroup = new ButtonGroup();
BGroup.add(rButton1);
BGroup.add(rButton2);
BGroup.add(rButton3);
JPanel rbPanel = new JPanel(new GridLayout(5, 1));
rbPanel.add(nLabel);
rbPanel.add(iLabel);
rbPanel.add(rButton1);
rbPanel.add(rButton2);
rbPanel.add(rButton3);
JPanel bpanel = new JPanel(new GridLayout(2, 2));
bpanel.add(addButton);
bpanel.add(showButton);
bpanel.add(copyButton);
bpanel.add(exitButton);
JPanel jtfPanel = new JPanel(new GridLayout(5, 1));
jtfPanel.add(iJTextField);
jtfPanel.add(nJTextField);
jtfPanel.add(swTextField);
jtfPanel.add(hwTextField);
jtfPanel.add(jItemCounter);
JPanel topPanel = new JPanel(new BorderLayout());
topPanel.add(rbPanel, BorderLayout.WEST);
topPanel.add(jtfPanel, BorderLayout.CENTER);
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(bpanel, BorderLayout.SOUTH);
mainPanel.add(reSoulte, BorderLayout.CENTER);
mainPanel.add(topPanel, BorderLayout.NORTH);
Container pane = getContentPane();
pane.add(mainPanel);
exitButton.addActionListener(new ButtonWatcher());
addButton.addActionListener(new ButtonWatcher());
copyButton.addActionListener(new ButtonWatcher());
showButton.addActionListener(new ButtonWatcher());
//rButton.addItemListenet(new ButtonWatcher());
}
private class ButtonWatcher implements ActionListener {
public void actionPerformed(ActionEvent a) {
Object buttonPressed = a.getSource();
if (buttonPressed.equals(exitButton)) {
System.exit(0);
}
if (buttonPressed.equals(addButton) && rButton1.isSelected()) {
item.add(swTextField.getText());
System.out.println(item);
}
}
}
public static void main(String args[]) {
Test t = new Test("Test");
t.setVisible(true);
}
}
Use ButtonGroup with the JRadioButton of your context.
Use jRadioButton.setActionCommand(String) to set their corresponding action name: for your context "SW Version" and anything such.
Make use of an ArrayList to add the item of your context. Try mapping each such array list using a HashMap<Key, Val> i.e., HashMap<String, ArrayList<Equipment>> where the "SW Version" or anything such name will be the key
Try adding listeners to each action button in-line using the means of anonymous class.
So a sample coding for add action would become depicting the usage(usefulness) of ButtonGroup:
addButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String actionCommand = buttonGroup1.getSelection()
.getActionCommand();
// actionCommand = "SW Version"
map.get(actionCmmand).add(equipment);
}
});
Tutorial and reference:
How to use Radio Button, check the demo for ButtonGroup
ButtonGroup class
HashMap

What is a good way to Organize multiple JPanel's in a JFrame?

What I am trying to do is organize five seperate JPanel's within the frame. Here is what the output is supposed to look like: There will be one panel across the top. Two panels directly below the top panel that vertically split the space and then another two panels that split the remaining space horizontally.
I cannot figure out how to organize the panels like described above and I think it is because I just don't know the proper syntax. So any help or advise is greatly appreciated here is the code I have thus far.
import java.lang.String.*;
import java.lang.Exception.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Display extends JFrame implements ActionListener{
// instance variables
private static final int FRAME_WIDTH = 400;
private static final int FRAME_HEIGHT = 350;
private static final int FRAME_X_ORIGIN = 150;
private static final int FRAME_Y_ORIGIN = 150;
private static final int BUTTON_WIDTH = 90;
private static final int BUTTON_HEIGHT = 30;
private JButton readFile;
private JButton exit;
private JButton stats;
private JButton blank;
private JCheckBox avgHomeworkScore;
private JCheckBox avgTestScore;
private JCheckBox sdHomeworkScore;
private JCheckBox sdTestScore;
private JRadioButton buttonOne;
private JRadioButton buttonTwo;
private JRadioButton buttonThree;
private JRadioButton buttonFour;
private JPanel header;
private JPanel statistics;
private JPanel courses;
private JPanel display;
private JPanel action;
public static void main(String[] args){
Display frame = new Display();
frame.setVisible(true);
}
public Display(){
Container contentPane;
//Set the frame properties
setSize (FRAME_WIDTH, FRAME_HEIGHT);
setResizable (false);
setTitle ("CSCE155A Course Offerings Viewer");
setLocation (FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
contentPane = getContentPane();
contentPane.setLayout(new GridLayout());
contentPane.setBackground( Color.white );
//header
//Create and Place the Buttons on the frame
readFile = new JButton("Read File");
readFile.setBounds(4, 285, BUTTON_WIDTH, BUTTON_HEIGHT);
exit = new JButton("Exit");
exit.setBounds(100, 285, BUTTON_WIDTH, BUTTON_HEIGHT);
stats = new JButton("Stats");
stats.setBounds(195, 285, BUTTON_WIDTH, BUTTON_HEIGHT);
blank = new JButton("Clear");
blank.setBounds(290, 285, BUTTON_WIDTH, BUTTON_HEIGHT);
action = new JPanel(new FlowLayout());
action.setBackground(Color.blue);
action.add(readFile);
action.add(exit);
action.add(stats);
action.add(blank);
contentPane.add(action);
//Register this frame as an Action listener of the buttons
readFile.addActionListener(this);
exit.addActionListener(this);
stats.addActionListener(this);
blank.addActionListener(this);
//Create and Place the checkboxes on the frame
avgHomeworkScore = new JCheckBox();
avgHomeworkScore.setMnemonic(KeyEvent.VK_H);
contentPane.add(avgHomeworkScore);
avgHomeworkScore.setSelected(true);
avgTestScore = new JCheckBox();
avgTestScore.setMnemonic(KeyEvent.VK_T);
avgTestScore.setSelected(true);
sdHomeworkScore = new JCheckBox();
sdHomeworkScore.setMnemonic(KeyEvent.VK_S);
sdHomeworkScore.setSelected(true);
sdTestScore = new JCheckBox();
sdTestScore.setMnemonic(KeyEvent.VK_D);
sdTestScore.setSelected(true);
statistics = new JPanel(new GridLayout(0,1));
contentPane.add(statistics);
statistics.add(avgHomeworkScore);
statistics.add(avgTestScore);
statistics.add(sdHomeworkScore);
statistics.add(sdTestScore);
avgHomeworkScore.addActionListener(this);
avgTestScore.addActionListener(this);
sdHomeworkScore.addActionListener(this);
sdTestScore.addActionListener(this);
//create the radio buttons
buttonOne = new JRadioButton();
buttonOne.setMnemonic(KeyEvent.VK_1);
buttonOne.setSelected(true);
buttonTwo = new JRadioButton();
buttonTwo.setMnemonic(KeyEvent.VK_2);
buttonThree = new JRadioButton();
buttonThree.setMnemonic(KeyEvent.VK_3);
buttonFour = new JRadioButton();
buttonFour.setMnemonic(KeyEvent.VK_4);
ButtonGroup group = new ButtonGroup();
group.add(buttonOne);
group.add(buttonTwo);
group.add(buttonThree);
group.add(buttonFour);
buttonOne.addActionListener(this);
buttonTwo.addActionListener(this);
buttonThree.addActionListener(this);
buttonFour.addActionListener(this);
courses = new JPanel(new GridLayout(0,1));
courses.setBackground(Color.blue);
courses.add(buttonOne);
courses.add(buttonTwo);
courses.add(buttonThree);
courses.add(buttonFour);
contentPane.add(courses);
//Exit program when the viewer is closed
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
Use a layout manager. Never set the bounds, sizes and locations of your panels and other components. That's the job of the layout manager. Layout managers are explained in details in the Swing tutorial (as everything else, BTW).
You could use a BorderLayout for the main panel, and another for the bottom panel, for example.

Using a JButton to change an interface in Java

The idea is there are 5 JButtons on the top of the screen. Every time you press one it removes the old menu and produces a new one. To me, my code looks fine. The problem is when i click on "Add CD" nothing happens, but then if i manually resize the window (moving my mouse to the edge of the window and changing the size of it) the new menu pops up... Can anyone give me advice on how to fix this problem... Thanks, the whole runnable code is below.
package ui;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
public class mainInterface extends JFrame implements ActionListener
{
// Variables declaration - do not modify
private JButton jButton1;
private JButton jButton2;
private JButton jButton3;
private JButton jButton4;
private JButton jButton5;
private JButton jButton6;
private JPanel jPanel1;
private JTextField text1;
private JTextField text2;
private JTextField text3;
private JTextField text4;
private JTextField text5;
private JTextField text6;
private JTextField text7;
private JTextField text8;
private JLabel label1;
private JLabel label2;
private JLabel label3;
private JLabel label4;
private JLabel label5;
private JLabel label6;
private JLabel label7;
private JLabel label8;
private JPanel bottomPanel;
private JPanel topPanel; // declaring panels
private JPanel holdAll;
private JPanel one;
private JPanel two;
private JPanel three;
private JPanel four;
//----------------------------------------------------------
//----------------------------------------------------------
public static void main(String args[])
{
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run()
{
mainInterface myApplication = new mainInterface();
myApplication.setLocation(100, 100);
myApplication.setSize(700, 400);
myApplication.setTitle("Kevin's Jukebox");
myApplication.setVisible(true);
}
});
}
//----------------------------------------------------------
//----------------------------------------------------------
/** Creates new form mainInterface */
public mainInterface()
{
jButton1 = new JButton("Add CD");
jButton2 = new JButton("Add Video");
jButton3 = new JButton("Total Play Time");
jButton4 = new JButton("Create Playlist");
jButton5 = new JButton("Show Library");
jButton6 = new JButton("Quit");
topPanel = new JPanel();
holdAll = new JPanel();
bottomPanel = new JPanel();
one = new JPanel();
two = new JPanel();
three = new JPanel();
four = new JPanel();
text1 = new JTextField(15);
label1 = new JLabel("Title: ");
text2 = new JTextField(15);
label2 = new JLabel("Artist: ");
text3 = new JTextField(15);
label3 = new JLabel("Length: ");
text4 = new JTextField(15);
label4 = new JLabel("Num of Tracks: ");
label5 = new JLabel("Welcome to Kevins Jukebox");
int flag = 0;
drawApp(flag);
jButton1.addActionListener(this);
jButton2.addActionListener(this);
jButton3.addActionListener(this);
jButton4.addActionListener(this);
jButton5.addActionListener(this);
jButton6.addActionListener(this);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
//----------------------------------------------------------
//----------------------------------------------------------
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == jButton1)
{
int flag = 1;
drawApp(flag);
}
}
//----------------------------------------------------------
//----------------------------------------------------------
public void drawApp(int flag)
{
topPanel.setLayout(new FlowLayout());
topPanel.add(jButton1);
topPanel.add(jButton2);
topPanel.add(jButton3);
topPanel.add(jButton4);
topPanel.add(jButton5);
topPanel.add(jButton6);
bottomPanel.add(label5);
holdAll.setLayout(new BorderLayout());
holdAll.add(topPanel, BorderLayout.NORTH);
holdAll.add(bottomPanel, BorderLayout.CENTER);
if (flag == 0)
bottomPanel.add(label5);
else
bottomPanel.remove(label5);
if (flag == 1)
{
one.add(label1);
one.add(text1);
bottomPanel.add(one);
two.add(label2);
two.add(text2);
bottomPanel.add(two);
three.add(label3);
three.add(text3);
bottomPanel.add(three);
four.add(label4);
four.add(text4);
bottomPanel.add(four);
bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.PAGE_AXIS));
}
getContentPane().add(holdAll, BorderLayout.CENTER); // places everything on the frame
}
//----------------------------------------------------------
}
Execute this.validate() after you update the UI's layout. Calling this method tells the UI to relayout its components.

Categories