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 ?
Related
My friend has given me a practice problem regarding prime number. Numbers 1 to n needs to be displayed in a new window. I also can't figure out on how I can use the input I got from panel1 to panel2. I'm very new to GUI since I haven't gone there when I studied Java a few years back. Hope you can help!
I haven't done much with the GUI since I don't really know where to start, but I've watched youtube videos and have gone through many sites on how to start with a GUI. Here's what I have done:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class sieve
{
private JPanel contentPane;
private MyPanel input;
private MyPanel2 sieve;
private void displayGUI()
{
JFrame frame = new JFrame("Input");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new CardLayout());
input = new MyPanel(contentPane);
sieve = new MyPanel2();
contentPane.add(input, "Input");
contentPane.add(sieve, "Sieve of Erasthoneses");
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new CardLayoutExample().displayGUI();
}
});
}
}
class MyPanel extends JPanel {
private JTextField text;
private JLabel label1;
private JButton OK;
private JButton cancel;
private JPanel contentPane;
public MyPanel(JPanel panel) {
contentPane = panel;
label1 = new JLabel ("Enter a number from 1 to n:");
text = new JTextField(1000);
OK = new JButton ("OK");
cancel = new JButton ("Cancel");
setPreferredSize (new Dimension (500, 250));
setLayout (null);
text.setBounds (145, 50, 60, 25);
OK.setBounds (450, 30, 150, 50);
cancel.setBounds (250, 30, 150, 50);
OK.setSize(315, 25);
OK.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
CardLayout cardLayout = (CardLayout) contentPane.getLayout();
cardLayout.next(contentPane);
}
});
add (text);
add (label1);
add (OK);
add (cancel);
}
}
class MyPanel2 extends JPanel {
private JFrame frame;
private JLabel label;
JLabel label1;
public MyPanel2()
{
frame = new JFrame("Sieve of Eratosthenes");
label = new JLabel("The Prime numbers from 2 to " + num + " are");
num1 = num;
boolean[] bool = new boolean[num1];
for (int i = 0; i < bool.length; i++)
{
bool[i] = true;
}
for (int i = 2; i < Math.sqrt(num1); i++)
{
if(bool[i] == true)
{
for(int j = (i*i); j < num1; j = j+i)
{
bool[j] = false;
}
}
}
for (int i = 2; i< bool.length; i++)
{
if(bool[i]==true)
{
label1 = new JLabel(" " + label[i]);
}
}
}
}
Thanks for your help!
Your code had many compilation errors.
Oracle has a helpful tutorial, Creating a GUI With JFC/Swing. Skip the Netbeans section. Review all the other sections.
I reworked your two JPanels. When creating a Swing application, you first create the GUI. After the GUI is created, you fill in the values to be displayed.
I created the following GUI. Here's the input JPanel.
Here's the Sieve JPanel.
I used Swing layout managers to create the two JPanels. Using null layouts and absolute positioning leads to many problems.
I created the sieve JPanel, then populated it with values. You can see how I did it in the source code.
Here's the complete runnable code. I made the classes inner classes.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Eratosthenes {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Eratosthenes().displayGUI();
}
});
}
private CardLayout cardLayout;
private JFrame frame;
private JPanel contentPane;
private InputPanel inputPanel;
private SievePanel sievePanel;
private void displayGUI() {
frame = new JFrame("Input");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
cardLayout = new CardLayout();
contentPane.setLayout(cardLayout);
inputPanel = new InputPanel();
sievePanel = new SievePanel();
contentPane.add(inputPanel.getPanel(), "Input");
contentPane.add(sievePanel.getPanel(), "Sieve");
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public void cancelAction() {
frame.dispose();
System.exit(0);
}
public class InputPanel {
private JPanel panel;
private JTextField textField;
public InputPanel() {
this.panel = createMainPanel();
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new BorderLayout());
JPanel entryPanel = new JPanel(new FlowLayout());
entryPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JLabel label = new JLabel("Enter a number from 1 to n:");
entryPanel.add(label);
textField = new JTextField(10);
entryPanel.add(textField);
panel.add(entryPanel, BorderLayout.BEFORE_FIRST_LINE);
JPanel buttonPanel = new JPanel(new FlowLayout());
entryPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JButton okButton = new JButton("OK");
buttonPanel.add(okButton);
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int inputNumber = valueOf(textField.getText().trim());
if (inputNumber < 2) {
return;
}
sievePanel.updatePrimeLabel(inputNumber);
sievePanel.updatePrimeNumbers(inputNumber);
cardLayout.show(contentPane, "Sieve");
}
private int valueOf(String number) {
try {
return Integer.valueOf(number);
} catch (NumberFormatException e) {
return -1;
}
}
});
JButton cancelButton = new JButton("Cancel");
buttonPanel.add(cancelButton);
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cancelAction();
}
});
okButton.setPreferredSize(cancelButton.getPreferredSize());
panel.add(buttonPanel, BorderLayout.AFTER_LAST_LINE);
return panel;
}
public JPanel getPanel() {
return panel;
}
}
public class SievePanel {
private JLabel primeLabel;
private JList<Integer> primeNumbersList;
private JPanel panel;
public SievePanel() {
this.panel = createMainPanel();
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
Font titlefont = panel.getFont().deriveFont(Font.BOLD, 24f);
JPanel textPanel = new JPanel(new BorderLayout());
JLabel titleLabel = new JLabel("Sieve of Eratosthenes");
titleLabel.setFont(titlefont);
titleLabel.setHorizontalAlignment(JLabel.CENTER);
textPanel.add(titleLabel, BorderLayout.BEFORE_FIRST_LINE);
primeLabel = new JLabel(" ");
primeLabel.setHorizontalAlignment(JLabel.CENTER);
textPanel.add(primeLabel, BorderLayout.AFTER_LAST_LINE);
panel.add(textPanel, BorderLayout.BEFORE_FIRST_LINE);
primeNumbersList = new JList<>();
JScrollPane scrollPane = new JScrollPane(primeNumbersList);
panel.add(scrollPane, BorderLayout.CENTER);
JButton button = new JButton("Return");
panel.add(button, BorderLayout.AFTER_LAST_LINE);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
cardLayout.show(contentPane, "Input");
}
});
return panel;
}
public void updatePrimeLabel(int inputNumber) {
primeLabel.setText("The prime numbers from 2 to " +
inputNumber + " are:");
}
public void updatePrimeNumbers(int inputNumber) {
DefaultListModel<Integer> primeNumbers =
new DefaultListModel<>();
boolean[] bool = new boolean[inputNumber];
for (int i = 0; i < bool.length; i++) {
bool[i] = true;
}
for (int i = 2; i < Math.sqrt(inputNumber); i++) {
if (bool[i] == true) {
for (int j = (i * i); j < inputNumber; j = j + i) {
bool[j] = false;
}
}
}
for (int i = 2; i < bool.length; i++) {
if (bool[i] == true) {
primeNumbers.addElement(i);
}
}
primeNumbersList.setModel(primeNumbers);
}
public JPanel getPanel() {
return panel;
}
}
}
i have 10 jcheckbox and only 5 should be selected. i already did all the coding for this one, but i don't know how to display the selected 5 into a jlabel. i tried doing it by this code:
JCheckBox check;
JPanel panel=new JPanel();
for(int i=0; i<10; i++){
check=new JCheckBox();
check.addActionListener(listener);
check.setName("Select"+i);
panel.add(check);
}
this is the listener
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
check = (JCheckBox) e.getSource();
name=check.getName();
}
};
and this is the panel where it should be displayed into jlabel
panel2=new JPanel(new GridLayout(5,1));
for(int i=0; i<5; i++){
txtVote=new JLabel(name);
panel2.add(txtVote);
}
but using this code, it doesn't display anything on the jlabel. if i change the listener into this:
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
check = (JCheckBox) e.getSource();
txtVote.setText(check.getName());
}
};
it will only display into the last label. other jlabels would be blank. please help thank you so much
EDIT
here is the code that is runnable
public class JCheckBoxtoLabel{
JCheckBox check;
String name;
JLabel txtVote;
public JCheckBoxtoLabel() {
JFrame frame = new JFrame();
JPanel panel = createPanel();
JPanel panel2 = panel2();
frame.setLayout(new GridLayout(1,2));
frame.add(panel); frame.add(panel2);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private JPanel createPanel() {
JPanel panel=new JPanel(new GridLayout(10,1));
for(int i=0; i<10; i++){
check=new JCheckBox();
check.addActionListener(listener);
check.setName("Select"+i);
panel.add(check);
}
return panel;
}
private JPanel panel2(){
JPanel panel2=new JPanel(new GridLayout(5,1));
for(int i=0; i<5; i++){
txtVote=new JLabel();
txtVote.setBorder(BorderFactory.createLineBorder(Color.RED));
panel2.add(txtVote);
}
return panel2;
}
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
check = (JCheckBox) e.getSource();
txtVote.setText(check.getName());
}
};
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new JCheckBoxtoLabel();
}
});
}
}
Consider changing what you're doing and displaying the text in a JList and not in JLabels. This can help you consolidate your information. You can also give your JCheckBoxes or JRadioButtons and ItemListener that only allows 5 of the buttons to be selected at a time -- unselecting the oldest one currently selected. For instance:
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
#SuppressWarnings("serial")
public class FiveNames extends JPanel {
private static final String[] ALL_NAMES = {"Bob", "Bill", "Frank", "Helen",
"Erica", "Mickey", "Donald", "Hillary", "Michael", "Peter", "Roger"};
private static final int ALLOWED_SELECTIONS_COUNT = 5;
private DefaultListModel<String> displayListModel = new DefaultListModel<>();
private JList<String> list = new JList<>(displayListModel);
public FiveNames() {
JPanel namePanel = new JPanel(new GridLayout(0, 1, 0, 5));
RButtonItemListener rButtonListener = new RButtonItemListener();
for (String name : ALL_NAMES) {
JRadioButton rButton = new JRadioButton(name);
rButton.setActionCommand(name);
rButton.addItemListener(rButtonListener);
namePanel.add(rButton);
}
list.setVisibleRowCount(ALLOWED_SELECTIONS_COUNT);
list.setPrototypeCellValue(" ");
list.setBackground(null);
setLayout(new GridLayout(1, 0));
add(namePanel);
add(list);
}
// listener to only allow the last 5 radiobuttons to be selected
private class RButtonItemListener implements ItemListener {
private List<ButtonModel> buttonModelList = new ArrayList<>();
#Override
public void itemStateChanged(ItemEvent e) {
JRadioButton rBtn = (JRadioButton) e.getSource();
ButtonModel model = rBtn.getModel();
if (e.getStateChange() == ItemEvent.SELECTED) {
buttonModelList.add(model);
if (buttonModelList.size() > ALLOWED_SELECTIONS_COUNT) {
for (int i = 0; i < buttonModelList.size() - ALLOWED_SELECTIONS_COUNT; i++) {
ButtonModel removedModel = buttonModelList.remove(0);
removedModel.setSelected(false);
}
}
} else {
buttonModelList.remove(model);
}
displayListModel.clear();
for (ButtonModel buttonModel : buttonModelList) {
displayListModel.addElement(buttonModel.getActionCommand());
}
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("FiveNames");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new FiveNames());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
The problem is that txtVote is only a single Jlabel and you are trying to use it for all 5. Since the fifth jlabel was the last to be created it is the one being used. My suggestion is that you create an arraylist field and inside panel12 add each label to the arraylist. Then inside the listener it would iterate through each jlabel in the arraylist check if has text set to it, if so check the next one until it finds one with no text, then sets the text to that. The problem with this at the moment is that in your code you are never defining what happens when they uncheck the box.
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class JCheckBoxtoLabel{
JCheckBox check;
String name;
JLabel txtVote;
ArrayList<JLabel> boxLabels;
public JCheckBoxtoLabel() {
boxLabels = new ArrayList<JLabel>();
JFrame frame = new JFrame();
JPanel panel = createPanel();
JPanel panel2 = panel2();
frame.setLayout(new GridLayout(1,2));
frame.add(panel); frame.add(panel2);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private JPanel createPanel() {
JPanel panel=new JPanel(new GridLayout(10,1));
for(int i=0; i<10; i++){
check=new JCheckBox();
check.addActionListener(listener);
check.setName("Select"+i);
panel.add(check);
}
return panel;
}
private JPanel panel2(){
JPanel panel2=new JPanel(new GridLayout(5,1));
for(int i=0; i<5; i++){
txtVote=new JLabel();
txtVote.setBorder(BorderFactory.createLineBorder(Color.RED));
panel2.add(txtVote);
boxLabels.add(txtVote);
}
return panel2;
}
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
check = (JCheckBox) e.getSource();
if(!check.isSelected()){
for(JLabel label: boxLabels){
if(label.getText().equals(check.getName())) label.setText("");
}
}else{
for(JLabel label: boxLabels){
if(label.getText().isEmpty()){
label.setText(check.getName());
return;
}
}
}
}
};
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new JCheckBoxtoLabel();
}
});
}
}
Your variable JLabel txtVote is a single JLabel object, not an array.
In your panel2() function you assign 5 new JLabels to txtVote. Since you assign 5 in a row, it gets overriden each time so it only ever contains the final JLabel.
private JPanel panel2(){
JPanel panel2=new JPanel(new GridLayout(5,1));
for(int i=0; i<5; i++){
txtVote=new JLabel();
txtVote.setBorder(BorderFactory.createLineBorder(Color.RED));
panel2.add(txtVote);
}
return panel2;
}
So when you call getText on voteTxt in the action listener, you are only getting the last labels text.
To fix this, you need to make txtVote an array of JLabels, and in your action listener iterate a second time through your JLabels and call get text on each in turn.
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
check = (JCheckBox) e.getSource();
for (int i = 0; i < txtVotes.length; i++) {
txtVotes[i].getText(check.getName());
}
}
};
I don't know if you realise or want to, but each label is being set to the same value, if you don't want this you will need to store an array of check names somewhere and iterate through these as well.
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();
}
});
}
}
hi i am trying to make java desktop application where i am trying to make jbutton bottom left i did following code i dont know where i am wrong my code is note working
here is my code
import java.awt.*;
import java.awt.event.*;
import javax.imageio.ImageIO;
import javax.swing.*;
new complete code
public class ApplicationCloseExample
{
private JButton[] buttons;
private void displayGUI()
{
final JFrame frame = new JFrame("Application Close Example");
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
for (int i = 5; i < 8; i++) {
buttons[i] = new JButton(Integer.toString(i));
bottomPanel.add(buttons[i]);
}
// JButton button = new JButton("Comment");
// bottomPanel.add(button);
// frame.getContentPane().add(contentPane, BorderLayout.CENTER);
frame.getContentPane().add(bottomPanel, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new ApplicationCloseExample().displayGUI();
}
});
}
}
How can i achieve this
I'm going to assume the null pointer exception is something to do with your buttons array. Check that you have initialised it properly.
private JButton[] buttons = new JButton[8];
I copied your code into a test project and ran it after some modifications:
public static void main(String[] args) {
final JFrame frame = new JFrame("Application Close Example");
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
for (int i = 5; i < 8; i++) {
buttons[i] = new JButton(Integer.toString(i));
bottomPanel.add(buttons[i]);
}
frame.getContentPane().add(bottomPanel, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
This produced a frame with three buttons aligned to the bottom left of the window.
There is an elegant solution that I'll give you but maybe it serves. Use WindowsBuilder and adds several buttons and then you look like is placing code. So make yourself an idea of the pattern that follows a setLayout with Flow.
Hey I could use help debugging this program. The code is not mine, it is from an answer to a question and I wanted to try it but I get a NullPointerException and can't figure out where the problem is. I think the problem may be image paths but I am not sure so I could use help.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
public class CircleImages {
private int score = 0;
private JTextField scoreField = new JTextField(10);
public CircleImages() {
scoreField.setEditable(false);
final ImageIcon[] icons = createImageIcons();
final JPanel iconPanel = createPanel(icons, 8);
JPanel bottomLeftPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
bottomLeftPanel.add(new JLabel("Score: "));
bottomLeftPanel.add(scoreField);
JPanel bottomRightPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING));
JButton newGame = new JButton("New Game");
bottomRightPanel.add(newGame);
JButton quit = new JButton("Quit");
bottomRightPanel.add(quit);
JPanel bottomPanel = new JPanel(new GridLayout(1, 2));
bottomPanel.add(bottomLeftPanel);
bottomPanel.add(bottomRightPanel);
newGame.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
reset(iconPanel, icons);
score = 0;
scoreField.setText(String.valueOf(score));
}
});
JFrame frame = new JFrame();
frame.add(iconPanel);
frame.add(bottomPanel, BorderLayout.PAGE_END);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private void reset(JPanel panel, ImageIcon[] icons) {
Component[] comps = panel.getComponents();
Random random = new Random();
for(Component c : comps) {
if (c instanceof JLabel) {
JLabel button = (JLabel)c;
int index = random.nextInt(icons.length);
button.setIcon(icons[index]);
}
}
}
private JPanel createPanel(ImageIcon[] icons, int gridSize) {
Random random = new Random();
JPanel panel = new JPanel(new GridLayout(gridSize, gridSize));
for (int i = 0; i < gridSize * gridSize; i++) {
int index = random.nextInt(icons.length);
JLabel label = new JLabel(icons[index]);
label.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e) {
score += 1;
scoreField.setText(String.valueOf(score));
}
});
label.setBorder(new LineBorder(Color.GRAY, 2));
panel.add(label);
}
return panel;
}
private ImageIcon[] createImageIcons() {
String[] files = {"DarkGrayButton.png",
"BlueButton.png",
"GreenButton.png",
"LightGrayButton.png",
"OrangeButton.png",
"RedButton.png",
"YellowButton.png"
};
ImageIcon[] icons = new ImageIcon[files.length];
for (int i = 0; i < files.length; i++) {
icons[i] = new ImageIcon(getClass().getResource("/circleimages/" + files[i]));
}
return icons;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new CircleImages();
}
});
}
}
Your problem is here:
icons[i] = new ImageIcon(getClass().getResource("/circleimages/" + files[i]));
You don't have the required images in your project, so getClass().getResource() will return null and you will have a NullPointerException in the constructor of ImageIcon.
What you have to do is put the following files in your project:
/circleimages/DarkGrayButton.png
/circleimages/BlueButton.png
/circleimages/GreenButton.png
/circleimages/LightGrayButton.png
/circleimages/OrangeButton.png
/circleimages/RedButton.png
/circleimages/YellowButton.png