JAVA external Frame to control array - java

I have very simple code, just 2 buttons to display numbers from array in textArea.
public class FotyUI extends javax.swing.JFrame {
public FotyUI() {
initComponents();
}
int[] numbers = {0,1,2,3,4,5,6,7,8,9};
int position = 0;
private void nextActionPerformed(java.awt.event.ActionEvent evt) {
position ++;
tekst.setText(" " + numbers[position]);
}
private void previousActionPerformed(java.awt.event.ActionEvent evt) {
position--;
tekst.setText(" " + numbers[position]);
}
Now, this code runs great I have two buttons and textArea, but I would like to create an external JFrame2 with 2 buttons to control/display array from Frame 1
When I type:
public class FotyUI extends javax.swing.JFrame {
public FotyUI() {
initComponents();
}
int[] numbers = {0,1,2,3,4,5,6,7,8,9};
int position = 0;
JFrame temp = new JFrame();
JPanel panelik = new JPanel();
JButton nextS = new JButton("Next");
JButton prevS = new JButton("Previous");
panelik.add(nextS);
I have an error to create package panelik....
Can u help me ? How to create Frame 2 with 2 buttons and textArea to display/control content of array from Frame1

ok, I solve it !!!!!!!!
JFrame frame = new JFrame("Test");
frame.setVisible(true);
frame.setSize(500,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
JButton button = new JButton("hello agin1");
panel.add(button);
pole = new JTextField();
panel.add(pole);
button.addActionListener (new Action1());
static class Action1 implements ActionListener {
public void actionPerformed (ActionEvent e) {
position ++;
tekst.setText(" " + numbers[position]);
pole.setText(" " + numbers[position]);
}
}

Related

JLabel not appearing in JPanel

I made a JFrame with JTextField, JPanel and a button in which the user inputs a value and after clicking the button, it will generate multiple labels based on the users input, but the JLabel doesnt appear. am i doing it wrong?
this is the coding for the button.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String s = jTextField1.getText();
int noSub = Integer.valueOf(s);
addData(noSub);
}
and this is the method to add JLabel.
public void addData(int a){
jPanel1.removeAll();
int num = a;
JLabel jLabel[] = new JLabel[num];
for(int i=0;i<num;i++){
jLabel[i]=new JLabel();
jLabel[i] = new JLabel("Label "+i);
jPanel1.add(jLabel[i]);
jPanel1.revalidate();
jPanel1.repaint();
}
jPanel1.updateUI();
}
Made a simple working example here:
public class Sample extends JFrame{
private JTextField inputField;
private JPanel outputPanel;
private Sample() {
JPanel mainPanel = new JPanel(new BorderLayout());
JPanel form = new JPanel(new GridBagLayout());
inputField = new JTextField(3);
JButton submitBtn = new JButton("Enter");
form.add(inputField);
form.add(submitBtn);
mainPanel.add(form, BorderLayout.NORTH);
outputPanel = new JPanel();
mainPanel.add(outputPanel);
submitBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String text = inputField.getText();
int noSub = Integer.valueOf(text);
addData(noSub);
}
void addData(int data){
outputPanel.removeAll();
JLabel jLabel[] = new JLabel[data];
for(int i=0;i<data;i++){
jLabel[i] = new JLabel("Label "+i);
outputPanel.add(jLabel[i]);
}
outputPanel.revalidate();
outputPanel.repaint();
// No need to call outputPanel.updateUI()
}
});
setSize(400,500);
add(mainPanel);
setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new Sample();
}
}

More than 1 object in a single JFrame

I'm hoping someone can push me in the right direction with this. I have 3 separate classes, Calculator, Calculator2, and a Calculator3. In principal they are all the same, except for a few changes to some of the buttons, so I'll just paste the code for Calculator. I was wondering how can I get them so all appear in a single JFrame next to each other in a main? I attached my most recent attempt of the main as well.
Here is Calculator:
public class Calculator implements ActionListener {
private JFrame frame;
private JTextField xfield, yfield;
private JLabel result;
private JButton subtractButton;
private JButton divideButton;
private JButton addButton;
private JButton timesButton;
private JPanel xpanel;
public Calculator() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
xpanel = new JPanel();
xpanel.setLayout(new GridLayout(3,2));
xpanel.add(new JLabel("x:", SwingConstants.RIGHT));
xfield = new JTextField("0", 5);
xpanel.add(xfield);
xpanel.add(new JLabel("y:", SwingConstants.RIGHT));
yfield = new JTextField("0", 5);
xpanel.add(yfield);
xpanel.add(new JLabel("Result:"));
result = new JLabel("0");
xpanel.add(result);
frame.add(xpanel, BorderLayout.NORTH);
/***********************************************************************
***********************************************************************
**********************************************************************/
JPanel southPanel = new JPanel(); //New panel for the artimatic buttons
southPanel.setBorder(BorderFactory.createEtchedBorder());
timesButton = new JButton("Multiplication");
southPanel.add(timesButton);
timesButton.addActionListener(this);
subtractButton = new JButton("Subtract");
southPanel.add(subtractButton);
subtractButton.addActionListener(this);
divideButton = new JButton("Division");
southPanel.add(divideButton);
divideButton.addActionListener(this);
addButton = new JButton("Addition");
southPanel.add(addButton);
addButton.addActionListener(this);
frame.add(southPanel , BorderLayout.SOUTH);
Font thisFont = result.getFont(); //Get current font
result.setFont(thisFont.deriveFont(thisFont.getStyle() ^ Font.BOLD)); //Make the result bold
result.setForeground(Color.red); //Male the result answer red in color
result.setBackground(Color.yellow); //Make result background yellow
result.setOpaque(true);
frame.pack();
frame.setVisible(true);
}
/**
* clear()
* Resets the x and y field to 0 after invalid integers were input
*/
public void clear() {
xfield.setText("0");
yfield.setText("0");
}
#Override
public void actionPerformed(ActionEvent event) {
String xText = xfield.getText(); //Get the JLabel fiels and set them to strings
String yText = yfield.getText();
int xVal;
int yVal;
try {
xVal = Integer.parseInt(xText); //Set global var xVal to incoming string
yVal = Integer.parseInt(yText); //Set global var yVal to incoming string
}
catch (NumberFormatException e) { //xVal or yVal werent valid integers, print message and don't continue
result.setText("ERROR");
clear();
return ;
}
if(event.getSource().equals(timesButton)) { //Button pressed was multiply
result.setText(Integer.toString(xVal*yVal));
}
else if(event.getSource().equals(divideButton)) { //Button pressed was division
if(yVal == 0) { //Is the yVal (bottom number) 0?
result.setForeground(Color.red); //Yes it is, print message
result.setText("CAN'T DIVIDE BY ZERO!");
clear();
}
else
result.setText(Integer.toString(xVal/yVal)); //No it's not, do the math
}
else if(event.getSource().equals(subtractButton)) { //Button pressed was subtraction
result.setText(Integer.toString(xVal-yVal));
}
else if(event.getSource().equals(addButton)) { //Button pressed was addition
result.setText(Integer.toString(xVal+yVal));
}
}
}
And here is my current main:
public class DemoCalculator {
public static void main(String[] args) {
JFrame mainFrame = new JFrame("Calculators");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Calculator calc = new Calculator();
Calculator2 calc2 = new Calculator2();
JPanel calcPanel = new JPanel(new BorderLayout());
JPanel calcPanel2 = new JPanel(new BorderLayout());
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
//calcPanel.add(calc, BorderLayout.CENTER);
//calcPanel2.add(calc2, BorderLayout.CENTER);
mainPanel.add(calcPanel);
mainPanel.add(calcPanel2);
calcPanel.add(mainPanel);
mainFrame.getContentPane().add(calcPanel);
mainFrame.getContentPane().add(calcPanel2);
mainFrame.pack();
mainFrame.setVisible(true);
}
}
You should just create a single JFrame and put your Calculator classes each into a single JPanel.Don't create a new JFrame for each class.
public class Calculator{
JPanel panel;
public Calculator(){
panel = new JPanel();
/*
* Add labels and buttons etc.
*/
panel.add(buttons);
panel.add(labels);
}
//Method to return the JPanel
public JPanel getPanel(){
return panel;
}
}
Then add the panels to your JFrame in your testers class using whatever layout best suits your needs.
public class DemoCalculator {
public static void main(String[] args) {
JPanel cal1,cal2;
JFrame frame = new JFrame("Calculators");
frame.add(cal1 = new Calculator().getPanel(),new BorderLayout().EAST);
frame.add(cal2 = new Calculator2().getPanel(),new BorderLayout().WEST);
frame.setSize(1000,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
}
}

Java grid layout GUI - how to enter new pane on event?

How can I set a button to link to a completely different grid pane? If I click the JButton "More options" for example, I want it to link me to a new page with more JButton options. Right now, everything is static.
The program right now just calculates the area of a rectangle given an length and width when you press "Calculate." The grid layout is 4 x 2, denoted by JLabel, JTextField, and JButton listed below.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class RectangleProgram extends JFrame
{
private static final int WIDTH = 400;
private static final int HEIGHT = 300;
private JLabel lengthL, widthL, areaL;
private JTextField lengthTF, widthTF, areaTF;
private JButton calculateB, exitB;
//Button handlers:
private CalculateButtonHandler cbHandler;
private ExitButtonHandler ebHandler;
public RectangleProgram()
{
lengthL = new JLabel("Enter the length: ", SwingConstants.RIGHT);
widthL = new JLabel("Enter the width: ", SwingConstants.RIGHT);
areaL = new JLabel("Area: ", SwingConstants.RIGHT);
lengthTF = new JTextField(10);
widthTF = new JTextField(10);
areaTF = new JTextField(10);
//SPecify handlers for each button and add (register) ActionListeners to each button.
calculateB = new JButton("Calculate");
cbHandler = new CalculateButtonHandler();
calculateB.addActionListener(cbHandler);
exitB = new JButton("Exit");
ebHandler = new ExitButtonHandler();
exitB.addActionListener(ebHandler);
setTitle("Sample Title: Area of a Rectangle");
Container pane = getContentPane();
pane.setLayout(new GridLayout(4, 2));
//Add things to the pane in the order you want them to appear (left to right, top to bottom)
pane.add(lengthL);
pane.add(lengthTF);
pane.add(widthL);
pane.add(widthTF);
pane.add(areaL);
pane.add(areaTF);
pane.add(calculateB);
pane.add(exitB);
setSize(WIDTH, HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private class CalculateButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
double width, length, area;
length = Double.parseDouble(lengthTF.getText()); //We use the getText & setText methods to manipulate the data entered into those fields.
width = Double.parseDouble(widthTF.getText());
area = length * width;
areaTF.setText("" + area);
}
}
public class ExitButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
public static void main(String[] args)
{
RectangleProgram rectObj = new RectangleProgram();
}
}
You can use CardLayout. It allows the two or more components share the same display space.
Here is a simple example
public class RectangleProgram {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Area of a Rectangle");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField lengthField = new JTextField(10);
JTextField widthField = new JTextField(10);
JTextField areaField = new JTextField(10);
JButton calculateButton = new JButton("Calculate");
JButton exitButton = new JButton("Exit");
final JPanel content = new JPanel(new CardLayout());
JButton optionsButton = new JButton("More Options");
optionsButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
CardLayout cardLayout = (CardLayout) content.getLayout();
cardLayout.next(content);
}
});
JPanel panel = new JPanel(new GridLayout(0, 2)) {
#Override
public Dimension getPreferredSize() {
return new Dimension(250, 100);
}
};
panel.add(new JLabel("Enter the length: ", JLabel.RIGHT));
panel.add(lengthField);
panel.add(new JLabel("Enter the width: ", JLabel.RIGHT));
panel.add(widthField);
panel.add(new JLabel("Area: ", JLabel.RIGHT));
panel.add(areaField);
panel.add(calculateButton);
panel.add(exitButton);
JPanel optionsPanel = new JPanel();
optionsPanel.add(new JLabel("Options", JLabel.CENTER));
content.add(panel, "Card1");
content.add(optionsPanel, "Card2");
frame.add(content);
frame.add(optionsButton, BorderLayout.PAGE_END);
frame.pack();
frame.setVisible(true);
}
});
}
}
Read How to Use CardLayout

Getting compiler error for unknown reason

Alright so my program is getting the user's input to figure out the prime numbers (up to the max which the user entered), and then display these results in a scrollable JFrame. I have done all of that (I believe so at least) but keep getting one error when I try and compile it. Also, if you see any other mistakes that I have missed feel free to let me know!
Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PrimeNumbersJ extends JFrame
{
private static final int WIDTH=400;
private static final int HEIGHT=300;
//JFrame Components
private JLabel jlblMaxNumber;
private JTextArea jtaOutput;
private JTextField jtfMaxNumber;
private JButton jbtnCalculate, jbtnClear, jbtnExit;
private CalculateButtonHandler calculateHandler;
private ClearButtonHandler clearHandler;
private ExitButtonHandler exitHandler;
private JScrollPane scrollingResult;
private JPanel jpnlTop = new JPanel();
private JPanel jpnlCenter = new JPanel();
private JPanel jpnlBottom = new JPanel();
public PrimeNumbersJ()
{
// Set the title and Size:
setTitle("Prime Numbers with JFrame");
setSize(WIDTH, HEIGHT);
jpnlBottom.setLayout(new GridLayout(1, 3));
// Instantiate the JLabel components:
jlblMaxNumber = new JLabel("Enter the Largest Number to test: ", SwingConstants.LEFT);
// Instantiate the JTextFields:
jtfMaxNumber = new JTextField(10);
// Make the JTextArea scrollable:
jtaOutput = new JTextArea(10,1);
scrollingResult = new JScrollPane(jtaOutput);
// Instantiate and register the Calculate button for clicks events:
jbtnCalculate = new JButton("Calculate");
calculateHandler = new CalculateButtonHandler();
jbtnCalculate.addActionListener(calculateHandler);
// Instantiate and register the Clear button for clicks events:
jbtnClear = new JButton("Clear");
clearHandler = new ClearButtonHandler();
jbtnClear.addActionListener(clearHandler);
// Instantiate and register the Exit button for clicks events:
jbtnExit = new JButton("Exit");
exitHandler = new ExitButtonHandler();
jbtnExit.addActionListener(exitHandler);
// Assemble the JPanels:
jpnlTop.setLayout(new GridLayout(1, 2));
jpnlTop.add(jlblMaxNumber);
jpnlTop.add(jtfMaxNumber);
jpnlCenter.setLayout(new GridLayout(1, 1));
jpnlCenter.add(scrollingResult);
jpnlBottom.setLayout(new GridLayout(1, 3));
jpnlBottom.add(jbtnCalculate);
jpnlBottom.add(jbtnClear);
jpnlBottom.add(jbtnExit);
// Start to add the components to the JFrame:
Container pane = getContentPane();
pane.setLayout(new BorderLayout());
pane.add(jpnlTop, BorderLayout.NORTH);
pane.add(jpnlCenter, BorderLayout.CENTER);
pane.add(jpnlBottom, BorderLayout.SOUTH);
// Show the JFrame and set code to respond to the user clicking on the X:
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
jpnlTop.setLayout(new GridLayout(1, 3));
jpnlTop.add(jlblMaxNumber);
jpnlTop.add(jtfMaxNumber);
jpnlCenter.setLayout(new GridLayout(1, 1));
jpnlCenter.add(scrollingResult);
jpnlBottom.add(jbtnCalculate);
jpnlBottom.add(jbtnClear);
jpnlBottom.add(jbtnExit);
// Show the JFrame and set code to respond to the user clicking on the X:
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}//End Constructor
private class CalculateButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
int iRemainder,iPrimeCheck;
int iNumbertoTest = 0;
boolean bValidInput = true;
String sPrime ="";
try
{
iNumbertoTest = Integer.parseInteger(jtfMaxNumber.getText());
}
catch (Exception aeRef)
{
JOptionPane.showMessageDialog(null,"Enter the Max Number to Test.", getTitle(), JOptionPane.WARNING_MESSAGE);
bValidInput = false;
}// end of catch
if ( bValidInput )
{
for(iNumberToTest = 1;iNumberToTest <= 100;iNumberToTest++) {
iRemainder = 0;
for(iPrimeCheck = 1;iPrimeCheck <= iNumberToTest;iPrimeCheck++){
if(iNumberToTest % iPrimeCheck == 0){
iRemainder++;
}
}
if(iRemainder == 2 || iNumberToTest == 1)
{
String sNumber = Integer.toString(iNumberToTest);
sPrime = sPrime + (sNumber + "\n");
}
}
// Populate the output by using the methods in the user defined class::
jtaOutput.append("The Prime Numbers Are: \n" + sPrime + "\n");
} // end if
} //end ActionPerformed
}//End CalculateButtonHandler
private class ExitButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}//end ExitButtonHandler
private class ClearButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
jtfMaxNumber.setText("");
jtaOutput.setText("");
}
} // end ClearButtonHandler
public static void main(String args[])
{
PrimeNumbersJ primNumJ = new PrimeNumbersJ();
}
}
Error
java:120: cannot find symbol
symbol : method parseInteger(java.lang.String)
location: class java.lang.Integer
iMaxNumber = Integer.parseInteger(jtfMaxNumber.getText());
^
Integer.parseInteger()
does not exist.
Are you looking for Integer.parseInt() ???
change Integer.parseInteger() to
Integer.parseInt()
also declare int iNumberToTest as class variable in CalculateButtonHandler class
The Integer class doesn't contain method called parseInteger. Use parseInt instead.

FlowLayout on top of GridLayout not working

I'm trying to create a hangman game and so far it's coming along GREAT, but the layout design just doesn't seem to fall into place! The alphabet is supposed to end up in a FlowLayout order on top of the Hangman picture with the buttons "Restart", "Help" "Add New Word" and "Exit" at the bottom! What am I doing wrong?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
public class Hangman extends JFrame
{
int i = 0;
static JPanel panel;
static JPanel panel2;
static JPanel panel3;
public Hangman()
{
JButton[] buttons = new JButton[26];
panel = new JPanel(new FlowLayout());
panel2 = new JPanel();
panel3 = new JPanel();
JButton btnRestart = new JButton("Restart");
btnRestart.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
}
});
JButton btnNewWord = new JButton("Add New Word");
btnNewWord.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
try
{
FileWriter fw = new FileWriter("Words.txt", true);
PrintWriter pw = new PrintWriter(fw, true);
String word = JOptionPane.showInputDialog("Please enter a word: ");
pw.println(word);
pw.close();
}
catch(IOException ie)
{
System.out.println("Error Thrown" + ie.getMessage());
}
}
});
JButton btnHelp = new JButton("Help");
btnHelp.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String message = "The word to guess is represented by a row "
+ "of dashes, giving the number of letters and category of "
+ "the word. \nIf the guessing player suggests a letter "
+ "which occurs in the word, the other player writes it "
+ "in all its correct positions. \nIf the suggested "
+ "letter does not occur in the word, the other player "
+ "draws one element of the hangman diagram as a tally mark."
+ "\n"
+ "\nThe game is over when:"
+ "\nThe guessing player completes the word, or guesses "
+ "the whole word correctly"
+ "\nThe other player completes the diagram";
JOptionPane.showMessageDialog(null,message, "Help",JOptionPane.INFORMATION_MESSAGE);
}
});
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
ImageIcon icon = new ImageIcon("D:\\Varsity College\\Prog212Assign1_10-013803\\images\\Hangman1.jpg");
JLabel label = new JLabel();
label.setIcon(icon);
String b[]= {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
for(i = 0; i < buttons.length; i++)
{
buttons[i] = new JButton(b[i]);
panel.add(buttons[i]);
}
panel2.add(label);
panel3.add(btnRestart);
panel3.add(btnNewWord);
panel3.add(btnHelp);
panel3.add(btnExit);
}
public static void main(String[] args)
{
Hangman frame = new Hangman();
frame.add(panel, BorderLayout.NORTH);
frame.add(panel2, BorderLayout.CENTER);
frame.add(panel3, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
}
Here are a few suggestions:
Use a GridLayout for the top panel; in this case, zero means the number of rows is determined by the specified number of columns and the total number of components in the layout:
JPanel north = new JPanel(new GridLayout(0, 9));
Here's an outline of how you can make your center panel have a reasonable initial size; note how you can draw relative to the current size:
JPanel center = new JPanel() {
private static final int N = 256;
private static final String S = "Todo...";
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int dx = (getWidth() - g.getFontMetrics().stringWidth(S)) / 2;
int dy = getHeight() / 2;
g.drawString(S, dx, dy);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(N, N);
}
};
You can construct your button names like this:
for (int i = 0; i < 26; i++) {
String letter = String.valueOf((char) (i + 'A'));
buttons[i] = new JButton(letter);
north.add(buttons[i]);
}
Make your panels instance variables and start on the event dispatch thread:
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
Hangman frame = new Hangman();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.add(frame.north, BorderLayout.NORTH);
frame.add(frame.center, BorderLayout.CENTER);
frame.add(frame.south, BorderLayout.SOUTH);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
});
This problem is pretty well documented if you do some research - it seems all the panels (besides the CENTER one) aren't recalculated when resized. See How do I make this FlowLayout wrap within its JSplitPane? and http://www.velocityreviews.com/forums/t608472-wrap-flowlayout.html
But for a really quick fix, try changing your main method to this... (basically using a BoxLayout as your main container)
public static void main(String[] args)
{
TempProject frame = new TempProject();
Box mainPanel = Box.createVerticalBox();
frame.setContentPane(mainPanel);
mainPanel.add(panel);
mainPanel.add(panel2);
mainPanel.add(panel3);
frame.pack();
frame.setVisible(true);
}

Categories

Resources