I am using the Becker Robots making a board game with two player. One Random and one Human (me).
The player should click UP, DOWN, LEFT, RIGHT buttons.
So far: I have created 2 classes. One that displays the board (9,9) and one that contains the player buttons.
I want to move this button into my main board display board. However, I want to keep these classes seperate because in order to make them do something I will need a listener class for each button which also redirects to the main.
import becker.robots.*;
import javax.swing.*;
public class PlayerButtons {
public static void main(String[] args) {
JFrame frame = new JFrame ("Test");
frame.setVisible(true);
frame.setSize(200,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contents = new JPanel();
JButton upButton = new JButton("UP");
JTextArea textDisplay = new JTextArea (5,10);
//set it up
contents.add(upButton);
contents.add(textDisplay);
//display in panel
frame.setContentPane(contents);
}
}
I think you should take a look to MODEL VIEW CONTROLER:
http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
It also could help if you post more code, but guessing, you could create a listener and check the boton id. On that way you'll be able to have just one listener.
Related
I have a problem with elements showing up on my GUI. I am creating a very simple program where I ask the user to input three different integers in three different boxes and a button to add the numbers together when it is pressed. Right now, I have created a button, a textfield, and a label but there's a problem: The button, textfield, and label does not appear on the GUI. I have to hover over the button area for it to appear and same with the textfield. The label doesn't show up at all even when I hover where it's supposed to be. Any reason why this is happening? Here's my code
import javax.swing.*;
public class ButtonPractice extends javax.swing.JFrame
{
public static void main(String[] args)
{
JFrame box = new JFrame("Simple addition");
box.setVisible(true);
box.setSize(500,500);
box.setResizable(false);
box.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(null);
box.add(panel);
JTextField inputNumOne = new JTextField("Integer here");
inputNumOne.setBounds(225,50,200,30);
panel.add(inputNumOne);
JLabel labelNumOne = new JLabel("First integer");
labelNumOne.setBounds(100,50,150,50);
panel.add(labelNumOne);
JButton combiner = new JButton("Concactentate");
//positioning of the button on the panel
combiner.setBounds(175,300,125,50);
panel.add(combiner);
}
}
Thanks in advance to those who review the code!
Call
box.getContentPane().add(panel);
after you've created your panel. Then call
box.setVisible(true) after that.
You should also not set your layout manager to null. Leaving it at the default FlowLayout is ok to start with.
I have a Jframe that the user enters new information through a Joptionpane, it is added to an array which is then appended and displayed to a contentpane.. the cycle then repeats till the user enters "STOP". Currently the program is outputting the new array under the old one. How would I clear away the old array in the content pane and only display the new values?
import java.awt.*;
import java.util.LinkedList;
import java.util.List;
public class Project1GUI {
static JFrame Frame;
static TextArea unsorted_words, sorted_words, linked_words;
public Project1GUI(String title){
//All this does is make an empty GUI FRAME.
Frame=new JFrame();//i made a new variable from the JFrame class
Frame.setSize(400,400);//Used the Variable from JFrame and used some of it functions. This function sets the hieght and width of the Frame
Frame.setLocation(200,200);//This sets where the Empty Frame should be
Frame.setTitle(title);//This puts a title up top of the Frame
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//places an x box that closes when clicked on
Frame.setVisible(true);//This activates the JFram when is set true.
Frame.setLayout(new GridLayout(1,2));//This sets the layout of the Frame and since i want a Grid i used a GirdLayout
//Functions and placed it inside the setlayout functions. to get 2 grids i places 1 meaning 1 row and 2 for 2 cols
unsorted_words=new TextArea(); //From the TextArea class i made three variables
sorted_words= new TextArea();
linked_words= new TextArea();
Container panel=new Container();
panel=Frame.getContentPane();
panel.add(unsorted_words);
panel.add(sorted_words);
panel.add(linked_words);
}
public void add_unsorted(String words){
unsorted_words.append(words+"\n");//add words to GUI
}
public void add_sorted(String words){
sorted_words.append(words+"\n");
}
public void add_linked(List<String> linked_words2){
linked_words.append(linked_words2+"\n");
}
}
For a more definitive answer, post an MCVE
Seeing as you haven't posted any code, I'm guessing you are using a JLabel or a JList or something of that sort to display the array. No matter which one you are doing, you need to tell the component to update it's content, it doesn't just do it itself. To do that, you need to call the components .setText() or similar method.
If you have a JLabel or JTextArea it could look like this.
labelOrTextArea.setText("New Text");
If you are using a JList you should update the lists Default List Model like this
dlm.addElement("New Text");
UPDATE
I see a couple things wrong with your code. First off JFrame Frame = new JFrame conventionally, variables should start with a lower case letter and they should not contain underscores '_'. You are also using AWT Components instead of Swing components. You should be using the likes of JTextArea, JPanel (Theres no JContainer), JLabel etc.
You are also never adding the panel to the frame.
frame.add(panel);
You should also not be adding stuff to the frame or panels after you set its visibility to true. So you should setup your frame like this
import javax.swing.*;
import java.awt.*;
import java.util.List;
public class Project1GUI
{
JTextArea unsorted_words, sorted_words, linked_words;
public Project1GUI()
{
JFrame frame = new JFrame("Title");
JPanel panel = new JPanel(new GridLayout(2, 1));
unsorted_words = new JTextArea();
sorted_words = new JTextArea();
linked_words = new JTextArea();
panel.add(unsorted_words);
panel.add(sorted_words);
panel.add(linked_words);
frame.add(panel);
frame.setSize(400,400);
frame.setLocation(200,200);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
You can then implement the methods you currently have and call them in an ActionListener or such.
Result:
On top of all of that, you should not rely on the use of static as it takes away from the main points of OOP.
I'm working on large scale program. As you can see I have one main JFrame and about 20 menu items on that. Each menu item must pop up a new window. At the beginning I have created a JLayeredPanel and then I assigned each menu item to one JPanel which is inside JFrame.Then I put 25 panel in JLayeredPanel... Default all the panels are set to invisible like:
panel1.setVisible(false);
panel2.setVisible(false);
so on
When user click on one menu item, its JPanel will be visible and rest are invisible. It looks messy and I have 5000 lines code. I used InternalFrame and TabbedPane but I'm not happy with them. I want to split my code in different JPanel classes and assign them to the main JFrame. I mean when user clicked on each menu item it will call the external JPanel and render it on the JPanel on the main JFrame. I am using design mode in netbeans and it does everything for me but the simpled structure is like this and it is not working:
public class NewJPanel extends JPanel{
//I have added buttons and etc on this panel
......
}
public class frame extends JFrame(){
JPanel panel = new JPanel();
.....
Public frame(){
frame.add(panel);
}
......
//When use click on the any button on the panel
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
//this is not working
NewJPanel fi = new NewJPanel ();
panel1.add(fi);
//or I tested this way separately but it did not work
panel1.remove();
panel1 = new NewJPanel();
add(panel);
invalidate();
}
}
please give me any suggestion how I can control this program in splited classes in professional way.
remove JPanel from JFrame.getContentPane.remove(myPanel)
add a new JPanel with constants, everyhing depends of used LayoutManager and its methods implemented in API
call JFrame.(re)validate() and JFrame.repaint() as last code lines, if everything is done, these notifiers correctly repaint available area
again to use CardLayout, there isn't signoficant performance or memory issue
Please give me any suggestion how I can control this program in splited classes in proressional way.
Ok.
You should put all of your JPanels in a JTabbedPane. The JTabbedPane would be added to the JFrame.
The JFrame, JTabbedPane, and each JPanel would be constructed in a separate class.
You use Swing components, rather than extending them. The only reason you extend a Swing component is if you override one of the component methods.
You should also create model classes for each of the JPanels, as well as a model class for the application.
Read this article to see how to put a Swing GUI together.
make's code better
public class NewJPanel extends JPanel{
//I have added buttons and etc on this panel
......
}
public class frame extends JFrame(){
JPanel panel = new JPanel();
.....
Public frame(){
//frame.add(panel); you dont need call frame because extends JFrame in frame class
add(panel);
......
//When use click on the any button on the panel
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
//this is not working
NewJPanel fi = new NewJPanel();
add(fi);
//or I tested this way separately but it did not work
/*panel1.remove();
panel1 = new NewJPanel();
add(panel);
invalidate();you must define panel1 before use it,like :JPanel panel1 = new JPanel();*/
}
}
So, I have been working on a Java Memory/Concentration Game assignment. I've not gotten as far as I wanted, it's only half finished, but I did have the GUI mostly working... Until I tried to add radio buttons to my Frame. I think the problem might be because I changed a JFrame(CardButtonPanelFrame) into a JPanel. I'm trying to add 3 JPanels to a larger JPanel which I add to a JFrame. I'm just getting a small blank window popping up when I used to have all 52 cards pop up.
Basically when I work on projects things can get out of control in their complexity so I thought I'd come here to make sure I'm heading in the right direction.
Here's my main:
import javax.swing.*;
public class Project3{
public static void main(String[] args){
JFrame frame = new JFrame();
Grid game = new Grid();
frame.pack();
frame.add(game);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Then this is outermost JPanel I'd like to hold the radio buttons at the top, the cards in the middle, and eventually the score at the bottom.
import java.awt.*;
import javax.swing.*;
public class Grid extends JPanel{
public Grid(){
JPanel panel = new JPanel(); //construct a frame
CardButtonPanelFrame buttons = new CardButtonPanelFrame();
wtf choices = new wtf();
panel.setLayout(new GridLayout(3,1)); //that panel uses GridLayout
panel.add(choices);//add the panels to the Frame
panel.add(buttons);
//frame.add(scores);
add(panel);
setVisible(true);
}
}
This is the radiobuttons panel... named wtf because I had some compiling issues and experimented with changing the name. I've not even gotten to the stage of figuring out how to implement the different player amounts yet.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class wtf extends JPanel implements ActionListener {
static String zerostring = "Zero Player Game";
static String onestring = "One Player Game";
static String twostring = "Two Player Game";
public wtf() {
super(new BorderLayout());
//Create the radio buttons.
JRadioButton zeroButton = new JRadioButton(zerostring);
zeroButton.setMnemonic(KeyEvent.VK_C);
zeroButton.setActionCommand(zerostring);
JRadioButton oneButton = new JRadioButton(onestring);
oneButton.setMnemonic(KeyEvent.VK_B);
oneButton.setActionCommand(onestring);
oneButton.setSelected(true);
JRadioButton twoButton = new JRadioButton(twostring);
twoButton.setMnemonic(KeyEvent.VK_D);
twoButton.setActionCommand(twostring);
//Group the radio buttons.
ButtonGroup group = new ButtonGroup();
group.add(zeroButton);
group.add(oneButton);
group.add(twoButton);
//Register a listener for the radio buttons.
zeroButton.addActionListener(this);
oneButton.addActionListener(this);
twoButton.addActionListener(this);
//Put the radio buttons in a column in a panel.
JPanel radioPanel = new JPanel(new GridLayout(0, 1));
radioPanel.add(zeroButton);
radioPanel.add(oneButton);
radioPanel.add(twoButton);
add(radioPanel, BorderLayout.LINE_START);
setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
}
/** Listens to the radio buttons. */
public void actionPerformed(ActionEvent e) {
//do something with e.getActionCommand()
}
}
So I have two more classes but I think the current problem is here and I'm afraid of making this a giant wall of code. I have more questions but I think I'll take it one at a time so I don't end up posting pages and pages of code that no one wants to read.
One problem you're doing is calling pack() on your JFrame before adding components. Don't do that, but instead add all components that you can first, then call pack(), then setVisible(true)
Hello
I'm an amateur trying to learn/improve my understanding of Java by writing a score card for archery. I ‘m trying to produce a GUI and so far have successfully produced on a JPanel a row of 18 labels of differing sizes and colours suitable for scoring a dozen.
I then tried to add five of these 'labels panels' to another panel to build up a grid and save having to create and add as many as 150 labels in some cases . No success so far as the original labels panels will not show up. All the panels are displayed on a JFrame
I've tried a number of different ways of getting the code to work, using the Java tutorial and googling the internet and studying similar problems on this site but I'm going round in circles. I must have missed something somewhere and hope that you may be able to help.
I'm using Java 6 and JGrasp v1.8.8_01 as an IDE
The following code for the labels panel has been cut down as much of it is repetitive.
import javax.swing.*;
import java.awt.*;
public class ArrowScoreLabels extends JPanel{
public JPanel createContentPane(){
JPanel panelForLabels = new JPanel();
panelForLabels.setLayout(null);
//Code creates 18 labels, sets the size, position, background colours, border and
//font and adds the labels to the’panelForLabels
JLabel scorelabel1;
scorelabel1 = new JLabel("",JLabel.CENTER);
scorelabel1.setBorder(BorderFactory.createLineBorder(Color.black));
scorelabel1.setFont(new Font("Arial", Font.ITALIC, 26));
scorelabel1.setLocation(0, 0);//first value differs for each label
scorelabel1.setSize(35, 35);
scorelabel1.setOpaque(true);
panelForLabels.add(scorelabel1);
panelForLabels.setOpaque(true);
return panelForLabels;
}
}
Running the following class shows the 18 labels on panel
import javax.swing.*;
import java.awt.*;
public class TestArrowScoreLabels {
private static void createAndShowArrowLabels() {
//Create and set up the window.
JFrame frame = new JFrame("To score one dozen");
//Create and set up the content pane.
ArrowScoreLabels asl = new ArrowScoreLabels();
frame.setContentPane(asl.createContentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(676, 73);
frame.setVisible(true);
}
//Main method to show the GUI/
public static void main(String[] args) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
createAndShowArrowLabels();
}
});
}
}
The following code for the second panel is similar, compiles but only shows the second green JPanel and not the panel with the labels.
import javax.swing.*;
import java.awt.*;
public class FiveDozenScorePanel{
public JPanel createContentPane(){
//A bottom JPanel on which to place five dozenpanels.
JPanel fivedozenpanel = new JPanel();
fivedozenpanel.setLayout(null); //requires absolute spacing
fivedozenpanel.setSize(676,185);
fivedozenpanel.setBackground(Color.green);
//Label panels for five dozen
ArrowScoreLabels dozenscorepanel1, dozenscorepanel2,
dozenscorepanel3,dozenscorepanel4,dozenscorepanel5;
//Create the 5 dozenscorelabels.
dozenscorepanel1 = new ArrowScoreLabels();
dozenscorepanel1.setLocation(5,5);//y value changes for each panel
fivedozenpanel.add(dozenscorepanel1);//plus the other 4
fivedozenpanel.setOpaque(true);
return fivedozenpanel;
}
private static void createAndShowDozenPanels() {
JFrame frame = new JFrame("To score five dozen");
FiveDozenScorePanel fdsp = new FiveDozenScorePanel();
frame.setContentPane(fdsp.createContentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Display the window
frame.setSize(700, 233);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
createAndShowDozenPanels();
}
});
}
}
I've also tried frame.getContentPane().add(fdsp); - frame.pack(); and read so much about paint methods that I'm totally confused.
I can get the ArrowScoreLabels image to appear directly onto a JFrame rather than a JPanel but only one of them and not five.
I would appreciate being pointed in the right direction. Thankyou for your time.
Update - 14th Dec 2010
I have managed to display the panelForLabels Jpanel on another Jpanel on a JFrame. This was done by adding the following code to the class ArrowScoreLabels. The original createContentPane() method was renamed createRowOne(). The panelForLabels was coloured red and the fivedozen panel yellow to ascertain which was showing. However I was only able to persuade the programme to display one row of labels despite a great deal of experimentation and research.
public static JPanel createContentPane(){
//Bottom panelto hold rows of labels
JPanel fivedozenscorepanel = new JPanel();
fivedozenscorepanel.setLayout(null);//requires absolute spacing
fivedozenscorepanel.setSize(660,180);
fivedozenscorepanel.setBackground(Color.yellow);
fivedozenscorepanel.add(createRowOne());
fivedozenscorepanel.setOpaque(true);
return fivedozenscorepanel;
}
The only way I displayed the 5 rows of 18 labels was to create all 90 in the ArrowScoreLabels class and then add them to one JPanel using absolute spacing and then to a JFrame.
I've taken note of pstantons advice - thankyou for that - and I'm looking into using the MigLayout Manager.
simple answer: use a layout manager. don't use absolute positioning.
just comment out all of your calls to setLocation and setLayout and swing will use the default FlowLayout.
for more control over the display, use a different layout manager.
also, if you use multiple panels you will have trouble aligning things in different panels unless they contain the same number of components which are exactly the same size so consider using one panel for all of the labels.
you can achieve just about any layout you need using MigLayout.
EDIT: in your example, there's no need for ArrowScoreLabels need to extend JPanel since you are doing the work in createContentPane to construct a separate JPanel. later in your code you call new ArrowScoreLabels() wich will just return a blank JPanel, instead you need to call new ArrowScoreLabels().createContentPane()
if you want ArrowScoreLabels to extend JPanel, implement public ArrowScoreLabels() ie the constructor instead of createContentPane.
I've the impression you don't set a size to your dozenscorepanel1. So, set a size :-)
Be careful with the layout null, because it's a pain ; you always forget something. Write your own, or use an existing one.