Jframe Jpanel - display result while window opened - swing

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.

Related

TextButton does not receive clicks in LibGDX

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.

Screen Display not proper on some screens Libgdx

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.

Positioning a button on a JPanel

I am trying to set the three buttons in the middle of this JPanel which is set above another panel.
Everything is working fine, but three buttons remains at the same position, no matter what.
How can I move the three buttons in the center of the panel2? Right now the three buttons are at the center Left of the panel2.
Code for my panel is here:
public AbcGeniusPanel()
{
//this.setVisible(false);
ImageIcon[] alphabets = new ImageIcon[26];
ImageIcon[] images = new ImageIcon[26];
setBackground(Color.yellow);
//Load the images for alphabet images into the alphabets array using a for loop
for(int i = 0; i < alphabets.length; i++)
{
alphabets[i] = new ImageIcon("C:\\Users\\Dip\\Desktop\\Java Projects\\AbcGeniusApp\\src\\Alphabets\\"+(i+1)+".png");
}
//Load the images images in the IMageIcon array
for(int i = 0; i < images.length; i++)
{
images[i] = new ImageIcon("C:\\Users\\Dip\\Desktop\\Java Projects\\AbcGeniusApp\\src\\Images\\"+(i+1)+".png");
}
//Create two JPanel objects
JPanel panel = new JPanel();
JPanel panel2 = new JPanel();
//Set a layoutManager on the panel
panel.setLayout(new GridLayout(2, 13, 5, 5)); //This is good for now
//Create an array for holdoing the buttons
buttons = new JButton[26];
/
//Try passing Images inside the JButton parameter later.
for(int i = 0; i < 26; i++)
{
buttons[i] = new JButton(alphabets[i]);
}
setLayout(new BorderLayout(2,0));
panel2.setLayout(new BoxLayout(panel2, BoxLayout.X_AXIS));
//add the panel to the Border layout
add(panel,BorderLayout.SOUTH);
add(panel2);
//Add evenHandling mechanism to all the buttons
for(int k = 0; k<26; k++)
{
buttons[k].addActionListener(this);
}
for(int count1 = 0; count1<26; count1++)
{
panel.add(buttons[count1]);
}
JButton button1 = new JButton();
JButton button2 = new JButton();
JButton button3 = new JButton();
panel2.add(button1);
panel2.add(button2);
panel2.add(button3);
}
You can use the BoxLayout (it may be easier just using Box.createHorizontalBox()) but you have to put vertical glue at each end of the box. You also may want to put horizontal struts between the buttons to give them some spacing.
It will be easier to just use a FlowLayout for your buttons, which does the equivalent of what I said without the extra code. There may be a potential drawback of the layout causing a button or 2 to flow over to the next line, but with your simple application it is probably not much of a chance.
Here are the two examples. Comment out one line and Comment in (???) the other line to see a different approach to the buttons:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class AlphabetExample {
public static void main(String[] args) {
AlphabetExample alphabetExample = new AlphabetExample();
JFrame frame = alphabetExample.createGui();
frame.setVisible(true);
}
private JFrame createGui() {
JFrame frame = new JFrame("Letters!");
frame.setSize(400, 300);
Container contentPane = frame.getContentPane();
contentPane.add(setupLetters(), BorderLayout.CENTER);
// contentPane.add(setupButtonsWithBox(), BorderLayout.NORTH); // <-- with a BoxLayout
contentPane.add(setupButtonsWithFlowPane(), BorderLayout.NORTH); // <-- with a FlowLayout
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
return frame;
}
private JPanel setupLetters() {
String letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
JPanel lettersPanel = new JPanel(new GridLayout(2, 13, 5, 5));
for (char x : letters.toCharArray()) {
final String letter = String.valueOf(x);
JButton button = new JButton(letter);
button.setActionCommand(letter);
lettersPanel.add(button);
}
return lettersPanel;
}
private JComponent setupButtonsWithBox() {
Box b = Box.createHorizontalBox();
b.add(Box.createHorizontalGlue());
b.add(new JButton("Left Button"));
b.add(Box.createHorizontalStrut(5));
b.add(new JButton("Center Button"));
b.add(Box.createHorizontalStrut(5));
b.add(new JButton("Right Button"));
b.add(Box.createHorizontalGlue());
return b;
}
private JComponent setupButtonsWithFlowPane() {
JPanel panel = new JPanel(); // default layout manager is FlowLayout
panel.add(new JButton("Left Button"));
panel.add(new JButton("Center Button"));
panel.add(new JButton("Right Button"));
return panel;
}
}
This solved my problem
for(int count1 = 0; count1<3; count1++)
{
panel2.add(Box.createHorizontalGlue());
panel2.add(imageButtons[count1]);
panel2.add(Box.createHorizontalGlue());
}

How to modify this view using GridBagLayout

I would be grateful if you could help me to modify this interface. I just started learning GridBagLayout and I want to figure out how I can implement the drawn interface using GridBagLayout()
|-----------------------------------------------|
| Playing File: name of the file | //This JLabel should cover the entire space
|-----------------------------------------------|
| 00:00:00 ----#---------------------- 00:00:00 | //This has on the left and on the right side two labels and in the middle a JSpinner
|-----------------------------------------------|
| [Open] [Play] [Pause] [Rewind] [Save] | //This line contains 5 buttons
|-----------------------------------------------|
Please find in attachment a working example
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.SwingUtilities;
public class Sample extends JPanel
{
private JLabel labelFileName = new JLabel("Playing File:");
private JLabel labelTimeCounter = new JLabel("00:00:00");
private JLabel labelDuration = new JLabel("00:00:00");
private JButton buttonOpen = new JButton(" Open ");
private JButton buttonPlay = new JButton(" Play ");
private JButton buttonPause = new JButton(" Pause ");
private JButton buttonRewind = new JButton(" Rewind ");
private JButton buttonSave = new JButton(" Save ");
private JSlider sliderTime = new JSlider();
GridBagConstraints constraints = new GridBagConstraints();
public Sample()
{
setLayout(new GridBagLayout());
constraints.insets = new Insets(5, 5, 5, 5);
sliderTime.setValue(0);
constraints.gridx = 0;
constraints.gridy = 0;
constraints.gridwidth = 5;
constraints.fill = GridBagConstraints.HORIZONTAL;
add(labelFileName, constraints);
constraints.gridx = 0;
constraints.gridy = 1;
constraints.gridwidth = 1;
add(labelTimeCounter, constraints);
constraints.gridx = 1;
constraints.gridy = 1;
constraints.gridwidth = 3;
add(sliderTime, constraints);
constraints.gridx = 4;
constraints.gridy = 1;
constraints.gridwidth = 1;
add(labelDuration, constraints);
JPanel panelButtons = new JPanel(new FlowLayout(FlowLayout.LEFT, 25, 5));
panelButtons.add(buttonOpen);
panelButtons.add(buttonPlay);
panelButtons.add(buttonPause);
panelButtons.add(buttonRewind);
panelButtons.add(buttonSave);
constraints.gridx = 0;
constraints.gridy = 2;
add(panelButtons, constraints);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
runApp();
}
});
}
public static void runApp()
{
JFrame frame = new JFrame("Frame");
frame.setVisible(true);
frame.setSize(800, 200);
frame.add( new Sample());
frame.setDefaultCloseOperation
}
}
Thanks
I would strongly suggest a one column grid with three rows.
The top row can be a panel set to flowlayout, or you could drop the label in directly. It is up to you to set the size of the label. Layout managers can't do that for you.
The middle row would be a borderlayout where the spinner is set to center, and the two labels are placed at east and west.
The bottom row should be a panel set with a flowlayout. To get the buttons nicely spaced out in your diagram, can only be done with a flowlayout.
My only concern would be that the slider panel could be resized in the vertical direction. In that case you might want to ditch the GridBaglayout, and just have a borderlayout on top where the top row is center, and the bottom two rows are packed into a panel that is south.

update text of textblock every a half of second in windows phone 8

I want to random a number of my array. Then I show it in a textblock. I want to do it every second. How to update my textblock every second ?. Please to help me.
Create a dispatcher timer and for every ticks update your textbock.
number = 0
dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0,0,1);
dispatcherTimer.Start();
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
//if you use binding and mvvm
this.Text = number.tostring();
//if you don't use binding
yourTextblock.Text = number.toString();
number ++;
}
create dispatcher timer and every half second update text box
int number=0;
private DispatcherTimer _timer;
public sample()
{
InitializeComponent();
_timer = new DispatcherTimer();
_timer.Interval = new TimeSpan(0, 0, 0,0,500);
_timer.Tick += _timer_Tick;
_timer.Start();
}
void _timer_Tick(object sender, EventArgs e)
{
number++;
yourTextblock.Text = number.toString();
}