This is what I currently have but its not not showing the results in two textareas..
Right now all it shows is one textarea with Odd numbers only. I'm not sure why the even numbers wont show. Any help is appreciated Thanks!
static TextFileInput inFile;
static String inFileName = "lab12.txt";
static JFrame myFrame;
static Container cPane;
static TextArea even, odd;
public static void main(String[] args) {
initialize();
readNumbersFromFile(inFileName);
}
public static void initialize() {
inFile = new TextFileInput(inFileName);
even = new TextArea();
odd = new TextArea();
myFrame=new JFrame();
myFrame.setSize(400,400);
myFrame.setLocation(200, 200);
myFrame.setTitle("test");
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
}
public static void readNumbersFromFile(String fileName){
String[] num = new String[20];
String line;
line = inFile.readLine();
for(int i = 0; i < inFile.getLineCount(); i++){
num[i] = line;
line = inFile.readLine();
}
cPane = myFrame.getContentPane();
cPane.add(even);
cPane.add(odd);
for(int i = 0; i < inFile.getLineCount(); i++){
if(Integer.parseInt(num[i]) % 2 == 0)
even.append(num[i] + "\n");
else
odd.append(num[i] + "\n");
}//for
myFrame.setVisible(true);
}//readSSNsFromFile
It is better you build the panel and division the panel by the row and column and add this panel on the frame.
'cPane' will have a BorderLayout by default. Adding components to a BorderLayout with no constraints will result in the component being put in the CENTER constraint. Any area of a BorderLayout can only accommodate one component.
A better general approach is to instantiate a JPanel with an appropriate layout, add the components to the JPanel, then either add that JPanel to the content pane, or set it as the content pane.
Related
I am trying to make a GUI which will take a value from one JPanel, and then when a button is pressed it will move on to the next panel, which uses information that was input from the previous panel. Since one panel is dependent on the value the user has input from the previous panel I don't think CardLayout will work here as it refers to the panels as strings.
As an example of the mechanism that I'm trying to implement, I have attempted to create a JFrame where
the first panel will ask the user to input a number,
the second panel will then display to the user the first number that the user selected and ask them to pick a second number,
the third panel will show the both the first and second number that the user selected and ask for a third number.
Finally, the fourth panel will display the sum of the three numbers that the user input in each JPanel, and allow the user to reset the JFrame.
I first created four separate classes that create the four JPanels I want to be able to move between. As can be seen from the code, I have tested each of these JPanels in a separate JFrame to see if they produce the desired effect.
Here is the code for PanelThree, PanelFour and the overall GUI. Panels one and two are very similar to panel three:
Panel Three:
import javax.swing.*;
import java.awt.*;
public class PanelThree extends JPanel {
JPanel row1 = new JPanel();
JPanel row2 = new JPanel();
JPanel row3 = new JPanel();
JSlider slider = new JSlider(0, 10, 5);
JButton next = new JButton("Find the total of all three numbers");
public PanelThree(int num0, int num1) {
BorderLayout lay = new BorderLayout();
setLayout(lay);
JLabel one = new JLabel("Choose your last number on the slider, the
slider goes from one to ten. Your first number was: " + num0 + ". Your
second number was: " + num1);
row1.add(one);
row2.add(slider);
row3.add(next);
add(row1, BorderLayout.NORTH);
add(row2, BorderLayout.CENTER);
add(row3, BorderLayout.SOUTH);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800,600);
PanelThree panelThree = new PanelThree(7, 2);
frame.setContentPane(panelThree);
frame.setVisible(true);
}
}
Panel Four:
import javax.swing.*;
import java.awt.*;
public class PanelFour extends JPanel {
JPanel row1 = new JPanel();
JPanel row2 = new JPanel();
JButton reset = new JButton("Reset");
public PanelFour(int num0, int num1, int num2) {
BorderLayout lay = new BorderLayout();
setLayout(lay);
int tot = num0 + num1 + num2;
JLabel total = new JLabel("All of your numbers add up to: " + tot);
row1.add(total);
row2.add(reset);
add(row1, BorderLayout.CENTER);
add(row2, BorderLayout.SOUTH);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800,600);
PanelFour panelFour = new PanelFour(7, 2, 9);
frame.setContentPane(panelFour);
frame.setVisible(true);
}
}
Now this is the problem, the class which tries to knit the four JPanels together and to have it react based on what the inputs were to the last JPanel in the JFrame. The issue seems to lie specifically with the actionPerformed method which is unable to access the components in the Frame constructor. Here is the code:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Frame extends JFrame implements ActionListener {
int x, y, z;
public void Frame() {
super("Number Adder");
int i = 1;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
PanelOne panelOne = new PanelOne();
panelOne.next.addActionListener(this);
PanelTwo panelTwo = new PanelTwo(x);
panelTwo.next.addActionListener(this);
PanelThree panelThree = new PanelThree(x, y);
panelThree.next.addActionListener(this);
PanelFour panelFour = new PanelFour(x, y, z);
panelFour.reset.addActionListener(this);
if (i == 1) {
add(panelOne);
} else if (i == 2) {
add(panelTwo);
} else if (i == 3) {
add(panelThree);
} else {
add(panelFour);
}
}
public actionPerformed(ActionEvent e) {
if (e.getSource() == panelOne.next) {
return x = int panelOne.slider.getValue();
return i = 2;
} else if (e.getSource() == panelTwo.next) {
return y = int panelTwo.slider.getValue();
return i = 3;
} else if (e.getSource() == panelThree.next) {
return z = int panelThree.slider.getValue();
return i = 4;
} else {
return i = 1;
}
repaint();
}
public static void main(String[] args) {
Frame frame = new Frame();
}
}
What can I do to fix this or improve this?
I don't think CardLayout will work here as it refers to the panels as strings
Why not?
You have a sequence of events.
Enter a number,
Display another panel.
There is no reason the second panel can't access the first number entered. That has nothing to do with a CardLayout.
Your second panel, just needs a way to access the data from the first panel. So maybe when you create the second panel you pass in the reference to the first panel. So when you display the second panel you can know access the number entered on the first panel.
My first question here. Already got a lot of help but now I don't know how to do.
My code:
package view;
import javax.swing.*;
public class OptionPlayerNames {
JPanel playerPanel = new JPanel();
JTextField playerNames = new JTextField();
public OptionPlayerNames() {
for (int i = 0; i < 8; i++) {
// JTextField playerNames = new JTextField();
playerPanel.add(new JLabel("Player " + (i + 1)));
playerPanel.add(playerNames);
}
playerPanel.setLayout(new BoxLayout(playerPanel, BoxLayout.Y_AXIS));
playerPanel.add(Box.createHorizontalStrut(5));
}
public JPanel getPanel(){
return playerPanel;
}
public String getPlayerNames() {
return playerNames.getText();
}
I want to have 8 Jlabels with just under it 8 JTextFields for user input.
Then get the text of the textfields.
Now I get only 1 text from 1 textField. Off course I only add 1 field.
When I put the JTextField under the for loop I get what I want but how to I get the text from all the JTextFields then? playerNames is then not known in the getter.
Thank you for your help.
You can do as follows, creating a Listof JTextField:
JPanel playerPanel = new JPanel();
List<JTextField> playerNames = new ArrayList<JTextField>();
public OptionPlayerNames() {
for (int i = 0; i < 8; i++) {
JTextField playerName = new JTextField();
playerPanel.add(new JLabel("Player " + (i + 1)));
playerPanel.add(playerName);
playerNames.add(playerName);
}
playerPanel.setLayout(new BoxLayout(playerPanel, BoxLayout.Y_AXIS));
playerPanel.add(Box.createHorizontalStrut(5));
}
public JPanel getPanel() {
return playerPanel;
}
public String getPlayerNames() {
String output = "";
// Compound you exit from the playerNames List
// Or better, return a List of String
return output;
}
You need to declare a Vector or array of JTextField as an instance variable (not just one, as you've commented out) and fill it in as you loop. Then you have random (arbitrary) access to any text value. Conveniently, the index i is already there for you to index into the array.
There should be a tip-off that the type: JTextField is singular, but your variable name: playerNames is plural. :-)
Note that getPlayerNames() also needs to be re-done to handle an array not a single field.
While this will work, ultimately, the whole code block isn't good separation of Model & View, so as you advance in programming, be sure to pay attention to that concept.
Ok so I'm building to show students how a loop goes through an array, I have added 2 images to help explain and the code, the first is the result I get after I click go then it freezes . The Second image is what I'd like it to do after you put in the values of 1 in start, 15 in stop, 3 in step and click the Go Button. And then to be cleared on the click of Clear button. I think they probably related. Can anyone see the problem? Thanks in advanced!
import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
import javax.swing.JOptionPane;
public class Checkerboard extends Frame implements ActionListener
{
int[] blocksTextField = new int[15];
Panel blocksPanel = new Panel();
TextArea blocksDisplay[] = new TextArea[16];
TextField start = new TextField (3);
TextField stop = new TextField (3);
TextField step = new TextField (3);
//Colors
Color Red = new Color(255, 90, 90);
Color Green = new Color(140, 215, 40);
Color white = new Color(255,255,255);
//textField ints
int inputStart;
int inputStop;
int inputStep;
//Lables
Label custStartLabel = new Label ("Start : ");
Label custStopLabel = new Label ("Stop : ");
Label custStepLabel = new Label ("Step : ");
//Buttons
Button goButton = new Button("Go");
Button clearButton = new Button("Clear");
//panel for input textFields and lables
Panel textInputPanel = new Panel();
//Panel for buttons
Panel buttonPanel = new Panel();
public Checkerboard()
{//constructor method
//set the 3 input textFields to 0
inputStart = 0;
inputStop = 0;
inputStep = 0;
//set Layouts for frame and three panels
this.setLayout(new BorderLayout());
//grid layout (row,col,horgap,vertgap)
blocksPanel.setLayout(new GridLayout(4,4,10,10));
textInputPanel.setLayout(new GridLayout(2,3,20,10));
buttonPanel.setLayout(new FlowLayout());
//setEditable()
//setText()
//add components to blocks panel
for (int i = 0; i<16; i++)
{
blocksDisplay[i] = new TextArea(null,3,5,3);
if(i<6)
blocksDisplay[i].setText(" " +i);
else
blocksDisplay[i].setText(" " +i);
blocksDisplay[i].setEditable(false);
// blocksDisplay[i].setBackground(Red);
blocksPanel.add(blocksDisplay[i]);
}//end for
//add componets to panels
//add text fields
textInputPanel.add(start);
textInputPanel.add(stop);
textInputPanel.add(step);
//add lables
textInputPanel.add(custStartLabel);
textInputPanel.add(custStopLabel);
textInputPanel.add(custStepLabel);
//add button to panel
buttonPanel.add(goButton);
buttonPanel.add(clearButton);
//ADD ACTION LISTENRS TO BUTTONS (!IMPORTANT)
goButton.addActionListener(this);
clearButton.addActionListener(this);
add(blocksPanel, BorderLayout.NORTH);
add(textInputPanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
//overridding the windowcClosing() method will allow the user to clisk the Close button
addWindowListener(
new WindowAdapter()
{
public void windowCloseing(WindowEvent e)
{
System.exit(0);
}
}
);
}//end of constructor method
public void actionPerformed(ActionEvent e)
{
//if & else if to see what button clicked and pull user input
if(e.getSource() == goButton) //if go clicked ...
{
System.out.println("go clicked");
try{
String inputStart = start.getText();
int varStart = Integer.parseInt(inputStart);
if (varStart<=0 || varStart>=15 )throw new NumberFormatException();
System.out.println("start = " + varStart);
// roomDisplay[available].setBackground(lightRed);
String inputStop = stop.getText();
int varStop = Integer.parseInt(inputStop);
if (varStop<=0 || varStart>=15 )throw new NumberFormatException();
System.out.println("stop = " + varStop);
String inputStep = step.getText();
int varStep = Integer.parseInt(inputStep);
if (varStep<=0 || varStep>=15 )throw new NumberFormatException();
System.out.println("step = " + varStep);
for (int i = varStart; i<varStop; varStep++)//ADD WHILE LOOP
{
blocksDisplay[i].setBackground(Red);
blocksDisplay[i].setText(" " +i);
}
}
catch (NumberFormatException ex)
{
JOptionPane.showMessageDialog(null, "You must enter a Start, Stop and Step value greater than 0 and less than 15",
"Error",JOptionPane.ERROR_MESSAGE);
}
}
else if(e.getSource() == clearButton ) //else if clear clicked ...
{
System.out.println("clear clicked");
}
//int available = room.bookRoom(smoking.getState());
//if (available > 0)//Rooms is available
}//end action performed method
public static void main(String[]args)
{
Checkerboard frame = new Checkerboard ();
frame.setBounds(50, 100, 300, 410);//changed size to make text feilds full charater size
frame.setTitle("Checkerboarder Array");
frame.setVisible(true);
}//end of main method
}
The problem is your loop: your loop variable name is i but you change the varStep variable instead of i so basically the loop variable never changes and thus the exit condition will never be true.
I believe you want to step i with varStep, so change your loop to:
for (int i = varStart; i<varStop; i += varStep)
// stuff inside loop
Take a look at this loop.
for (int i = varStart; i<varStop; varStep++)//ADD WHILE LOOP
{
blocksDisplay[i].setBackground(Red);
blocksDisplay[i].setText(" " +i);
}
It ends when i >= varStop, but neither i nor varStop change as a consequence of its execution, so it can never stop. You only increment varStep.
I think you want to increment i by varStep on each iteration instead, i.e. i += varStep
You use varStep++ in your for loop. I think you meant to do i+varStep.
The application freezes because you're never increasing i, resulting in an endless loop.
Hi I have to do a lottery with numbers when I first choice in a panel when I press Start it should serve me a panel with figures given them passed to the constructor panel but while I normally displays the panel the numbers in the JTextField does not apper.
The code when I press the button to make a panel with numbers at the function that returns to 2nd table numbers I put here a system.out and she shows them normally underneath its constructor passing the table as a parameter.
if (source == start) {
try {
int numbers[][] = fucts.takeBulletin();
RMIClient r=new RMIClient( numbers,1);
}catch() {
}
}
heare is the constructor code
public RMIClient(int [][]numbs,int a) {
super("!!!!!!!!!!!!!!!BINGO!!!!!!!!!!!!!!!!!!");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
Container pane = getContentPane();
GridLayout layout=new GridLayout(7 , 7);
pane.setLayout(layout);
pane.add(numB);
pane.add(numI);
pane.add(numN);
pane.add(numG);
pane.add(numO);
pane.add(num13);
for (int row = 0; row < numbs.length; row++) {
for (int col = 0; col < numbs[row].length; col++) {
pane.add(new JTextField(""+numbs[row][col])); <----- is nedd " "+
}
}
setContentPane(pane);
pack();
}
I can not understand why they do not pass the values from the table in textfield , is show me empty textfields
If it is a JApplet, try to move the whole content of the constructor into the init() method.
The constructor could save the int[][] numbs to an instance variable, and the init() method will see it.
int[][] numbs;
public RMIClient(int[][] numbs, int a) {
this.numbs = numbs;
}
public void init() {
...
}
these are my code I've problem with label when i read line from the text filed i can add the labels "_" that they are equal to the size of the word the program road it before.
I've problem creating label , I hope you understand my problem & please if you can can you give me a solution ?
public class HangGame extends JFrame {
JLabel lbl;
JLabel word ;
private String[]myword = new String [20];
Game() {
}
void readfile () {
Properties prob = new Properties();
try{
for(int x=0; x<n; x++){
}
}}
private void initLabelPanel() {
//craete array of labels the size of the word
letterHolderPanel = new JPanel();
int count =0;
//if you run my code I've problem with this array [myword.length()] the compiler can not find it.
wordToFindLabels = new JLabel[myword.length()];
//Initiate each labels text add tp array and to letter holder panel
for (int i = 0; ih; i++) {JLabel lbl = new JLabel("_");
letterHolderPanel.add(lbl);
lbl.setBounds();
}
}
}
myword is an array of Strings, not a single String so you need to replace:
wordToFindLabels = new JLabel[myword.length()];
with
wordToFindLabels = new JLabel[myword.length];
You could rename the variable to, say, mywordArray, to avoid confusion.
Also use a layout manager rather than using absolute positioning(null layout).
See: Doing Without a Layout Manager (Absolute Positioning)
length is property not method change the code accordingly
wordToFindLabels = new JLabel[myword.length];
and now youre code will be
for (int i = 0; i < wordToFindLabels.length; i++) {
String labelValue="";
if(myword[i] != null) {
for (int j = 0; j < myword[i].length(); j++){
labelValue+="_"
}
}
JLabel lbl = new JLabel(labelValue);
wordToFindLabels[i] = lbl;
letterHolderPanel.add(lbl);
lbl.setBounds(30, 60, 20, 20);
}