Alright, so I'm simply defining a combo box like so...
JComboBox yearSelect = new JComboBox();
Now, I have not even added this to a panel or anything, I've just defined it. When I run the app, nothing displays.. when I comment out this line.. the app displays the other panels like I want it to.. is there something I'm doing wrong? Maybe I'm forgetting something that has to do with combo boxes? I think it may be something stupid that I'm missing.
Here is my entire constructor for the content.
private Container pane; // content pane
private JPanel calendarPanel; // where our calendar will go
private JPanel datePanel; // where "todays date" will go
private JPanel pnlToolbar; // tool bar for moving in the year
private JPanel bottomPanel;
private JPanel yearPanel;
private JLabel lbCurrentMonth;
private JLabel dateLabel;
private JButton monthBack;
private JButton monthForward;
private JComboBox yearSelect;
private Date today = new Date();
private int currentMonth = today.getMonth();
private int currentYear = today.getYear();
final private String [] days = {"Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday",
"Saturday"};
final private String [] months = {"January", "Febuary", "March", "April",
"May", "June", "July", "August",
"September", "October", "November",
"December"};
public Calendar() {
// call the calendar frame class constructor (Window class)
// this function will setup our basic window
super();
// define the current date of the calendar as today
// below are attributes to our window. They define what content
// is on them.
// define our window
pane = window.getContentPane();
pane.setLayout(new BorderLayout());
calendarPanel = new JPanel(new FlowLayout());
calendarPanel.setBorder(BorderFactory.createTitledBorder("Calendar"));
pnlToolbar = new JPanel(new FlowLayout(FlowLayout.CENTER, 40, 5));
pnlToolbar.setSize(300, 45);
//////////////////////////////////////////////////////////////////////
/* setup our lower date panel, that displays todays date
and the year drop down menu */
// for "todays date"
dateLabel = new JLabel(returnDateString());
dateLabel.setFont(new Font(null, Font.BOLD, 12));
datePanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 5));
datePanel.add(new JLabel("Todays Date: "), BorderLayout.WEST);
datePanel.add(dateLabel, BorderLayout.EAST);
// for "year select"
// yearSelect = new JComboBox();
yearPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 5, 5));
//yearPanel.add(yearSelect);
bottomPanel = new JPanel(new BorderLayout());
bottomPanel.add(datePanel, BorderLayout.WEST);
//bottomPanel.add(yearPanel, BorderLayout.EAST);
// setup the tool bar panel
lbCurrentMonth = new JLabel(months[currentMonth]);
monthBack = new JButton("<<");
monthForward = new JButton(">>");
monthForward.setEnabled(true);
monthBack.setEnabled(true);
pnlToolbar.add(monthBack);
pnlToolbar.add(lbCurrentMonth);
pnlToolbar.add(monthForward);
// add everything to the content panel
pane.add(calendarPanel, BorderLayout.CENTER);
pane.add(bottomPanel, BorderLayout.SOUTH);
pane.add(pnlToolbar, BorderLayout.NORTH);
You need to add a model to display your data. See JComboBox.setModel.
Yea still nothing, I've attached the rest of my code above. Even when I don't add the object to a panel, it does this. I'm simply instantiating the object, nothing more. Any ideas? Also, I've created a seperate application to make sure I'm doing the combo boxes correctly here is something I noticed. It doesnt the exact same thing in the sperate application.. below.. (very dirty)
public class Main {
public static void main(String[] args) {
String [] selectFill = {"Cat", "Dog"};
JFrame window = new JFrame("Window");
window.setBounds(0, 0 , 800, 600);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLayout(null);
//JComboBox selectBox = new JComboBox(selectFill);
JLabel check = new JLabel("Select: ");
JPanel contentPanel = new JPanel(new FlowLayout());
Container pane = window.getContentPane();
pane.add(contentPanel);
pane.setLayout(new FlowLayout());
contentPanel.add(check);
//contentPanel.add(selectBox);
}
}
For some strange reason when I resize the window, or minmize it loads the content. Or.. if I comment out the line for the combo box object it displays the content as well.
Related
I am trying to display client details in window application using Jframe. Everything is fine except that clients needs to wait until the process completed to show the result in window(Jframe).
Is there a way to show result(Jpanel.add()) dynamically after set Jframe.setVisible(true);
Note : I am new to this code
code I tried :
JFrame frame = new JFrame();
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}});
JPanel panel = new JPanel();
frame.setVisible(true);
int y=100;
for (int i = 0; i < 10; i++) {
//connecting DB and fetching data #single loop may take 5 secs to complete the process
panel.add(new JLabel("Client"+i)).setBounds(50,y, 100, 30); //after added, this should display in opened window
y=y+20;
//connecting DB and fetching data
for(int clinetDetails=0;clinetDetails< 3;clinetDetails++) {
panel.add(new JLabel("ClientDetails"+clinetDetails)).setBounds(50,y, 100, 30);
y=y+20;
}
panel.add(new JLabel("Client :"+i+" Completed")).setBounds(50,y, 100, 30);
y=y+20;
// frame.pack();
}
panel.setLayout(new GridLayout(0, 1));
JScrollPane scrollPane = new JScrollPane(panel);
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
frame.setPreferredSize(new Dimension(300, 300));
frame.pack();
You should probably use a SwingWorker, but this will give you an idea.
First you should do swing work on the EDT, so we start by creating the GUI.
static public void main(String[] args){
EventQueue.invokeLater( ()->createGui());
}
static public void createGui(){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.setVisible(true);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
JScrollPane scrollPane = new JScrollPane(panel);
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
frame.setPreferredSize(new Dimension(300, 300));
frame.pack();
Runnable r = ()->{
for (int i = 0; i < 10; i++) {
//connecting DB and fetching data #single loop may take 5 secs to complete the process //all of the swing work should be done on the EDT.
final String clientName = "Client"+i;
EventQueue.invokeLater( ()->{
panel.add(new JLabel( clientName ));
} );
//connecting DB and fetching data
for(int clinetDetails=0;clinetDetails< 3;clinetDetails++) {
String clientD = "ClientDetails "+clinetDetails;
EventQueue.invokeLater( ()->{
panel.add(new JLabel(clientD));
panel.add(new JLabel( clientName + " Completed" ) );
});
}
}
};
new Thread(r).start(); //starts the working thread.
}
This will start a gui, and then when the new thread starts, you'll free up the edt so that java can display your gui, then as new information is produced, it updates the gui by posting an even to the EDT.
I have to complete this code with these simple measures. Cannot do anything overly complicated. I want to translate from the top input text field and output on the bottom text field. So far, it looks right, but my translation simply outputs in the same text field as my input. I am a noob, and checked my notes and textbook, and cannot figure out how to change the output to the bottom field. It just doesn't seem to be possible with this level of code. The translation is right. I think I need to modify the Translate button, but am not sure where to indicate what. It works fine if I just wanted to output in my input box. Well, here is my code so far:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Translator4 extends JFrame implements ActionListener
{
public static final int WIDTH = 500;
public static final int HEIGHT = 500;
public static final int NUMBER_OF_CHAR = 50;
private JTextField phrase;
private JTextField translatedphrase;
public static void main(String[] args)
{
Translator4 gui = new Translator4();
gui.setVisible(true);
}
public Translator4()
{
//title bar and overall size
super("Pig Latin Translator v.4.0");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(3,1));
//create input text filed
JPanel namePanel = new JPanel();
namePanel.setLayout(new BorderLayout());
namePanel.setBackground(Color.WHITE);
phrase = new JTextField(NUMBER_OF_CHAR);
namePanel.add(phrase, BorderLayout.CENTER);
JLabel nameLabel = new JLabel("Enter the phrase in English to be translated:");
namePanel.add(nameLabel, BorderLayout.NORTH);
add(namePanel);
//create the buttons
JPanel buttonPanel= new JPanel();
buttonPanel.setLayout(new FlowLayout());
buttonPanel.setBackground(Color.GREEN);
JButton actionButton = new JButton("Translate");
actionButton.addActionListener(this);
buttonPanel.add(actionButton);
JButton clearButton = new JButton("Clear");
clearButton.addActionListener(this);
buttonPanel.add(clearButton);
add(buttonPanel);
//create the output text field
JPanel namePanel2 = new JPanel();
namePanel2.setLayout(new BorderLayout());
namePanel2.setBackground(Color.WHITE);
translatedphrase = new JTextField(NUMBER_OF_CHAR*2); //output will be larger so I multiplied it by 2
namePanel.add(phrase, BorderLayout.CENTER);
JLabel nameLabel2 = new JLabel("Translation:");
namePanel2.add(nameLabel2, BorderLayout.NORTH);
add(namePanel2);
}
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand();
if (actionCommand.equals("Translate")) //when the user wants a translation, this block executes
{
String[] words=new String[100]; //takes up to 100 words
String sentence = phrase.getText(); //the user input made into a string
String newSentence=""; //the output string generated
words = sentence.split(" "); //splits based on spaces, no other punctuation allowed
for (int index=0; index< words.length; index++) //steps thru the array of words
{
char firstChar = words[index].charAt(0); //rules for vowels, 'one' becomes 'oneway'
if (firstChar=='a'||firstChar=='e'||firstChar=='i'||firstChar=='o'||firstChar=='u')
{
words[index] = words [index] + "way";
newSentence=newSentence + " " + words[index]; //adds the word just now modified to new sentence
}
else //rules for words that don't start with vowels, 'blank' becomes 'lankbay'
{
firstChar = ' ';
words[index] = (words[index]).substring(1,(words[index].length()))
+ (words[index]).charAt(0) + "ay";
newSentence=newSentence + " " + words[index]; //adds the word just now modified to new sentence
}
phrase.setText(newSentence); //sends the new sentence back for output... problem here
}
}
else if (actionCommand.equals("Clear"))
phrase.setText("");
else
phrase.setText("Unexpected error.");
}
}
but my translation simply outputs in the same text field as my input
That's because that's what you're telling it to do
phrase.setText(newSentence); //sends the new sentence back for output... problem here
So I assume, phrase is the input and translatedphrase is the output, so that would mean, to fix your immediate issue, all you need to do is replace phrase with translatedphrase
translatedphrase.setText(newSentence); //sends the new sentence back for output... no more problem
I would also suggest you change the other setText calls you're making against phrase to translatedphrase as well
This...
translatedphrase = new JTextField(NUMBER_OF_CHAR * 2); //output will be larger so I multiplied it by 2
namePanel.add(phrase, BorderLayout.CENTER);
JLabel nameLabel2 = new JLabel("Translation:");
namePanel2.add(nameLabel2, BorderLayout.NORTH);
is also an issue, as you never actually add translatedphrase to anything, you just re-add phrase to namePanel again
So, I assume it should be
translatedphrase = new JTextField(NUMBER_OF_CHAR * 2); //output will be larger so I multiplied it by 2
namePanel2.add(translatedphrase, BorderLayout.CENTER);
JLabel nameLabel2 = new JLabel("Translation:");
namePanel2.add(nameLabel2, BorderLayout.NORTH);
Here is my code:
public WelcomeScreen(final WallGame game) {
this.game = game;
// Setting up camera and viewport.
camera = new OrthographicCamera();
viewport = new StretchViewport(GAME_WORLD_WIDTH, GAME_WORLD_HEIGHT, camera);
viewport.apply();
stage = new Stage(viewport);
camera.position.set(camera.viewportWidth / 2, camera.viewportHeight / 2, 0);
Gdx.input.setInputProcessor(stage);
skin = new Skin(Gdx.files.internal("uiskin.json"));
skin.getFont("default-font").getData().setScale(0.1f, 0.1f);
backgroundTxtr = new Texture(Gdx.files.internal("background/background.png"));
background = new Image(backgroundTxtr);
background.setBounds(0, 0, GAME_WORLD_WIDTH, GAME_WORLD_HEIGHT);
final TextButton button = new TextButton("start", skin, "red-button");
button.setBounds(10, 10, 50, 50);
button.setTouchable(Touchable.enabled);
button.addListener(new ClickListener() {
public void clicked(InputEvent event, float x, float y) {
Gdx.app.log("AKS", "CLICKED");
}
});
final Dialog dialog = new Dialog("Click Message", skin);
dialog.setBounds(50, 50, 40, 40);
stage.addActor(background);
stage.addActor(button);
stage.addActor(dialog);
}
I can't seem to make the button work, I have an image to be shown when the button is clicked (the "down" attribute of the TextButton) but it doesn't change. What am I doing wrong?
I figured it out. I hadn't created a Table object to add the button into. It worked after I did that.
I am developing a game in which i am making a Game Over Screen but the components are not rearranging properly.
What i am Getting on 1024 * 720 screen is:
and what it should look like:
and the code is:
#Override
public void show() {
stage = new Stage(new ScreenViewport());
camera = new OrthographicCamera(Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
Gdx.input.setInputProcessor(stage);
font = new BitmapFont(Gdx.files.internal("newfont.fnt"));
verysmallfont = new BitmapFont(Gdx.files.internal("verysmallfont.fnt"));
smallfont = new BitmapFont(Gdx.files.internal("smallfont.fnt"));
atlas = new TextureAtlas("ui/buttons.pack");//add atlas
skin = new Skin(atlas);
table = new Table(skin);
actiontable = new Table(skin);
actionbar = new Table(skin);
actionbar2 = new Table(skin);
table.setBounds(0,0,Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
actiontable.setBounds(0,0,Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
actionbar.setBounds(0,0,Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
actionbar2.setBounds(0,0,Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
TextButton.TextButtonStyle buttonback = new TextButton.TextButtonStyle();
buttonback.up = skin.getDrawable("back");
buttonback.pressedOffsetX = 1;
buttonback.pressedOffsetY = -1;
buttonback.font = font;
buttonBack = new TextButton("",buttonback);
TextButton.TextButtonStyle lifebuttonstyle = new TextButton.TextButtonStyle();
lifebuttonstyle.up = skin.getDrawable("life");
lifebuttonstyle.pressedOffsetX = 1;
lifebuttonstyle.pressedOffsetY = -1;
lifebuttonstyle.font = font;
buttonlife = new TextButton("",lifebuttonstyle);
TextButton.TextButtonStyle textButtonStyle = new TextButton.TextButtonStyle();
textButtonStyle.up = skin.getDrawable("heart_game_continue");
textButtonStyle.pressedOffsetX = 1;
textButtonStyle.pressedOffsetY = -1;
textButtonStyle.font = font;
buttonPlay = new TextButton("",textButtonStyle);
TextButton.TextButtonStyle adsfreeStyle = new TextButton.TextButtonStyle();
adsfreeStyle.up = skin.getDrawable("Video");
adsfreeStyle.pressedOffsetX = 1;
adsfreeStyle.pressedOffsetY = -1;
adsfreeStyle.font = font;
buttonVideo = new TextButton("",adsfreeStyle);
TextButton.TextButtonStyle sharebuttonStyle = new TextButton.TextButtonStyle();
sharebuttonStyle.up = skin.getDrawable("Replay");
sharebuttonStyle.pressedOffsetX = 1;
sharebuttonStyle.pressedOffsetY = -1;
sharebuttonStyle.font = font;
buttonReplay = new TextButton("",sharebuttonStyle);
Label.LabelStyle headingstyle = new Label.LabelStyle(font,Color.WHITE);
label = new Label("Game Over",headingstyle);
label.setFontScale(1.7f);
Label.LabelStyle contstyle = new Label.LabelStyle(smallfont,Color.WHITE);
cont = new Label("Continue?",contstyle);
cont.setFontScale(2f);
Label.LabelStyle replaystyle = new Label.LabelStyle(verysmallfont,Color.WHITE);
replay = new Label("Replay",replaystyle);
shortVideo = new Label("(Short Video)",replaystyle);
replay.setFontScale(2f);
shortVideo.setFontScale(2f);
table.align(Align.top);
table.padTop(197f);
table.add(label);
table.getCell(label).spaceBottom(150f);
table.row();
table.add(cont);
table.getCell(cont).spaceBottom(80f);
table.row();
table.add(buttonPlay).size(200f,200f);
actiontable.add(buttonVideo).size(200f,200f);
actiontable.add(buttonReplay).size(200f,200f);
actiontable.align(Align.bottom);
actiontable.getCell(buttonVideo).spaceBottom(20f).padRight(100f);
actiontable.getCell(buttonReplay).spaceBottom(20f).padLeft(100f);
actiontable.row();
actiontable.add(shortVideo).padRight(100f);
actiontable.add(replay).padLeft(100f);
actiontable.padBottom(197f);
actiontable.setFillParent(true);
actionbar.align(Align.topLeft).setWidth(Gdx.graphics.getWidth());
actionbar.add(buttonBack).align(Align.left).size(90f,90f);
actionbar2.align(Align.topRight);
actionbar2.add(buttonlife).align(Align.right).size(90f,90f);
actionbar.getCell(buttonBack).pad(43f);
actionbar2.getCell(buttonlife).align(Align.right).pad(43f);
stage.addActor(actionbar2);
stage.addActor(actionbar);
stage.addActor(table);
stage.addActor(actiontable);
buttonPlay.addListener(new ClickListener(){
#Override
public void clicked(InputEvent event, float x, float y) {
((Game) Gdx.app.getApplicationListener()).setScreen(new Main(level,a,start,sweep,collide,innerarcs,out,mid,arcsleft,left,pointerColor));
};
});
buttonReplay.addListener(new ClickListener(){
#Override
public void clicked(InputEvent event, float x, float y) {
int total = out+mid+innerarcs;
((Game) Gdx.app.getApplicationListener()).setScreen(new Main(level,a,total,pointerColor));
}
});
buttonBack.addListener(new ClickListener(){
#Override
public void clicked(InputEvent event, float x, float y) {
((Game) Gdx.app.getApplicationListener()).setScreen(new Menu(level));
}
});
}
SpriteBatch batch;
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0.184f,0.184f,0.184f,1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.act(delta);
stage.draw();
}
private OrthographicCamera camera;
#Override
public void resize(final int width, final int height) {
table.setTransform(true);
table.setSize(width,height);
actiontable.setTransform(true);
actiontable.setSize(width,height);
actionbar.setTransform(true);
actionbar.setSize(width,height);
}
I am new to libgdx please help i dont have any knowledge about how to use camera and viewports.
Thanks in advance..
€dit: sorry my bad - there's nothing like "stage.resize"
But I'll let the answer in, because it'll fix your problem, though not as fast as you wish, but in a more clear way.
(THE FOLLOWING TEXT IS NOT NECESSARRY FOR THE ANWSER AND ARE ONLY SUGGESTIONS)
(if you follow the following steps, you'll save yourself time & headaches in the future)
I'd suggest a viewport, because they'll kill many problems with scaling, and there are quite a few, from which you can choose, as you need.
LibGdx Viewports
A viewport takes care for different screen sizes with the help from different techniques (e.g. scaling, black bars)
Additionally a viewport is SUPER easy to implement.
You'll do the following(e.g. FitViewport(stretches content, if necessary)):
stage = new Stage();
OrthographicCamera cam = new OrthographicCamera();
cam.setToOrtho(false, 800, 600);
stage.setViewport(new FitViewport(800, 600, cam));
TADA. You implemented a viewport. Was not so hard.
(but make sure to call stage.getViewport().update(w, h) in the resize(w, h) method!! AND DON'T FORGET IT!!)
Second suggestion I'd do is:
Use a main table.
So you do following
Table myMothershipTable = new Table();
myMothershipTable.setFillParent(true);
myMothershipTable.add(add);
myMothershipTable.add(all);
myMothershipTable.add(content);
stage.addActor(myMothershipTable);
Now you've only one actor, which is the table, and you can be damned sure, that this table will fill the whole screen.
Your screen is 10999x3? yeah. the table will be 10999x3.
Good. If you've refactored your whole stuff into one table I'd suggest the next step:
stage.setDebugAll(true); //this will help you to see the actual buildup from your actors & elements
So heres the why:
The viewport takes care for your stage size
the single table makes sure, that your complete content will be within the screen ==> now you can add one item after another, and make sure with..
stage.setDebugAll(true).. that your content is placed properly.
If you follow this simple steps, you'll save yourself a lot of time and headache with designing the UI.
To be accurate and brief:
Is it possible to Layout a frame container with group of components(like check boxes, radio buttons, etc...) instead of adding them one by one to a frame? So, positioning them in a frame would be a lot more easier.
private void initializaUI(){
setSize(700, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Panel container to wrap checkboxes and radio buttons
JPanel panel = new JPanel(null);
JPanel checkBoxPanel = new JPanel(new BoxLayout(panel, defaultCloseOperation, null));
JPanel radioPanel_1 = new JPanel(new GridLayout());
JPanel radioPanel_2 = new JPanel(new GridLayout());
//Text field to display order
JTextField orderField = new JTextField(20);
orderField.setBounds(100, 100, 100, 20);
//Button to process place the order
JButton button = new JButton("Process Selection");
button.setBounds(300, 100, 100, 40);
//toppings check boxes
checkBoxPanel.setVisible(true);
checkBoxPanel.setBounds(100, 200, 100, 50);
String Topping[] = {"Tomato", "Green Pepper", "Black Olives", "Mushrooms", "Extra Cheese", "Pepperoni", "Sausage"};
checkBoxPanel.add(new JCheckBox("Tomato"));
checkBoxPanel.add(new JCheckBox(Topping[1]));
checkBoxPanel.add(new JCheckBox(Topping[2]));
checkBoxPanel.add(new JCheckBox(Topping[3]));
checkBoxPanel.add(new JCheckBox(Topping[4]));
checkBoxPanel.add(new JCheckBox(Topping[5]));
checkBoxPanel.add(new JCheckBox(Topping[6]));
//sizes radio buttons
String size[] = {"Small:$6.50", "Medium:$8.50", "Large:$10.00"};
JRadioButton radio = new JRadioButton(size[0]);
radio.setBounds(100, 50, 100, 20);
//
panel.add(checkBoxPanel);
//
setContentPane(panel);
This is the code which supposed to perform some actions based on user entry. please help me make it clear and readable.
This is the error: "The field Component.x is not visible"
Yes, that's what a JPanel is for. It's an empty container that has its inner layout manager and that can be placed wherever you want inside a JFrame (or inside another JPanel). So, just to give you an example you can have:
JPanel checkBoxPanel = new JPanel(new GridLayout(..));
JPanel fieldsPanel = new JPanel(new BoxLayout(..));
checkBoxPanel.add(new JCheckBox(..));
fieldsPanel.add(new JTextField(..));
frame.setLayout(new BorderLayout());
frame.add(checkBoxPanel, BorderLayout.NORTH);
frame.add(..)