JPanel with Grid Layout and JButtons doesn't load / work - java

I'm having trouble getting a JPanel inside a BorderLayout to work.
I defined the layout of the Panel as a Grid Layout, and then added a bunch of buttons I had made before hand to the JPanel. However, when I run the program, the JFrame loads but nothing within the frame loads. Here's the code:
import java.awt.*;
import javax.swing.*;
public class Phone extends JFrame {
private JTextField PhoneText;
private JPanel ButtonPanel;
private JButton bttn1;
private JButton bttn2;
private JButton bttn3;
private JButton bttn4;
private JButton bttn5;
private JButton bttn6;
private JButton bttn7;
private JButton bttn8;
private JButton bttn9;
private JButton bttn10;
private JButton bttn11;
private JButton bttn12;
public Phone(){
setTitle("Phone - Agustin Ferreira");
Container ContentPane = getContentPane();
ContentPane.setLayout(new BorderLayout());
setSize(300, 400);
setVisible(true);
setBackground(Color.DARK_GRAY);
PhoneText = new JTextField("(317)188-8566");
bttn1 = new JButton ("1");
bttn2 = new JButton ("2");
bttn3 = new JButton ("3");
bttn4 = new JButton ("4");
bttn5 = new JButton ("5");
bttn6 = new JButton ("6");
bttn7 = new JButton ("7");
bttn8 = new JButton ("8");
bttn9 = new JButton ("9");
bttn10 = new JButton ("*");
bttn11 = new JButton ("0");
bttn12 = new JButton ("#");
ButtonPanel = new JPanel(new GridLayout(4,3,0,0));
ButtonPanel.add(bttn1);
ButtonPanel.add(bttn2);
ButtonPanel.add(bttn3);
ButtonPanel.add(bttn4);
ButtonPanel.add(bttn5);
ButtonPanel.add(bttn6);
ButtonPanel.add(bttn7);
ButtonPanel.add(bttn8);
ButtonPanel.add(bttn9);
ButtonPanel.add(bttn10);
ButtonPanel.add(bttn11);
ButtonPanel.add(bttn12);
ContentPane.add(PhoneText, BorderLayout.NORTH);
ContentPane.add(ButtonPanel, BorderLayout.CENTER);
}
}
Additionally, I have another class that calls the Phone class. Here's the code for that, just in case:
package ProgrammingAssignment11;
import javax.swing.JFrame;
public class GUI_Driver {
public static void main(String[] args) {
Phone Nokia;
Nokia = new Phone();
Nokia.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
}
Any Help?
Much appreciated, M3tal T1ger

Your main problem:
You should only call setVisible(true) after adding components to your GUI. You don't do this and so the GUI gets drawn without its components.
Also:
You should avoid setting the sizes or preferred sizes of anything. Instead let the components and layout managers size themselves.
And don't forget to call pack() after adding all components and before making the GUI visible.
Learn and follow Java naming conventions, including giving all variables and methods names that begin with a lower case letter, and all classes with names that start with an upper-case letter.
For example:
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class Phone2 extends JPanel {
private static final String[][] BTN_TEXTS = {
{"1", "2", "3"},
{"4", "5", "6"},
{"7", "8", "9"},
{"*", "0", "#"}
};
private static final float BTN_POINTS = 48f;
private static final float TEXT_POINTS = 24f;
private static final int DISPLAY_COLUMNS = 12;
private JButton[][] buttons = new JButton[BTN_TEXTS.length][BTN_TEXTS[0].length];
private JTextField display = new JTextField(DISPLAY_COLUMNS);
public Phone2() {
display.setFocusable(false);
display.setFont(display.getFont().deriveFont(TEXT_POINTS));
GridLayout gridLayout = new GridLayout(BTN_TEXTS.length, BTN_TEXTS[0].length);
JPanel btnPanel = new JPanel(gridLayout);
for (int i = 0; i < BTN_TEXTS.length; i++) {
for (int j = 0; j < BTN_TEXTS[i].length; j++) {
String text = BTN_TEXTS[i][j];
JButton btn = new JButton(new BtnAction(text));
btn.setFont(btn.getFont().deriveFont(Font.BOLD, BTN_POINTS));
btnPanel.add(btn);
buttons[i][j] = btn;
}
}
setLayout(new BorderLayout());
add(display, BorderLayout.NORTH);
add(btnPanel, BorderLayout.CENTER);
}
private class BtnAction extends AbstractAction {
public BtnAction(String name) {
super(name);
}
#Override
public void actionPerformed(ActionEvent evt) {
String text = evt.getActionCommand();
display.setText(display.getText() + text);
}
}
private static void createAndShowGui() {
Phone2 mainPanel = new Phone2();
JFrame frame = new JFrame("Phone");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Related

Auto-scroll JTextArea with ScrollPane?

I'm trying to build a dynamic log window (basically a auto-scrolling jtext-area).
The problem I'm having is that although I'm printing 500 lines in the text area, it displays as below:
Below you have my code:
import java.awt.Dimension;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.text.DefaultCaret;
public class Main {
private static JFrame mainFrame;
public static void main(String args[]) {
mainFrame = new JFrame();
mainFrame.setSize(500, 500);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ControlPanel cp = new ControlPanel();
mainFrame.add(cp);
mainFrame.setVisible(true);
}
}
class ControlPanel extends JPanel {
private JButton resetButton = new JButton("Reset");
private JPanel logPanel = new JPanel();
private JLabel actionLogsLabel = new JLabel("Action Log");
private JLabel pointsLogsLabel = new JLabel("Points Log");
private JTextArea actionLog = new JTextArea();
private JTextArea pointsLog = new JTextArea();
private JScrollPane actionScroll;
private JScrollPane pointsScroll;
public ControlPanel() {
init();
this.add(resetButton);
this.add(logPanel);
}
private void init() {
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
this.setAlignmentX(LEFT_ALIGNMENT);
this.logPanel.setLayout(new BoxLayout(logPanel, BoxLayout.Y_AXIS));
this.logPanel.setAlignmentX(LEFT_ALIGNMENT);
actionLog.setPreferredSize(new Dimension(500, 300));
actionLog.setMaximumSize(actionLog.getPreferredSize());
actionLog.setEditable(false);
actionLog.setWrapStyleWord(true);
DefaultCaret caret = (DefaultCaret) actionLog.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
pointsLog.setPreferredSize(new Dimension(500, 300));
pointsLog.setMaximumSize(pointsLog.getPreferredSize());
pointsLog.setEditable(false);
pointsLog.setWrapStyleWord(true);
pointsScroll = new JScrollPane(pointsLog, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
actionScroll = new JScrollPane(actionLog, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
logPanel.add(actionLogsLabel);
logPanel.add(actionScroll);
for(int i = 0; i < 500; i++) {
actionLog.setText(actionLog.getText() + "Line: " + i + "\n");
}
logPanel.add(pointsLogsLabel);
logPanel.add(pointsScroll);
}
}
Hopefully someone with a bit more Swing experience can take the time to point me the right way with this.
Never do this:
actionLog.setPreferredSize(new Dimension(500, 300));
Since by doing this you artificially restrict the size of the JTextArea causing the effect that is currently vexing you. Note also that it's generally a good idea to avoid setting preferred sizes on anything.
Instead set the column and row counts of the JTextARea. This can be done via setter methods or via a simple constructor call: JTextArea myTextArea = new JTextArea(rows, columns);
As an aside: I wonder if a JList will work better for you.
MCVE Example:
import javax.swing.*;
import javax.swing.text.DefaultCaret;
public class Main2 {
private static void createAndShowGUI() {
JPanel mainPanel = new ControlPanel();
JFrame frame = new JFrame("Main2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
class ControlPanel extends JPanel {
private static final int LOG_ROWS = 15;
private static final int LOG_COLS = 40;
private JButton resetButton = new JButton("Reset");
private JPanel logPanel = new JPanel();
private JLabel actionLogsLabel = new JLabel("Action Log");
private JLabel pointsLogsLabel = new JLabel("Points Log");
private JTextArea actionLog = new JTextArea();
private JTextArea pointsLog = new JTextArea();
private JScrollPane actionScroll;
private JScrollPane pointsScroll;
public ControlPanel() {
init();
this.add(resetButton);
this.add(logPanel);
}
private void init() {
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
this.setAlignmentX(LEFT_ALIGNMENT);
this.logPanel.setLayout(new BoxLayout(logPanel, BoxLayout.Y_AXIS));
this.logPanel.setAlignmentX(LEFT_ALIGNMENT);
// !! actionLog.setPreferredSize(new Dimension(500, 300));
// !! actionLog.setMaximumSize(actionLog.getPreferredSize());
actionLog.setRows(LOG_ROWS); // !!
actionLog.setColumns(LOG_COLS); // !!
actionLog.setEditable(false);
actionLog.setWrapStyleWord(true);
DefaultCaret caret = (DefaultCaret) actionLog.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
// !! pointsLog.setPreferredSize(new Dimension(500, 300));
// !! pointsLog.setMaximumSize(pointsLog.getPreferredSize());
pointsLog.setRows(LOG_ROWS); // !!
pointsLog.setColumns(LOG_COLS); // !!
pointsLog.setEditable(false);
pointsLog.setWrapStyleWord(true);
pointsScroll = new JScrollPane(pointsLog,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
actionScroll = new JScrollPane(actionLog,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
logPanel.add(actionLogsLabel);
logPanel.add(actionScroll);
for (int i = 0; i < 500; i++) {
actionLog.setText(actionLog.getText() + "Line: " + i + "\n");
}
logPanel.add(pointsLogsLabel);
logPanel.add(pointsScroll);
}
}
Edit
Example with nested layouts and JLists:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;
public class Main2B {
private static void createAndShowGUI() {
ControlPanel2B controlPanel = new ControlPanel2B();
controlPanel.setBorder(BorderFactory.createEtchedBorder());
JPanel mainPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
mainPanel.add(controlPanel, gbc);
JFrame frame = new JFrame("Main2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
#SuppressWarnings("serial")
class ControlPanel2B extends JPanel {
private static final int LOG_ROWS = 15;
private static final int LIST_WIDTH = 500;
private JButton resetButton = new JButton("Reset");
private JPanel logPanel = new JPanel();
private JLabel actionLogsLabel = new JLabel("Action Log");
private JLabel pointsLogsLabel = new JLabel("Points Log");
private DefaultListModel<String> actionLogListModel = new DefaultListModel<>();
private JList<String> actionLogList = new JList<String>(actionLogListModel);
private DefaultListModel<String> pointsLogListModel = new DefaultListModel<>();
private JList<String> pointsLogList = new JList<String>(pointsLogListModel);
private JScrollPane actionScroll;
private JScrollPane pointsScroll;
public ControlPanel2B() {
init();
this.add(resetButton);
this.add(logPanel);
}
private void init() {
actionLogList.setVisibleRowCount(LOG_ROWS);
pointsLogList.setVisibleRowCount(LOG_ROWS);
actionLogList.setFixedCellWidth(LIST_WIDTH);
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
this.setAlignmentX(LEFT_ALIGNMENT);
this.logPanel.setLayout(new BoxLayout(logPanel, BoxLayout.Y_AXIS));
this.logPanel.setAlignmentX(LEFT_ALIGNMENT);
pointsScroll = new JScrollPane(pointsLogList,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
actionScroll = new JScrollPane(actionLogList,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
logPanel.add(actionLogsLabel);
logPanel.add(actionScroll);
for (int i = 0; i < 500; i++) {
actionLogListModel.addElement("Line: " + i);
}
logPanel.add(pointsLogsLabel);
logPanel.add(pointsScroll);
}
}

How to arrange multiple panels in JFrame

I am trying to make a simple calculator to practice Graphics (i am a complete GUI noob). I am having some problems with having unneeded spaces after Polyashenkos Calulator and the text area and the space between the text area and the buttons. Also how do i keep that layout but eliminate the space and also make the bottom 3 buttons smaller. Any tips about what im doing or how i can do it better would be much appreciated. Thank you.
import javax.swing.*;
import java.awt.*;
public class calculator {
public static void main(String[] args) {
// creates the JFrame(a window with decorations)
JFrame frame = new JFrame("Calculator");
// stops the program when window is closed
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(377, 350);
// the main panel of the JFrame,
// remembet you cant add content directly to JFrame
JPanel content = new JPanel(new GridLayout(4, 0));
// panel for the text field
JPanel textarea = new JPanel(new GridLayout(4, 0));
// panel for the buttons,
// GridLayout(int rows, int cols, int horiz_gap, int vert_gap)
JPanel buttonarea = new JPanel(new GridLayout(4, 5, 2, 2));
// the panel for the bigger bottom buttons
JPanel secondbuttonarea = new JPanel(new GridLayout(1, 1, 2, 2));
// the panel for the text on top
JPanel label = new JPanel();
content.add(label);
content.add(textarea);
content.add(buttonarea);
content.add(secondbuttonarea);
JLabel words = new JLabel("Polyashenko's Calculator", JLabel.CENTER);
label.add(words);
JTextField enterhere = new JTextField("0.", JTextField.CENTER);
// will set the curser of the text bar on right side
enterhere.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
textarea.add(enterhere);
// makes a button called b1 with text in it
JButton b1 = new JButton("BkSP");
// adds the backspace button to the buttonarea panel
buttonarea.add(b1);
JButton b2 = new JButton("CE");
buttonarea.add(b2);
JButton b3 = new JButton("C");
buttonarea.add(b3);
JButton b4 = new JButton("/");
buttonarea.add(b4);
JButton b5 = new JButton("sqrt");
buttonarea.add(b5);
JButton b6 = new JButton("7");
buttonarea.add(b6);
JButton b7 = new JButton("8");
buttonarea.add(b7);
JButton b8 = new JButton("9");
buttonarea.add(b8);
JButton b9 = new JButton("*");
buttonarea.add(b9);
JButton b10 = new JButton("%");
buttonarea.add(b10);
JButton b11 = new JButton("4");
buttonarea.add(b11);
JButton b12 = new JButton("5");
buttonarea.add(b12);
JButton b13 = new JButton("6");
buttonarea.add(b13);
JButton b14 = new JButton("-");
buttonarea.add(b14);
JButton b15 = new JButton("1/x");
buttonarea.add(b15);
JButton b16 = new JButton("1");
buttonarea.add(b16);
JButton b17 = new JButton("2");
buttonarea.add(b17);
JButton b18 = new JButton("3");
buttonarea.add(b18);
JButton b19 = new JButton("+");
buttonarea.add(b19);
JButton b20 = new JButton("+/-");
buttonarea.add(b20);
JButton b21 = new JButton("0");
secondbuttonarea.add(b21);
JButton b22 = new JButton(".");
secondbuttonarea.add(b22);
JButton b23 = new JButton("=");
secondbuttonarea.add(b23);
// adds the buttonarea panel to the main panel
frame.getContentPane().add(content);
// makes the window visible, put at end of program
frame.setVisible(true);
}
}
one of lessons by Hovercraft Full Of Eels (-: forums.sun.com :-)
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.*;
import javax.swing.*;
public class SciCalc {
private static void createAndShowUI() {
SciCalcGui gui = new SciCalcGui();
SciCalcMenu menu = new SciCalcMenu(gui);
JFrame frame = new JFrame("Calculator");
frame.getContentPane().add(gui.getMainPanel());
frame.setJMenuBar(menu.getJMenuBar());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowUI();
}
});
}
private SciCalc() {
}
}
class SciCalcGui {
private static final String[][] STANDARD_BTN_TEXTS = {
{"7", "8", "9", "/"}, {"4", "5", "6", "*"},
{"1", "2", "3", "-"}, {"0", ".", "=", "+"}};
private static final String[][] SCIENTIFIC_BTN_TEXTS = {
{"sqrt", "1/x", "sin"}, {"%", "Exp", "cos"},
{"x^y", "ln", "tan"}, {"x^2", "n!", "sec"}};
private static final int GAP = 5;
private static final Font BTN_FONT = new Font(Font.DIALOG, Font.BOLD, 20);
private JPanel mainPanel = new JPanel();
private JPanel sciPanel;
private JTextField display = new JTextField();
SciCalcGui() {
display.setFont(BTN_FONT);
JPanel standardPanel = createBtnPanel(STANDARD_BTN_TEXTS, "Standard");
sciPanel = createBtnPanel(SCIENTIFIC_BTN_TEXTS, "Scientific");
mainPanel.setLayout(new BorderLayout());
mainPanel.setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
mainPanel.add(standardPanel, BorderLayout.CENTER);
mainPanel.add(sciPanel, BorderLayout.WEST);
mainPanel.add(display, BorderLayout.NORTH);
sciPanel.setVisible(false);
}
public void sciPanelSetVisible(boolean visible) {
sciPanel.setVisible(visible);
Window win = SwingUtilities.getWindowAncestor(mainPanel);
win.pack();
}
public JPanel getMainPanel() {
return mainPanel;
}
private JPanel createBtnPanel(String[][] texts, String title) {
JPanel btnPanel = new JPanel();
int rows = texts.length;
int cols = texts[0].length;
btnPanel.setLayout(new GridLayout(rows, cols, GAP, GAP));
for (int row = 0; row < texts.length; row++) {
for (int col = 0; col < texts[row].length; col++) {
JButton btn = new JButton(texts[row][col]);
btn.setFont(BTN_FONT);
btnPanel.add(btn);
}
}
btnPanel.setBorder(BorderFactory.createTitledBorder(title));
return btnPanel;
}
}
class SciCalcMenu {
private static final String STANDARD = "Standard";
private static final String SCIENTIFIC = "Scientific";
private SciCalcGui gui;
private JMenuBar menuBar = new JMenuBar();
private JMenuItem standardView;
private JMenuItem scientificView;
SciCalcMenu(SciCalcGui gui) {
this.gui = gui;
standardView = new JMenuItem(STANDARD, KeyEvent.VK_T);
scientificView = new JMenuItem(SCIENTIFIC, KeyEvent.VK_S);
ViewAction viewAction = new ViewAction();
standardView.addActionListener(viewAction);
scientificView.addActionListener(viewAction);
standardView.setEnabled(false);
JMenu viewMenu = new JMenu("View");
viewMenu.setMnemonic(KeyEvent.VK_V);
viewMenu.add(standardView);
viewMenu.add(scientificView);
menuBar.add(new JMenu("Edit"));
menuBar.add(viewMenu);
menuBar.add(new JMenu("Help"));
}
public JMenuBar getJMenuBar() {
return menuBar;
}
private class ViewAction implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals(STANDARD)) {
gui.sciPanelSetVisible(false);
standardView.setEnabled(false);
scientificView.setEnabled(true);
} else if (command.equals(SCIENTIFIC)) {
gui.sciPanelSetVisible(true);
standardView.setEnabled(true);
scientificView.setEnabled(false);
}
}
}
}
A GridLayout won't ever look very good in cases like this.
The content expands to fill the box in the grid. You only have minimal control over the spacing between rows and columns.
You may have to change layouts to make it look the way you want. GridBagLayout has all that control but is much harder to configure.
Sometimes you can nest panels with BorderLayout and GridLayout to make it look reasonable. But it is Swing and that means its usable but it becomes very hard to make it look slick.
I always like to use a FlowLayout for OK/Cancel buttons. They look best to me that way and you can push them all left, right or centered. Your calculator buttons should work well with a GridLayout but you can't easily have a tall "Enter" button or a wide "0" button.
For example, try using a vertical BoxLayout instead of a grid that is 4 high by 1 wide.

Java Swing RadioButtons

i am making a group of radiobuttons and a Panel in the centre should change the colour clicking the radiobuttons.
Everything seems correct but ... it does not work !
With the main class i see the panel but the colour does not change ...
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ChoiceFrame extends JFrame
{
public ChoiceFrame()
{
class ChoiceListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
setTheColor();
}
}
buttonPanel = createButtonPanel();
add(buttonPanel, BorderLayout.SOUTH);
colorPanel = createColorPanel();
add(colorPanel, BorderLayout.NORTH);
setSize(FRAME_WIDTH, FRAME_HEIGHT);
colorPanel.repaint();
}
public JPanel createButtonPanel()
{
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3,1));
redButton = new JRadioButton("Red Colour");
blueButton = new JRadioButton("Blue Colour");
greenButton = new JRadioButton("Green Colour");
redButton.addActionListener(listener);
blueButton.addActionListener(listener);
greenButton.addActionListener(listener);
ButtonGroup group = new ButtonGroup();
group.add(redButton);
group.add(blueButton);
group.add(greenButton);
panel.add(redButton);
panel.add(blueButton);
panel.add(greenButton);
return panel;
}
public JPanel createColorPanel()
{
JPanel panel = new JPanel();
return panel;
}
public void setTheColor()
{
if (redButton.isSelected())
colorPanel.setBackground(Color.RED);
else if (blueButton.isSelected())
colorPanel.setBackground(Color.BLUE);
else if (greenButton.isSelected())
colorPanel.setBackground(Color.GREEN);
}
private JPanel colorPanel;
private JPanel buttonPanel;
private JRadioButton redButton;
private JRadioButton blueButton;
private JRadioButton greenButton;
private ActionListener listener;
private static final int FRAME_WIDTH = 400;
private static final int FRAME_HEIGHT = 400;
}
Add in your constructor also initialization of ChoiceListener.
listener = new ChoiceListener()
In your createButtonPanel() method, you should initialize your listener with:
listener = new ChoiceListener();
There's no point creating a new ChoiceListener object when an ActionListener field exists.
You can make while loop and Every time while loop will check which radioButton is selected

Adding JPanels to JPanel array

I have declared an array:
private javax.swing.JPanel[] panelArray = new javax.swing.JPanel[3];
I also have 3 panels: panel0, panel1 and panel2. Can I add these panels to the array? i.e
panelArray[0] = panel0;
panelArray[1] = panel1;
panelArray[2] = panel2;
And then manipulate the arrays like this?
boolean[] myBools; .... then set them as true/false
for(int i=0; i<3; i++)
{
if(myBools[i])
panelArray[i].setVisible(true)
}
Because that does not work for me
On my side it's working fine, in this program :
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class MyPanel
{
private JPanel[] panelArray = new JPanel[3];
private boolean[] myBools = new boolean[]{false, false, false};
private int counter = 0;
private int prvPanelCounter = 0;
private Timer timer;
private ActionListener timerAction = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
counter++;
if (counter > 2)
counter = 0;
myBools[counter] = true;
for (int i = 0; i < 3; i++)
{
if (myBools[i])
{
panelArray[i].setVisible(myBools[i]);
panelArray[prvPanelCounter].setVisible(myBools[prvPanelCounter]);
myBools[i] = false;
prvPanelCounter = i;
break;
}
}
}
};
private void createAndDisplayGUI()
{
JFrame frame = new JFrame("Locate Mouse Position");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel panel0 = new JPanel();
panel0.setOpaque(true);
panel0.setBackground(Color.BLUE);
JPanel panel1 = new JPanel();
panel1.setOpaque(true);
panel1.setBackground(Color.RED);
JPanel panel2 = new JPanel();
panel2.setOpaque(true);
panel2.setBackground(Color.DARK_GRAY);
panelArray[0] = panel0;
panelArray[1] = panel1;
panelArray[2] = panel2;
JComponent contentPane = (JComponent) frame.getContentPane();
contentPane.setLayout(new GridLayout(0, 1));
frame.add(panel0);
frame.add(panel1);
frame.add(panel2);
panel0.setVisible(myBools[counter]);
panel1.setVisible(myBools[counter]);
panel2.setVisible(myBools[counter]);
frame.setSize(300, 300);
frame.setLocationByPlatform(true);
frame.setVisible(true);
timer = new Timer(1000, timerAction);
timer.start();
}
public static void main(String\u005B\u005D args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new MyPanel().createAndDisplayGUI();
}
});
}
}
What you want to do can be done, but here's a few points to bear in mind:
Make sure you initialise the JPanels before referencing them.
The statement "panelArray[i].setVisible(true)" needs a semicolon after it.
None of these panels will be visible unless you add them to another component, such as a JFrame.
Rather than state javax.swing.JPanel, you could just import the JPanel at the top of the page and refer to it as simply JPanel.
Your "if" statement is unnecessary. Just do .setVisible(myBools[i]);
Hope these were of some help to you.
Yes, you can. Did you really not initialize the myBools array with new ?

Why am I getting this exception? Trying to make a simple GUI in Java

import java.awt.*;
import javax.swing.*;
public class userInput extends JFrame {
private JButton newEntry;
private JButton deleteEntry;
private JButton editEntry;
private JButton saveEntry;
private JButton cancelEntry;
private FlowLayout layout;
public userInput() {
super("My Address Book"); //sets the title!
JTextField field = new JTextField(20);
Container content = getContentPane();
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
buttonPanel.add(newEntry);
buttonPanel.add(deleteEntry);
buttonPanel.add(editEntry);
buttonPanel.add(saveEntry);
buttonPanel.add(cancelEntry);
add(buttonPanel, BorderLayout.SOUTH);
content.setLayout(new BorderLayout());
content.add(buttonPanel, "South");
setVisible(true);
}
}
Here is my driver program:
import javax.swing.*;
public class AddressBookGui {
public static void main (String[] args)
{
userInput addressBook = new userInput();
addressBook.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //whenever you hit x you will exit the program
addressBook.setSize(750, 600);
addressBook.setVisible(true);
}
}
you have to initialize newEntry before doing
newEntry = new JButton("foo");
buttonPanel.add(newEntry);
along with the other buttons
You forgot to allocate your Buttons:
newEntry = new JButton();
deleteEntry = new JButton();
...

Categories