I use JToolbarButton button, I want to make it be "pressed" when I click on it, just like JButton works.How can I do this?
Please help!Thanks.
As mentioned in Costis' reply, you are probably after a JToggleButton. It might also be necessary to suppress the painting of the border, as in the 2nd tool bar in this example.
import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
class ToggleBar {
public static JToggleButton getButton(
Image selected,
Image unselected,
boolean decorated) {
JToggleButton b = new JToggleButton();
b.setSelectedIcon(new ImageIcon(selected));
b.setIcon(new ImageIcon(unselected));
b.setBorderPainted(decorated);
return b;
}
public static Image getCircleImage(Color c) {
BufferedImage bi = new BufferedImage(
32,32,BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bi.createGraphics();
g.setColor(c);
g.fillOval(0,0,32,32);
g.dispose();
return bi;
}
public static void main(String[] args) {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
Image red = getCircleImage(Color.RED);
Image green = getCircleImage(Color.GREEN);
JPanel p = new JPanel(new GridLayout(0,1));
JToolBar tb1 = new JToolBar();
for (int ii=0; ii<5; ii++) {
tb1.add( getButton(red, green, true) );
}
p.add(tb1);
JToolBar tb2 = new JToolBar();
for (int ii=0; ii<5; ii++) {
tb2.add( getButton(red, green, false) );
}
p.add(tb2);
JOptionPane.showMessageDialog(null, p);
}
});
}
}
There is a JToolbarButton in Apache Batik.
It seems to me though that what you are looking for is a JToggleButton. You can adjust it to display a small image and to be small.
jToggleButton1.setIcon(new javax.swing.ImageIcon("image.png"));
jToggleButton1.setSelectedIcon(new javax.swing.ImageIcon("selected_image.png"));
Add another image with setSelectedIcon in order to make you button look pressed.
Related
I have a problem with my pause screen. I made a simple Splash screen, followed by the main menu, where you can start or end the game, followed by a random picture. If the user presses Esc it switches to the pause screen, which is very similar to the main menu. Only difference is that it doesn't generate a new picture if the user clicks on "Continue", instead it just renders the game screen again. But if I press Esc after continuing again, the pause menu appears lower on the screen than it should. If I repeat pressing Continue and then Escape, the buttons eventually moved out of the displayed screen. I didn't find a solution yet, so I made an account here, since this site helped me a lot so far.
Furthermore I want to know if there are things I could improve. I just started with libGDX, so there probably are a lot of things I could've done better, and I want to know that. SO if you have a few improvements, I would be glad to read them :)!
This is the code:
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
public class GameScreen implements Screen{
private Texture[] monsterTextures = {new Texture(Gdx.files.internal("Ressources/DemonHunter.jpg")), new Texture(Gdx.files.internal("Ressources/WingedDemon.jpg")),
new Texture(Gdx.files.internal("Ressources/Viking.jpg")), new Texture(Gdx.files.internal("Ressources/DemonWarrior.jpg"))};
private Image[] monsterImages = {new Image(monsterTextures[0]), new Image(monsterTextures[1]), new Image(monsterTextures[2]), new Image(monsterTextures[3])};
private Stage gameStage = new Stage(), pauseStage = new Stage();
private Table table = new Table();
private Skin menuSkin = new Skin(Gdx.files.internal("skins/menuSkin.json"),
new TextureAtlas(Gdx.files.internal("skins/menuSkin.pack")));
private TextButton buttonContinue = new TextButton("Continue", menuSkin),
buttonExit = new TextButton("Exit", menuSkin);
private Label title = new Label ("Game", menuSkin);
private int randomMonster;
public static final int GAME_RUNNING = 0;
public static final int GAME_PAUSING = 1;
public static final int GAME_PAUSED = 2;
private int gamestatus = 0;
#Override
public void show() {
randomMonster = 0 + (int)(Math.random() * ((3-0) + 1));
gameStage.addActor(monsterImages[randomMonster]);
}
#Override
public void render(float delta) {
if(Gdx.input.isKeyJustPressed(Keys.ESCAPE)) pauseGame();
if(gamestatus == GAME_RUNNING) {
Gdx.gl.glClearColor(0,0,0,1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
gameStage.act();
gameStage.draw();
}
if(gamestatus == GAME_PAUSING) {
buttonContinue.addListener(new ClickListener(){
public void clicked(InputEvent event, float x, float y) {
Gdx.gl.glClearColor(0,0,0,1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
gamestatus = GAME_RUNNING;
}
});
buttonExit.addListener(new ClickListener(){
public void clicked(InputEvent event, float x, float y) {
Gdx.app.exit();
}
});
table.add(title).padBottom(40).row();
table.add(buttonContinue).size(150, 60).padBottom(20).row();
table.add(buttonExit).size(150, 60).padBottom(20).row();
table.setFillParent(true);
pauseStage.addActor(table);
Gdx.input.setInputProcessor(pauseStage);
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
pauseStage.act();
pauseStage.draw();
gamestatus = GAME_PAUSED;
}
if(gamestatus == GAME_PAUSED) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
pauseStage.act();
pauseStage.draw();
}
}
public void pauseGame() {
gamestatus = GAME_PAUSING;
}
#Override
public void resize(int width, int height) {
// TODO Auto-generated method stub
}
#Override
public void pause() {
pauseGame();
}
#Override
public void resume() {
// TODO Auto-generated method stub
}
#Override
public void hide() {
// TODO Auto-generated method stub
}
#Override
public void dispose() {
for(int i = 0; i < monsterTextures.length; i++) {
monsterTextures[i].dispose();
}
gameStage.dispose();
pauseStage.dispose();
menuSkin.dispose();
}
}
Thanks, Joshflux
I think your render() method is doing things it shouldn't. Like creating the clickListener and also adding buttons to the table (and possibly some other items in there).
The render method gets called every "frame". You don't want to be recreating this, say 60 times a second. You want to do it once (like when you create the particular screen) and then just draw (render) it every frame.
Restructure your code to do the "Creation" stuff once. The render() method should just draw it. I think you continually adding items to your table each frame may be what is causing the buttons to move off the screen.
I'm making a Hangman game and it seems that my code doesn't provide me much freedom with using layouts. I added an image to my JFrame then I added a JPanel to my image which I'm using for all the JLabels and JTextFields but it seems to me that its inefficient because in order to change the layout of my JTextFields or JLabels I have to change the layout of my image which messes up the entire looks of the game. How can I make this code more efficient and give myself more freedom to change the layouts of my JLabels and JTextFields without messing everything up? Thanks for the help in advanced.
/*PACKAGE DECLARATION*/
package Game;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
/************************
* GAME MECHANICS CLASS *
* **********************/
public class GameStructure {
/* INSTANCE DECLARATIONS */
private String []wordList = {"computer","java","activity","alaska","appearance","article",
"automobile","basket","birthday","canada","central","character","chicken","chosen",
"cutting","daily","darkness","diagram","disappear","driving","effort","establish","exact",
"establishment","fifteen","football","foreign","frequently","frighten","function","gradually",
"hurried","identity","importance","impossible","invented","italian","journey","lincoln",
"london","massage","minerals","outer","paint","particles","personal","physical","progress",
"quarter","recognise","replace","rhythm","situation","slightly","steady","stepped",
"strike","successful","sudden","terrible","traffic","unusual","volume","yesterday"};
private int []length = new int [64];
private JTextField tf;//text field instance variable (used)
private JLabel jl2;//label instance variable (used)
private JLabel jl3;//label instance (working on)
private String letter;
/*****************
* LENGTH METHOD *
* ***************/
public void length(){
jl3 = new JLabel();
int j = 0;
for(j = 0; j<64; j++) {
length[j] = wordList[j].length();//gets length of words in wordList
}//end for
int l = 0;
String line = "";
//create line first then put into .setText
for(int m = 0; m<length[l]; m++) {
line += "__ ";
l++;
}//end for
jl3.setText(line);
}//end length method
/*****************
* WINDOW METHOD *
* ***************/
public void window() {
LoadImageApp i = new LoadImageApp();//calling image class
JFrame gameFrame = new JFrame();//declaration
JPanel jp = new JPanel();
//JPanel jp2 = new JPanel();//jpanel for blanks
JLabel jl = new JLabel("Enter a Letter:");//prompt with label
jl.setFont(new Font("Rockwell", Font.PLAIN, 20));//set font
tf = new JTextField(1);//length of text field by character
jl2 = new JLabel("Letters Used: ");
tf.setFont(new Font("Rockwell", Font.PLAIN, 20));//set font
jl2.setFont(new Font("Rockwell", Font.PLAIN, 20));//set font
jp.add(jl);//add label to panel
jp.add(tf);//add text field to panel
jp.add(jl2);//add letters used
gameFrame.add(i); //adds background image to window
i.add(jp); // adds panel containing label to background image panel
gameFrame.setTitle("Hangman");//title of frame window
gameFrame.setSize(850, 600);//sets size of frame
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//exit when 'x' button pressed
gameFrame.setIconImage(new ImageIcon("Hangman-Game-grey.png").getImage());//set the frame icon to an image loaded from a file
gameFrame.setLocationRelativeTo(null);//window centered
gameFrame.setResizable(false);//user can not resize window
gameFrame.setVisible(true);//display frame
}//end window method
/*********************
* USER INPUT METHOD *
* *******************/
public void userInput() {
tf.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {//when enter key pressed
JTextField tf = (JTextField)e.getSource();
letter = tf.getText();
jl2.setText(jl2.getText() + letter + " ");//sets jlabel text to users entered letter
}//end actionPerformed method
});
}//end userInput method
}//end GameMechanics class
/*PACKAGE DECLARATION*/
package Game;
/***********************
* IMPORT DECLARATIONS *
* *********************/
import java.awt.BorderLayout;
import java.awt.Graphics;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
/***************
* IMAGE CLASS *
* *************/
public class LoadImageApp extends JPanel {
private static final long serialVersionUID = 1L;
private ImageIcon image;
/***********************
* PAINT IMAGE METHOD *
* *********************/
public void paintComponent (Graphics g) {
//setLayout(new BorderLayout());
super.paintComponent(g);
image = new ImageIcon("hangman.png");//image name & type
image.paintIcon(this, g, 270, 20);
}//end paintComponent method
}//end LoadImageApp class
/*PACKAGE DECLARATION*/
package Game;
/*******************
* GAME MAIN CLASS *
* *****************/
public class GameMain {
/***************
* MAIN METHOD *
* *************/
public static void main (String []args) {
GameStructure game = new GameStructure();//declaration
game.length();
game.window();
game.userInput();
}//end main method
}//end GameMain class
Some suggestions:
Don't override a JPanel's paint(...) method, but rather its paintComponent(Graphics g) method, not unless you need to change how it renders its child components or its borders (you don't). Also by doing this you gain some Swing graphics advantages including automatic double buffering.
Never read in an image into the paint or paintComponent method. These methods are one of the main determinants of how responsive your GUI appears to the user, and so you never want to do file I/O in the method. And also, why have code that inefficiently re-reads the same image in whenever paint or paintComponent is called? Why not simply store the image or ImageIcon in a variable once, and be done with it?
Learn and use the layout managers
JPanels that go over drawing or image rendering JPanels often should be non-opaque - so be sure to call setOpaque(false) on them, and also on some other overlying Swing components.
_________________________
Edit
For example, here is my SSCCE that shows an example of getting an image (here off of the internet) in a class constructor. Also note that my SSCCE will work on any computer connected to the internet since it does not require image files, unlike yours. Also code not related to displaying the GUI has been cut out making the remaining code more pertinent to the problem. Consider doing this next time you post an SSCCE.
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
class GameStructure {
private JTextField tf;
private JLabel jl2;
public void window() {
LoadImageApp loadImageApp = new LoadImageApp();
JFrame gameFrame = new JFrame();
JPanel jp = new JPanel();
jp.setOpaque(false); //!!
jp.setBorder(BorderFactory.createTitledBorder("jp"));
JLabel jl = new JLabel("Enter a Letter:");
jl.setFont(new Font("Rockwell", Font.PLAIN, 20));
tf = new JTextField(1);
jl2 = new JLabel("Letters Used: ");
tf.setFont(new Font("Rockwell", Font.PLAIN, 20));
jl2.setFont(new Font("Rockwell", Font.PLAIN, 20));
jp.add(jl);
jp.add(tf);
jp.add(jl2);
gameFrame.add(loadImageApp);
loadImageApp.add(jp);
gameFrame.setTitle("Hangman");
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// gameFrame.setIconImage(
// new ImageIcon("Hangman-Game-grey.png").getImage());
gameFrame.setResizable(false);
gameFrame.pack();
gameFrame.setLocationRelativeTo(null);
gameFrame.setVisible(true);
}
}
class LoadImageApp extends JPanel {
private static final long serialVersionUID = 1L;
private static final int PREF_W = 850;
private static final int PREF_H = 600;
private BufferedImage img;
public LoadImageApp() {
// just used as an example public image
String spec = "https://duke.kenai.com/"
+ "SunRIP/.Midsize/SunRIP.png.png";
URL url;
try {
url = new URL(spec);
img = ImageIO.read(url);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (img != null) {
g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
}
}
}
public class GameMain {
public static void main(String[] args) {
GameStructure game = new GameStructure();
game.window();
}
}
I wonder if there is a way to change to source code format automatically produced
by Net Beans IDE in GUI - applet applications. For example placement of the items in the source code are relational but what if I want them in absolute coordinates. I am asking this question because I need source code in that format so that I can easily change source code and can do some manual job. More specially, I want to create a Button Group of 12x8 array with no gap between them . But using IDE to do this takes long time and indeed, I couldn't even placed the buttons with no gap between them. Any help highly appreciated!
This is simple to put together manually. GUI builders usually harm more than they help.
Here's the test run:
And here's the code. I put the classes together in one file to make it easier to paste. The classes should be in separate files.
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class ButtonArray implements Runnable {
#Override
public void run() {
JFrame frame = new JFrame("JButton Array Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ButtonPanel buttonPanel = new ButtonPanel();
frame.add(buttonPanel.getMainPanel());
frame.setLocationByPlatform(true);
// frame.setSize(new Dimension(800, 600));
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new ButtonArray());
}
public class ButtonPanel {
private static final int WIDTH = 12;
private static final int HEIGHT = 8;
private JButton[][] buttonArray;
private JPanel mainPanel;
public ButtonPanel() {
buttonArray = new JButton[WIDTH][HEIGHT];
createPartControl();
}
private void createPartControl() {
mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout(HEIGHT, WIDTH));
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
buttonArray[j][i] =
new JButton(createButtonText(j, i));
mainPanel.add(buttonArray[j][i]);
}
}
}
private String createButtonText(int j, int i) {
StringBuilder builder = new StringBuilder();
builder.append("(");
builder.append(i);
builder.append(", ");
builder.append(j);
builder.append(")");
return builder.toString();
}
public JPanel getMainPanel() {
return mainPanel;
}
}
}
You need to use some grid like layout for the panel (ex. FormLayout) configure it and simply add all buttons there.
I have to load a small icon on the botton of my software. just to have a loading/ok/error icon. as sudgested on "http://www.particle.kth.se/~lindsey/JavaCourse/Book/Part1/Java/Chapter06/images.html" i create a dwowing panel extending JPanel.
class drawingPanel extends JPanel
{
Image img;
drawingPanel (Image img){
this.img = img;
}
public void paintComponent (Graphics g) {
super.paintComponent (g);
// Use the image width & height to find the starting point
int imgX = getSize ().width/2 - img.getWidth (this);
int imgY = getSize ().height/2 - img.getHeight (this);
//Draw image centered in the middle of the panel
g.drawImage (img, imgX, imgY, this);
} // paintComponent
}
I initialize the component in the following way:
// Grab the image.
Image img = new ImageIcon(iconPath+"ok.png").getImage();
// Create an instance of DrawingPanel
iconPanel = new drawingPanel(img);
all works well but at runtime i want to be able to change the icon within the pannel. i tryed all the fo;llowing but none managed to view the new picture:
Image img = new ImageIcon(iconPath+"loading.gif").getImage();
// Create a new instance of DrawingPanel
this.iconPanel = new drawingPanel(img);
this.iconPanel.repaint();
this.iconPanel.revalidate();
this.iconPanel.repaint();
this.repaint();
this.revalidate();
(i tryed this because the class in whic i am writing the code is another extension of JPanel that contains IconPanel. Any idea about why i do not manage to change the picture?
Thanks,
Stefano
First thing don't start class name with small name. Rename drawingPanel to DrawingPanel.
I have tried making a simple demo based on your description and it works fine. The image in panel is changing perfectly.
public class Demo {
public Demo() {
JFrame frame = new JFrame();
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
// Grab the image.
Image img = new ImageIcon("1.png").getImage();
// Create an instance of DrawingPanel
final DrawingPanel iconPanel = new DrawingPanel(img);
frame.add(iconPanel, BorderLayout.CENTER);
JButton button = new JButton("Change image..");
frame.add(button, BorderLayout.NORTH);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
iconPanel.setImg(new ImageIcon("2.png").getImage());
iconPanel.repaint();
}
});
frame.setVisible(true);
}
public static void main(String[] args){
new Demo();
}
}
class DrawingPanel extends JPanel {
Image img;
DrawingPanel(Image img) {
this.img = img;
}
public void setImg(Image img) {
this.img = img;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Use the image width & height to find the starting point
int imgX = getSize().width / 2 - img.getWidth(this);
int imgY = getSize().height / 2 - img.getHeight(this);
// Draw image centered in the middle of the panel
g.drawImage(img, imgX, imgY, this);
} // paintComponent
}
The changes I have made is add a setter method of img in DrawingPanel class. So instead of creating new DrawingPanel you just have to call setImg() with new Image and then call reapint to paint the new image.
I'm fairly new to Java Swing/AWT et al and hence the question. I have a simple dialog with some text and a couple JButton. I am using the GridbagLayout for this dialog.
But when I look at the dialog, the JButtons are kind of having a weird shape and I cannot seem to right justify the text either.
Is this a limitation of the Layout I am using. Is there much simpler and elegant solution for my problem with either the buttons or the textlayout?
A screenshot of the dialog is attached below.
The code for my dialog Class is:
public class UpgradePopupWindow extends JPanel implements ActionListener {
static final long serialVersionUID = 0;
final String upgrade = " Continue Upgrade ";
final String restore = "Restore Previous Version";
JPanel panels;
JButton upgradeButton;
JButton restoreButton;
JTextArea Message;
JFrame newFrame;
FlasherThread flash;
protected JTextArea addText(String text, boolean visible, int fontStyle) {
JTextArea textArea = new JTextArea(text);
textArea.setFont(new Font("SansSerif", fontStyle, 12)); //$NON-NLS-1$
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setEditable(false);
textArea.setBackground(Color.DARK_GRAY);
textArea.setForeground(Color.WHITE);
textArea.setOpaque(false);
textArea.setVisible(visible);
textArea.setAlignmentX(Component.CENTER_ALIGNMENT);
add(textArea);
return textArea;
}
protected JTextArea addMultiLineLabel(String text, int fontStyle, int fontSize, Object constraints) {
JTextArea textArea = new JTextArea(text);
textArea.setFont(new Font("SansSerif", fontStyle, fontSize));
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setEditable(false);
textArea.setBackground(new Color(0, 0, 0, 0)); // Zero alpha = transparent background
textArea.setOpaque(false);
textArea.setBorder(new TitledBorder(""));
textArea.setAlignmentX(Component.CENTER_ALIGNMENT);
add(textArea, constraints);
return textArea;
}
private UpgradePopupWindow(JFrame frame, Object ft) {
super(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
flash = (FlasherThread)ft;
String text = "An error occurred during the attempt to update your device's software. We recommend the following: (1) Restore your device to its previous version, (2) back up important data, and then (3) try updating your device again. If you continue with the current update, only your previously backed-up data will be available.";
//addFiller(5);
//addLabel(text, Font.PLAIN, 12);
gbc.gridy = 0;
gbc.gridx = 0;
gbc.gridwidth = 2;
gbc.weightx = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
addMultiLineLabel(text, Font.PLAIN, 12, gbc);
//addText(text, true, Font.PLAIN);
addFiller(20);
newFrame = frame;
gbc.gridy = 1;
gbc.gridwidth = 1;
gbc.fill = GridBagConstraints.NONE;
upgradeButton = new JButton(upgrade);
upgradeButton.setActionCommand("upgrade");
upgradeButton.addActionListener(this);
upgradeButton.setEnabled(true);
upgradeButton.setBackground(Color.WHITE);
upgradeButton.setForeground(Color.GRAY);
add(upgradeButton,gbc);
++ gbc.gridx;
restoreButton = new JButton(restore);
restoreButton.setActionCommand("restore");
restoreButton.addActionListener(this);
restoreButton.setEnabled(true);
//restoreButton.setForeground(Color.DARK_GRAY);
restoreButton.setBackground(Color.DARK_GRAY);
add(restoreButton,gbc);
setOpaque(true);
newFrame.setContentPane(this);
//newFrame.getContentPane().setBackground(Color.LIGHT_GRAY);
}
protected void addFiller(int size) {
Dimension diminsion = new Dimension(size, size);
Filler filler = new Filler(diminsion, diminsion, diminsion);
filler.setAlignmentX(Component.CENTER_ALIGNMENT);
add(filler);
}
public static void createGUI(Object obj) {
//Create and set up the frame.
JFrame frame = new JFrame("PopUp Dialog");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(440, 180));
//create and setup the content pane
UpgradePopupWindow popUpContentPane = new UpgradePopupWindow(frame, obj);
popUpContentPane.setOpaque(true);
frame.setContentPane(popUpContentPane);
frame.pack();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if("restore".equals(e.getActionCommand())) {
System.out.println("restore button selected");
flash.setUpgradeRestoreChoice("restore");
newFrame.dispose();
} else if ("upgrade".equals(e.getActionCommand())) {
System.out.println("upgrade button selected");
flash.setUpgradeRestoreChoice("upgrade");
newFrame.dispose();
}
}
}
![alt text][1]
As #Javaguru said - use MigLayout. For the text DO NOT use JTextArea. This component is mostly for text editing. JLabel is enough for your purpose - you can even use HTML inside of it.
You don't have to create this kind of dialog from scratch. There are many options. One of them is my Swing TaskDialog framework ;)
But if you still insist on implementing it yourself here a simple implementation using MigLayout ( even with MigLayout it can be done using several differnt ways):
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import net.miginfocom.swing.MigLayout;
public class TestDialog extends JDialog {
private static final long serialVersionUID = 1L;
private final JLabel label = new JLabel("Your text here");
private final JButton restoreButton = new JButton("Restore Previous Version");
private final JButton ugradeButton = new JButton("Continue Upgrade");
public TestDialog( String title ) {
super( (JDialog)null, title );
setContentPane(createContent());
}
private JPanel createContent() {
JPanel content = new JPanel();
content.setPreferredSize( new Dimension(400, 100));
content.setBackground(Color.WHITE);
content.setLayout(new MigLayout("", "[400px,grow][pref!]", "[grow][pref!]"));
this.label.setVerticalAlignment(SwingConstants.TOP);
content.add(this.label, "cell 0 0 2 1,grow");
content.add(this.restoreButton, "cell 1 1,alignx left,aligny top");
content.add(this.ugradeButton, "cell 0 1,alignx right,aligny top");
return content;
}
// very simplified test
public static void main(String[] args) {
TestDialog dlg = new TestDialog("Popup Dialog");
dlg.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dlg.pack();
dlg.setLocationRelativeTo(null);
dlg.setVisible(true);
}
}
There are a lot of much more elegant solutions out there .. ;)
You should really never use GridbagLayout if not absolutely required (or only with a gui editor)! It's simply a pain in the ass!
Rather I suggest using one of the following LayoutManagers:
MigLayout: http://www.miglayout.com/
TableLayout: https://tablelayout.dev.java.net/
Creating a pleasing layout is much simpler and intuitive than with the GridbagLayout and its configuration overhead.