Referencing a contentPane in an actionPerformed method - java

I'm creating a load button and want it to populate a 9x9 gridlayout content pane nested inside the CENTER panel of a border layout (main window). This method is located inside the PAGE_START section of the border layout. The question is how can I place the buttons in the Grid Layout of the CENTER section from here?
//Load Button
JButton load = new JButton("Load");
load.addActionListener(new ActionListener() {
#Override
public void actionPerformed (ActionEvent a) {
//Dialog Box To Locate The Puzzle
SudokuPuzzle puzzle;
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"Text Files", "txt");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(SudukoGUI.this);
if(returnVal == JFileChooser.APPROVE_OPTION) {
String fileLocation = chooser.getSelectedFile().getName();
Scanner file = new Scanner(fileLocation);
puzzle = new SudokuPuzzle(file, file);
//Load Puzzle To Model and draw it
try {
gridView = new JButton[9][9];
int[][] viewArray = puzzle.getArray();
for (int row = 0; row < 9; row++) {
for (int col = 0; col < 9; col++) {
gridView[row][col] = new JButton(String.valueOf(viewArray[row][col]));
***************THE NEXT LINE REPRESENTS MY PROBLEM***************
this.getContentPane().board.add(gridView[row][col]);
}
}
This is in the constructor
JPanel board = new JPanel();
board.setLayout (new GridLayout (9,9));
board.setPreferredSize(new Dimension(400,400));
this.getContentPane().add(board, BorderLayout.CENTER);

This
this.getContentPane().board.add(gridView[row][col]);
Does not make any sense. You added board to the content pane in your constructor, but this does not mean that board is now a field of the content pane. So
getContentPane().board
Should fail to compile.
You should probably make board a field of your class, rather than declaring it a local variable in your constructor. Then you will able to refer to board throughout the body of your class.
Basic example:
public class Example
{
private JPanel board;
public Example()
{
board = new JPanel();
getContentPane().add(board);
//assuming above code takes place in the constructor
JButton load = new JButton("load");
load.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
...lots of code
//as board is no longer a local variable this will compile
board.add(gridView[row][col]);
}
}
}
}
Note that you probably want to add load to your frame at some point.

First of all declare board as final variable using:
final JPanel board = new JPanel();
So that board could be accessed from anonymous inner class of ActionListener. Thereafter, change this line:
this.getContentPane().board.add(gridView[row][col]);
To
board.add(gridView[row][col]);

Related

I want to use the same object to create multiple dropdown menus on a Jframe

I am currently trying to create a menu where whenever you click a button it will create a new dropdown menu below the old one. These menu will all have the same values so i want to use the same objects repeatedly for them. Currently using a list to hold an array with the two menus created every time the button is clicked, then set new bounds for the dropdown menus put them on a new array, then add them to the list and repeat. With the code I have it wont display the old menus only the ones with the new bounds.
UI Class
public void NTButtonClick () {
Var1.AddBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Component[] Leveli = new Component[3];
Leveli[0] = Var1.box1;
Leveli[1] = Var1.box2;
Var1.LDS.add(Leveli);
Var1.frame1.add(Var1.LDS.get(Var1.i)[0]);
Var1.frame1.add(Var1.LDS.get(Var1.i)[1]);
Var1.frame1.repaint();
Var1.frame1.revalidate();
Var1.V=Var1.V+80;
Var1.i++;
SetBounds();
}
});
}
Set Bounds CLass
public void SetBounds () {
Var1.box1.setBounds(20,Var1.V,200,40);
Var1.box2.setBounds(300,Var1.V,200,40);
Veriables Class
List <Component[]> LDS = new ArrayList<Component[]>();
public int V = 40;
public int i = 0;
public JFrame frame1 = new JFrame();
public Component box1 = new JComboBox( Locations );
public Component box2 = new JComboBox(Locations);
public JButton AddBut = new JButton("+");
public JButton Export = new JButton("Export");
public JLabel AddText = new JLabel("Add Another Trip");
public JLabel ToText = new JLabel("To");
}
Any help would be greatly appreciated thanks.

Have a phone keypad and I want to make it a simple addition calculator

I made a simple phone keypad and I want to change a button to add numbers. Right now, the + button simply adds a + to the displayed numbers at the top, but I want that to add the inputted numbers. Like on a calculator, exactly what the + does. And I would like to change the clear button to be an enter button. Here's my partner's and I code so far to make the keypad:
public class Keypad extends JPanel implements ActionListener {
JLabel display;
JButton numButton;
JButton clearButton;
String displayContent = "";
String[] numPadContent = {"1","2","3","4","5","6","7","8","9","+","0"};
ArrayList<JButton> buttonList;
// Keypad constructor class
public Keypad(Container pane) {
// sets the size of the Keypad display
pane.setPreferredSize(new Dimension(320, 335));
// initialize display to hold displayContent
display = new JLabel(displayContent);
display.setPreferredSize(new Dimension(320, 25));
// create lowered bevel border around the display
display.setBorder(BorderFactory.createLoweredBevelBorder());
// add the display to the panel
pane.add(display, BorderLayout.PAGE_START);
// initialize the buttonList
buttonList = new ArrayList<JButton>(12);
JPanel numberPanel = new JPanel();
// set the numberPanel to have a 4row by 3col grid layout
numberPanel.setLayout(new GridLayout(4,3,0,0));
// set the size of the numberPanel
numberPanel.setPreferredSize(new Dimension(320,260));
// create the buttons and add them to the buttonList, properly displaying the numbers
for (int i = 0; i < numPadContent.length; i++) {
numButton = new JButton(numPadContent[i]);
buttonList.add(numButton);
}
// add the buttonList to the number panel
for (int n = 0; n < buttonList.size(); n++) {
buttonList.get(n).addActionListener(this);
numberPanel.add(buttonList.get(n));
}
// create black border around the number panel
numberPanel.setBorder(BorderFactory.createMatteBorder(5, 5, 5, 5, Color.black));
// add number panel to center part of display
pane.add(numberPanel, BorderLayout.LINE_END);
// create Clear button that is actionable
clearButton = new JButton("Clear");
clearButton.setPreferredSize(new Dimension(320, 30));
clearButton.addActionListener(this);
// add Clear button to bottom of display
pane.add(clearButton, BorderLayout.PAGE_END);
}
// update the display depending on clicked button(s)
public void actionPerformed(ActionEvent e) {
String textThere = display.getText();
String additionalText = "";
// add clicked number button text to display
for (int a = 0; a < buttonList.size(); a++) {
if (e.getSource().equals(buttonList.get(a))) {
additionalText = buttonList.get(a).getText();
}
}
// clear display if "Clear" button is clicked
if (e.getSource().equals(clearButton)) {
textThere = "";
}
display.setText(textThere.concat(additionalText));
}
public static void main(String[] args) {
//create and set up the window.
JFrame frame = new JFrame("Keypad");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//set up the content pane.
frame.getContentPane().add(new Keypad(frame));
frame.pack();
frame.setVisible(true);
}
See this link: Is there an eval() function in Java?
You can import javax.script and use the ScriptEngine's eval() method to evaluate your expression.

Actionlistener java

For my class I need to use my ActionListener. I am having trouble adding my ActionListener to my buttons. I have to use the word "this" like this.buttons to add my ActionListener but Im having trouble doing that. I will get to my actionPerformed method later but my main problem is my ActionListener.
public class TextButtonsHW extends JFrame implements ActionListener {
private JButton[] buttons; //Do not change
private JTextArea textArea; //Do not change
//Assign values for these constants in the constructor
private final int ENTER; //Index of Enter button in buttons
private final int SPACE; //Index of Space button in buttons
private final int CLEAR; //Index of Clear button in buttons
/**
* Set up this frame and its contents.
* #param title Title to appear in JFrame title bar
*/
public TextButtonsHW(String title) {
super(title); //call parent JFrame constructor to set the title
buttons = new JButton[] { new JButton("A"), new JButton("B"), new JButton("C"),
new JButton("1"), new JButton("2"), new JButton("3"),
new JButton("X"), new JButton("Y"), new JButton("Z"),
new JButton("Enter"), new JButton("Space"), new JButton("Clear")};
ENTER = buttons.length-3;
SPACE = buttons.length-2;
CLEAR = buttons.length-1;
textArea = new JTextArea(15, 5);
textArea.setEditable(false);
this.buttons[0].addActionListener(I dont know what to put right here);
//TODO: instantiate all JButtons, add them to the buttons array,
// and register "this" as the ActionListener for each button.
//DONE
//TODO: assign values to ENTER, SPACE, and CLEAR constants to
// indicate the indexes of those buttons in the buttons array
//DONE
//TODO: create the JTextArea textArea
//TODO: set its "editable" property to false
//DONE
//Create a TextButtonsHWPanel to display the buttons and textArea
TextButtonsHWPanel mainPanel = new TextButtonsHWPanel(buttons, textArea);
this.getContentPane().add(mainPanel);
this.pack();
}
public void actionPerformed(ActionEvent e) {
//TODO: update the text of textArea according to which
// button generated the ActionEvent.
}
public static void main(String[] args) {
final TextButtonsHW f = new TextButtonsHW("Text Buttons");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null); //centers frame on screen
f.setVisible(true);
}
}
buttons[0].addActionListener(this);
Since you have 12 buttons you could also go for a for-loop to add ActionListener to all your buttons i.e.
for(int i=0; i<12; i++)
{
buttons[i].addActionListener(this);
}
Instead of a long code i.e.
buttons[0].addActionListener(this);
buttons[1].addActionListener(this);
........................
Though buttons[0].addActionListener(this); will work well, From design perspective I will suggest to have separate class (may be inner class) which implements ActionListner and pass its object reference to the method.
the whole point of Object Oriented programming is to delegate different responsibilities to different Objects(classes), so code becomes more maintainable and reusable.

Java GUI NullPointerException with Canvas class

So I am working on a GUI project for my class and I am a bit stuck. My problem has to do with my GUI aspect so I guess you could ignore the other methods having to do with the sorting. As of now, my main concern is just getting the GUI working. However, I keep running into an error, a null pointer exception to be exact:
Java.lang.NullPointerException
at SortDriver$SortCanvas.paint(SortDriver.java:253)
at SortDriver.init(SortDriver.java:197)
at sun.applet.AppletPanel.run(AppletPanel.java:436)
at java.lang.Thread.run(Thread.java:679)
After reading though my code, I think I narrowed it down to the my SortCanvas class. I never used it before but it was part of the stub my professor gave to us. That is to say that it works correctly and displays the image correctly but it looks like my implementation is incorrect however. Could someone help me figure out how to implement my SortCanvas "picture" correctly please? I read over the Java Docs for Canvas and I still don't understand what I am doing wrong. Here is my code:
import java.awt.*;
import java.applet.Applet;
import javax.swing.*;
import java.awt.event.*;
public class SortDriver extends Applet {
private int array[]; // array to be sorted
private int limit = 1000; // size of array to be sorted - you may have to make
// this bigger for faster sorts
private int largestNum; // need to know for color scaling purposes in paint()
// flag to tell paint() whether to paint a single location or the whole array
private enum PaintType {ALL, SINGLE};
private PaintType doPaint = PaintType.ALL;
private int index = -1; // index of single array location to be painted
//this listener object responds to button events
private ButtonActionListener buttonListener;
//button to start the sort
private JButton sortButton;
//basic window frame
private JFrame mainFrame;
//layouts
private BorderLayout initialLayout;
private FlowLayout northLayout;
private BorderLayout centerLayout;
private BorderLayout southLayout;
//basic panel for window frame
private JPanel initialPanel;
//panels for window layout
private JPanel northPanel;
private JPanel centerPanel;
private JPanel southPanel;
//panels for radio buttons
private JPanel radioOrderPanel;
private JPanel radioSortPanel;
private JPanel radioColorPanel;
//north panel header labels
private JLabel topTitleLabel;
private JLabel bottomTitleLabel;
private JLabel arraySizeLabel;
//radio buttons for list order (radioOrderButton)
//random set, ordered set, reverse set
private JRadioButton rOB1, rOB2, rOB3;
//radio buttons for sort type (radioSortButton)
//bubblesort, insertionsort, mergesort, quicksort
private JRadioButton rSB1, rSB2, rSB3, rSB4;
//radio buttons for color choice (radioColorButton)
//green, red, white, blue
private JRadioButton rCB1, rCB2, rCB3, rCB4;
//radio button groups for each radio panel
private ButtonGroup orderGroup, sortGroup, colorGroup;
//text field for size of the array
private JTextField arraySizeTextField;
// the picture of the sort will appear on this canvas
private SortCanvas picture;
private final int pictureWidth = 500; // size of the sort bar 1001
private final int pictureHeight = 50;
public void init() {
buttonListener = new ButtonActionListener();
array = new int[limit];
// load the array
largestNum = array[0] = (int) (Math.random()*1000000.0);
for (int i=1; i<limit; i++) {
array[i] = (int) (Math.random()*1000000.0);
// also keep track of the largest so that we can scale by it in paint()
if (array[i] > largestNum) largestNum = array[i];
}
//set up the main frame
mainFrame = new JFrame();
initialPanel = (JPanel) mainFrame.getContentPane();
initialLayout = new BorderLayout();
mainFrame.setResizable(false);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setSize(650, 750);
initialPanel.setLayout(initialLayout);
//set up north panel
northPanel = new JPanel();
northLayout = new FlowLayout();
topTitleLabel = new JLabel("SortIt!");
bottomTitleLabel = new JLabel("A program by Mike Sevilla");
northPanel.setLayout(northLayout);
northPanel.add(topTitleLabel, BorderLayout.NORTH);
northPanel.add(bottomTitleLabel, BorderLayout.NORTH);
initialPanel.add(northPanel, BorderLayout.NORTH);
//set up center panel
centerPanel = new JPanel();
centerLayout = new BorderLayout();
centerPanel.setLayout(centerLayout);
//place array size label
arraySizeLabel = new JLabel("Size:");
//place array size text field w/ space for 5 chars
arraySizeTextField = new JTextField("", 5);
//place sort button
sortButton = new JButton("Sort it!");
// the listener is triggered when the button is clicked
sortButton.addActionListener(buttonListener);
centerPanel.setLayout(centerLayout);
//place sort bar on top of center layout
picture = new SortCanvas();
centerPanel.add(picture, BorderLayout.CENTER);
centerPanel.add(arraySizeLabel, BorderLayout.CENTER);
centerPanel.add(arraySizeTextField, BorderLayout.CENTER);
centerPanel.add(sortButton, BorderLayout.CENTER);
initialPanel.add(centerPanel, BorderLayout.CENTER);
//set up south panel
southPanel = new JPanel();
southLayout = new BorderLayout();
southPanel.setLayout(southLayout);
//set radio buttons and format layouts
radioOrderPanel = new JPanel();
radioOrderPanel.setLayout(new BoxLayout(radioOrderPanel, BoxLayout.Y_AXIS));
radioSortPanel = new JPanel();
radioSortPanel.setLayout(new BoxLayout(radioSortPanel, BoxLayout.Y_AXIS));
radioColorPanel = new JPanel();
radioColorPanel.setLayout(new BoxLayout(radioColorPanel, BoxLayout.Y_AXIS));
//define radio buttons
rOB1 = new JRadioButton("Random Order", true);
rOB1.addActionListener(buttonListener);
radioOrderPanel.add(rOB1);
rOB2 = new JRadioButton("In Order", false);
rOB2.addActionListener(buttonListener);
radioOrderPanel.add(rOB2);
rOB3 = new JRadioButton("In Reverse", false);
rOB3.addActionListener(buttonListener);
radioOrderPanel.add(rOB3);
rSB1 = new JRadioButton("Bubble Sort", true);
rSB1.addActionListener(buttonListener);
radioSortPanel.add(rSB1);
rSB2 = new JRadioButton("Insertion Sort", false);
rSB2.addActionListener(buttonListener);
radioSortPanel.add(rSB2);
rSB3 = new JRadioButton("Merge Sort", false);
rSB3.addActionListener(buttonListener);
radioSortPanel.add(rSB3);
rSB4 = new JRadioButton("Quick Sort", false);
rSB4.addActionListener(buttonListener);
radioSortPanel.add(rSB4);
rCB1 = new JRadioButton("Green", true);
rCB1.addActionListener(buttonListener);
radioColorPanel.add(rCB1);
rCB2 = new JRadioButton("Red", false);
rCB2.addActionListener(buttonListener);
radioColorPanel.add(rCB2);
rCB3 = new JRadioButton("White", false);
rCB3.addActionListener(buttonListener);
radioColorPanel.add(rCB3);
rCB4 = new JRadioButton("Blue", false);
rCB4.addActionListener(buttonListener);
radioColorPanel.add(rCB4);
//add radio buttons to a button group
orderGroup = new ButtonGroup();
orderGroup.add(rOB1);
orderGroup.add(rOB2);
orderGroup.add(rOB3);
sortGroup = new ButtonGroup();
sortGroup.add(rSB1);
sortGroup.add(rSB2);
sortGroup.add(rSB3);
sortGroup.add(rSB4);
colorGroup = new ButtonGroup();
colorGroup.add(rCB1);
colorGroup.add(rCB2);
colorGroup.add(rCB3);
colorGroup.add(rCB4);
initialPanel.add(southPanel, BorderLayout.NORTH);
picture.paint(picture.getGraphics());
mainFrame.setVisible(true);
}
// this object is triggered whenever a button is clicked
private class ButtonActionListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
// find out which button was clicked
Object source = event.getSource();
// start sort button was clicked
if (source == sortButton) {
// call the sort
doBubblesort();
}
// called when user hits return in text field
if (source == arraySizeTextField) {
int size = Integer.parseInt(arraySizeTextField.getText());
}
}
}
private void doBubblesort() {
int temp;
// this is just bubblesort
for (int i=0; i<limit-1; i++) {
for (int j=0; j<limit-1-i; j++) {
if (array[j]>array[j+1]) {
temp = array[j]; array[j] = array[j+1]; array[j+1] = temp;
// redraw only locations j and j+1
doPaint = PaintType.SINGLE; // try changing this to ALL and see what happens
index = j;
picture.paint(picture.getGraphics());
index = j+1;
picture.paint(picture.getGraphics());
}
}
}
}
class SortCanvas extends Canvas {
// this class paints the sort bar
SortCanvas() {
setSize(pictureWidth, pictureHeight);
setBackground(Color.white);
}
public void paint(Graphics g) {
if (doPaint == PaintType.ALL) {
// paint whole array - this takes time so it shouldn't be done too frequently
setBackground(Color.white);
g.setColor(Color.white);
g.fillRect(0, 0, pictureWidth, pictureHeight);
for (int i=0; i<limit; i++) {
// the larger the number, the brighter green it is
// green is between 0.0 and 1.0
// divide by the largest number to get a value between 0 and 1
float green = (float)(array[i]/(float)largestNum);
// clamp if necessary - it shouldn't be
if (green<0f) green = 0f;
if (green>1f) green = 1f;
g.setColor(new Color(0.0f, green, 0.0f));
// array location 0 is painted at left;
// array location limit-1 is painted to right
//this is a single vertical line in the bar
g.drawLine((int)(i*pictureWidth/limit), 0,
(int)(i*pictureWidth/limit), pictureHeight);
}
}
else {
// just paint one location on the bar
float green = (float)(array[index]/(float)largestNum);
if (green<0f) green = 0f;
if (green>1f) green = 1f;
g.setColor(new Color(0.0f, green, 0.0f));
g.drawLine((int)(index*pictureWidth/limit), 0,
(int)(index*pictureWidth/limit), pictureHeight);
}
}
}
}
This is not required;
picture.paint(picture.getGraphics());
getGraphics will return null if the component has not yet being painted itself. You should avoid using this method, it is simply a snap shot of the current components graphical state (which in your case is nothing)
You don't control the paint process, that's down to the repaint manager. You can request updates via the repaint methods. Have a read through Painting in AWT and Swing
You should avoid mixing heavy weight (Canvas) & light weight components (JFrame) together, where possible, you should stick with Swing components
Calling paint() directly can lead to unexpected behavior as you are see from this, use repaint() instead:
picture.repaint();

display imageicon in Jlabel

I'm doing a program in Netbeans
.. and I need to display the content of the folder (there are images) in a JPanel
... display every image in jlabel
.... I did this code, but its not working
...... I create a interface with a JButton and JPanel:
public class MyInterface extends javax.swing.JFrame
{
/** Creates new form NewJFrame1 */
public MyInterface()
{
initComponents();
}
private File files;
private JFileChooser es = new JFileChooser();
String path;
JLabel label;
public List<ImageIcon> pictures = new ArrayList<ImageIcon>();
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
if (es.showOpenDialog(jPanel1) == JFileChooser.APPROVE_OPTION)
{
files = es.getSelectedFile();
path = files.getAbsolutePath();
return;
}
label.setIcon(pictures.get(WIDTH));
files = null;
return;
}
private JLabel getLabel(BufferedImage[] images)
{
for (int j = 0; j < images.length; j++)
{
pictures.add(new ImageIcon(images[j]));
}
label = new JLabel(pictures.get(0));
label.setHorizontalAlignment(JLabel.CENTER);
return label;
}
private JPanel draw()
{
JPanel panl = new JPanel();
for (int j = 0; j < pictures.size(); j++)
{
panl.getBorder();
}
JPanel panel = new JPanel();
panl.addAncestorListener(null);
panl.add(panl);
return panel;
}
}
hard to say something and wise
1) maybe there isn't any reason for create JLabels and JPanels on the fly
2) if you want to display only one Image in one moment then
create JFrame
put there JLabel and JButton
use Icon for Image/BufferedImage, put this Icon to the JLabel
3) if you want to display more than one Images (let's to say up to 20-50 Images) then use GridLayout for JLabels contains Icon
4) if number of Images isn't limited somehow then use JList
It's not entirely clear what you are trying to do, your code doesn't compile as shown, and it's a bit of a mess. Some pointers though:
In draw(), you are adding a JPanel to itself, which is not a good sign. Then you return a different panel that has not been modified. Sort out the panel and panl naming to fix this.
In getLabel(), which isn't actually called anywhere, you return one label created from the first image. So you will only be able to display one of the images.
In jButton1ActionPerformed you return early if the user selects a file, so the path will be set but it's not clear that anything else happens.

Categories