Absolute Positioning a JButton - java

I am trying to position a JButton with a null layout but it will not show up, if i switch to gridlayout they are only lined up in the middle no matter what i change. How can i set the position and size of my button?
In Frame
package Run;
import javax.swing.*;
import ThreeD.Display;
import ThreeD.Launcher;
import TowerDefence.Window;
import java.awt.*;
import java.awt.image.BufferedImage;
public class Frame extends JFrame{
public static String title = "Game";
/*public static int GetScreenWorkingWidth() {
return java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().width;
}*/
/*public static int GetScreenWorkingHeight() {
return java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().height;
}*/
//public static Dimension size = new Dimension(GetScreenWorkingWidth(), GetScreenWorkingHeight());
public static Dimension size = new Dimension(1280, 774);
public static void main(String args[]) {
Frame frame = new Frame();
System.out.println("Width of the Frame Size is "+size.width+" pixels");
System.out.println("Height of the Frame Size is "+size.height+" pixels");
}
public Frame() {
setTitle(title);
setSize(size);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ThreeDLauncher();
}
public void ThreeDLauncher() {
//setLayout(new GridLayout(1, 1, 0, 0));
setLayout(null);
Launcher launcher = new Launcher();
add(launcher);
setVisible(true);
}
public void TowerDefence() {
setLayout(new GridLayout(1, 1, 0, 0));
Window window = new Window(this);
add(window);
setVisible(true);
}
public void ThreeD() {
BufferedImage cursor = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
Cursor blank = Toolkit.getDefaultToolkit().createCustomCursor(cursor, new Point(0, 0), "blank");
getContentPane().setCursor(blank);
Display display = new Display();
add(display);
setVisible(true);
display.start();
}
}
In Launcher
package ThreeD;
import java.awt.Rectangle;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.UIManager;
public class Launcher extends JPanel{
private JButton play, options, help, mainMenu;
private Rectangle rplay, roptions, rhelp, rmainMenu;
public Launcher() {
drawButtons();
}
private void drawButtons() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(Exception e) {
e.printStackTrace();
}
play = new JButton("Play");
options = new JButton("Options");
help = new JButton("Help");
mainMenu = new JButton("Main Menu");
rplay = new Rectangle(20, 50, 80, 40);
roptions = new Rectangle(20, 50, 80, 40);
rhelp = new Rectangle(20, 50, 80, 40);
rmainMenu = new Rectangle(20, 50, 80, 40);
play.setBounds(rplay);
options.setBounds(roptions);
help.setBounds(rhelp);
mainMenu.setBounds(rmainMenu);
add(play);
add(options);
add(help);
add(mainMenu);
}
}

Child containers do not inherit their parent's LayoutManager, so in the constructor of Launcher I would recommend:
public Launcher() {
this.setLayout(null);
//this.setLayout(new GroupLayout(2, 2)); // I strongly recommend you try this though and get rid of the setBounds and rects
drawButtons();
}
Edit: LayoutManagers layout their components, but not what is inside a component. That's why it isn't enough to just set the frame's layout.

My guess is you are not setting the size or layout before adding the JPanel Launcher. So the buttons are displaying fine, but the JPanel is not. Try putting in:
launcher.setBounds( new Rectangle( 0, 0, 200, 200 ) );
or what ever size you need.
See if that works

Related

How can I make flush JButtons in swing?

I am doing a layout, and I have a pair of buttons that I would like to be flush together. I can think of a couple ways to accomplish this, but I am wondering if there is a good way.
Here is some template code:
package helloworld;
import javax.swing.BoxLayout;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.EventQueue;
/**
* Created by matt on 22/07/16.
*/
public class FlushButtons {
private void showGui(){
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JButton plus = new JButton("+");
JButton minus = new JButton("-");
panel.setLayout(new BoxLayout(panel, BoxLayout.LINE_AXIS));
panel.add(plus);
panel.add(minus);
frame.setContentPane(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args){
EventQueue.invokeLater(()->{
new FlushButtons().showGui();
});
}
}
That produces the image on the left, but I would like it to look more like the image on the right.
I tried using JButton#setMargin, but that did not have any effect. I have used JButton#setPreferredSize which I can get the desired result, but I need to know the size of the button beforehand.
Here's my solution which looks ..pretty neat!
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class FlushButtons {
private JComponent ui = null;
FlushButtons() {
initUI();
}
private JButton getFlushButton(String text) {
JButton b = new JButton();
b.setBorderPainted(false);
b.setContentAreaFilled(false);
b.setMargin(new Insets(0,0,0,0));
b.setBorder(null);
b.setIcon(new ImageIcon(getImageOfText(text, Color.GREEN.darker())));
b.setRolloverIcon(new ImageIcon(getImageOfText(text, Color.ORANGE)));
b.setPressedIcon(new ImageIcon(getImageOfText(text, Color.RED)));
return b;
}
private BufferedImage getImageOfText(String text, Color color) {
int s = 24;
BufferedImage bi = new BufferedImage(s, s, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi.createGraphics();
g.setColor(color);
g.fillRect(0, 0, s, s);
g.setColor(Color.BLACK);
g.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 16));
// use better ways to position text..
g.drawString(text, 8, 16);
g.dispose();
return bi;
}
public void initUI() {
if (ui!=null) return;
ui = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
ui.setBorder(new EmptyBorder(4,4,4,4));
ui.add(getFlushButton("+"));
ui.add(getFlushButton("-"));
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
FlushButtons o = new FlushButtons();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
Here is my solution, which looks a bit ridiculous.
JPanel panel = new JPanel();
JButton plus = new JButton("+");
JButton minus = new JButton("-");
plus.setPreferredSize(new Dimension(29, 29));
plus.setMaximumSize(new Dimension(33, 33));
minus.setPreferredSize(new Dimension(29, 29));
minus.setMaximumSize(new Dimension(33, 33));
panel.setLayout(new BoxLayout(panel, BoxLayout.LINE_AXIS));
panel.add(plus);
panel.add(minus);
panel.add(Box.createVerticalStrut(33));
panel.add(Box.createHorizontalGlue());
Without the vertical strut the buttons get packed without borders.
Something of a hack, hope to hear something better.

How do you limit a component to be in a certain spot

I'm creating a slideshow using swing and trying to place it in the center of my JFrame. The slideshow works fine, but it's taking up the entire center section. How would I limit it to a small place under the banner?
Here's a picture of what it looks like.
Here's a picture of what I want it to look like
This is what I have so far, you run this class.
package com.RBV2.engine;
import javax.swing.*;
import com.RBV2.Settings;
import com.RBV2.panels.News;
import com.RBV2.panels.SlideShow;
import com.RBV2.panels.SlideShow.MovingPanel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.io.*;
/*
* Author Jon & David
*
*/
#SuppressWarnings("serial")
public class Client extends JFrame implements ActionListener {
private JPanel bottomPanel, news;
private JButton launch;
private JLabel loading, banner;
private MovingPanel slideshow;
protected boolean updated = false;
private void createLayout() {
createPanel();
addPanel();
setVisible(true);
}
private void createPanel() {
bottomPanel = new JPanel(new BorderLayout());
news = new News();
slideshow = new SlideShow.MovingPanel();
launch = new JButton(new URL("http://www.runerebellion.com/clientImages/launch.png"));
loading = new JLabel(new URL("http://www.runerebellion.com/clientImages/loader.gif"));
banner = new JLabel(new URL("http://www.runerebellion.com/clientImages/201457.gif"));
launch.addActionListener(this);
}
private void addPanel() {
setTitle("RuneRebellionV2 Launcher");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
//Bottom Panel
add(bottomPanel, BorderLayout.SOUTH);
bottomPanel.add(new JLabel(" Launcher, release " + Settings.version), BorderLayout.WEST);
bottomPanel.setBackground(Color.BLACK);
bottomPanel.add(launch, BorderLayout.EAST);
launch.setPreferredSize(new Dimension(120, 40));
//News Feed
add(news, BorderLayout.CENTER);
news.add(banner, BorderLayout.CENTER);
banner.setPreferredSize(new Dimension(500, 70));
//slideshow
slideshow.setPreferredSize(new Dimension(610, 331));
add(slideshow, BorderLayout.CENTER);
//Sets size
setSize(Settings.width, Settings.height);
}
public Client() throws IOException {
createLayout();
}
public static void main(String args[]) throws IOException {
final Client l = new Client();
l.setVisible(true);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
l.setVisible(true);
}
});
}
These specific lines of code call the slideshow(I commented out exactly where)
private void addPanel() {
setTitle("RuneRebellionV2 Launcher");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
//Bottom Panel
add(bottomPanel, BorderLayout.SOUTH);
bottomPanel.add(new JLabel(" Launcher, release " + Settings.version), BorderLayout.WEST);
bottomPanel.setBackground(Color.BLACK);
bottomPanel.add(launch, BorderLayout.EAST);
launch.setPreferredSize(new Dimension(120, 40));
//News Feed
add(news, BorderLayout.CENTER);
news.add(banner, BorderLayout.CENTER);
banner.setPreferredSize(new Dimension(500, 70));
//slideshow here
slideshow.setPreferredSize(new Dimension(610, 331));
add(slideshow, BorderLayout.CENTER);
//Sets size
setSize(Settings.width, Settings.height);
}
Here is my slideshow class, you may need this also.
package com.RBV2.panels;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class SlideShow extends JFrame {
public static class MovingPanel extends JPanel {
public int i = 0;
public MovingPanel() {
Timer timer = new Timer(3000, new TimerListener());
timer.start();
}
protected void paintComponent(Graphics x) {
super.paintComponent(x);
int y = i % 25;
Image showImg = new ImageIcon("bin/slide/" + y + ".png").getImage();
x.drawImage(showImg, 0, 0, getWidth(), getHeight(), 0, 0, 610, 331, null);
}
class TimerListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
i++;
repaint();
if (i >= 5)
i = 1;
}
}
}
}
So my question is how would I limit the slideshow to be in a box in the very center under the banner.
Have a look at this picture (from Border layout Tutorial)
As you are only adding panels to the Center and South(PAGE_END) regions of the layout manager there is no other components to stop the center panel from stretching out as far as it can.
Note this relevant sentence of the tutorial
If the window is enlarged, the center area gets as much of the available space as possible. The other areas expand only as much as necessary to fill all available space. Often a container uses only one or two of the areas of the BorderLayout object — just the center, or the center and the bottom.
You either need to add blank panels on the other sides or make use of an empty border within your Center panel. See here about how to use borders.
I painted the background, then painted the images over the background
protected void paintComponent(Graphics x) {
super.paintComponent(x);
int y = i % 25;
Image showImg = new ImageIcon("bin/slide/" + y + ".png").getImage();
super.paintComponent(x);
x.drawImage((Settings.background).getImage(), 0, 0, getWidth(), getHeight(), this);
x.drawImage(showImg, 360, 260, getWidth(), getHeight(), 0, 0, 110, 31, null);
}

Place image at random grid point on button click

I'm using Java with Window builder
I've created a 4x4 grid out of jlabels (each grid point is a different jlabel) on my jframe.
I also have a button called btnPlace.
What I want to do is have an image appear at a random grid point on button click. The image file is called red.png which is a red circle. The image can appear at any grid point except the grid point number 1.
Sort of like this: http://i.stack.imgur.com/bBn6D.png
Here's my code:
public class grid {
public static void main (String[] args)
{
JFrame grid =new JFrame();
grid.setDefaultCloseOperation
(JFrame.EXIT_ON_CLOSE);
JPanel set = new JPanel();
set.setBounds(10, 11, 307, 287);
grid.getContentPane().add(set);
set.setLayout(new GridLayout(4, 4, 0, 0));
JLabel a = new JLabel("");
set.add(a);
JLabel b = new JLabel("");
set.add(b);
JLabel c = new JLabel("");
set.add(c);
^^ this repeats up to JLabel p. just to save time.
JButton btnPlace = new JButton("Place");
grid.getContentPane().add(btnPlace);
grid.setVisible(true);
} }
Here is fully working example:
On pressing button it'll draw Image on randomly selected JLabel
package stackoverflow;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class DummyColor {
private JFrame frame;
private JLabel[] labels = new JLabel[4];
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DummyColor window = new DummyColor();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public DummyColor() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setResizable(false);
frame.setBounds(100, 100, 657, 527);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lbl1 = new JLabel("First BOX");
lbl1.setBounds(10, 11, 273, 194);
frame.getContentPane().add(lbl1);
JLabel label = new JLabel("Second BOX");
label.setBounds(336, 11, 273, 194);
frame.getContentPane().add(label);
JLabel label_1 = new JLabel("Third BOX");
label_1.setBounds(10, 251, 273, 194);
frame.getContentPane().add(label_1);
JLabel label_2 = new JLabel("Fourth BOX");
label_2.setBounds(347, 251, 273, 194);
frame.getContentPane().add(label_2);
labels[0] = lbl1;
labels[1] = label;
labels[2] = label_1;
labels[3] = label_2;
JButton btnPick = new JButton("Place");
btnPick.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ImageIcon imageIcon = new ImageIcon(DummyColor.class.getResource("/red.jpg"));
int randInt = randInt(1, 4);
System.out.println(randInt);
for (int i = 0; i < labels.length; i++) {
JLabel jLabel = labels[i];
if (i == randInt - 1) {
jLabel.setIcon(imageIcon);
} else {
jLabel.setIcon(null);
}
}
}
});
btnPick.setBounds(10, 439, 57, 23);
frame.getContentPane().add(btnPick);
}
private static int randInt(int min, int max) {
// Usually this can be a field rather than a method variable
Random rand = new Random();
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
}
I would create a custom JPanel and add a MouseListener. Whenever the Panel is clicked, an image will be draw at that point clicked on the panel
public class grid{
public static void main(String[] args){
JFrame frame = new JFrame();
frame.add(new MyPanel());
}
}
class MyPanel extends JPanel{
Point p;
BufferedImage img;
addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
p = e.getLocationOnScreen();
repaint();
}
});
#Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
try{
img = ImageIO.read("someImage.png");
}catch(Exception e){e.printStackTrace();}
g.drawImage(img, p.getX(), p.getY(), width, height, this);
}
}

JPanel Inside Of A JPanel

I am trying to get a JPanel to appear inside of another JPanel. Currently, the JPanel is in an external JFrame and loads with my other JFrame. I want the JPanel to be inside the other JPanel so the program does not open two different windows.
Here is a picture:
The small JPanel with the text logs I want inside of the main game frame. I've tried adding the panel to the panel, panel.add(othePanel). I've tried adding it the JFrame, frame.add(otherPanel). It just overwrites everything else and gives it a black background.
How can I add the panel, resize, and move it?
Edits:
That is where I want the chatbox to be.
Class code:
Left out top of class.
public static JPanel panel;
public static JTextArea textArea = new JTextArea(5, 30);
public static JTextField userInputField = new JTextField(30);
public static void write(String message) {
Chatbox.textArea.append("[Game]: " + message + "\n");
Chatbox.textArea.setCaretPosition(Chatbox.textArea.getDocument()
.getLength());
Chatbox.userInputField.setText("");
}
public Chatbox() {
panel = new JPanel();
panel.setPreferredSize(new Dimension(220, 40));
panel.setBackground(Color.BLACK);
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setPreferredSize(new Dimension(380, 100));
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setEditable(false);
scrollPane
.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
userInputField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
String fromUser = userInputField.getText();
if (fromUser != null) {
textArea.append(Frame.username + ":" + fromUser + "\n");
textArea.setCaretPosition(textArea.getDocument()
.getLength());
userInputField.setText("");
}
}
});
panel.add(userInputField, SwingConstants.CENTER);
panel.add(scrollPane, SwingConstants.CENTER);
//JFrame frame = new JFrame();
//frame.add(panel);
//frame.setSize(400, 170);
//frame.setVisible(true);
}
Main frame class:
public Frame() {
frame.getContentPane().remove(loginPanel);
frame.repaint();
String capName = capitalizeString(Frame.username);
name = new JLabel(capName);
new EnemyHealth("enemyhealth10.png");
new Health("health10.png");
new LoadRedCharacter("goingdown.gif");
new Spellbook();
new LoadMobs();
new LoadItems();
new Background();
new Inventory();
new ChatboxInterface();
frame.setBackground(Color.black);
Frame.redHealthLabel.setFont(new Font("Serif", Font.PLAIN, 20));
ticks.setFont(new Font("Serif", Font.PLAIN, 20));
ticks.setForeground(Color.yellow);
Frame.redHealthLabel.setForeground(Color.black);
// Inventory slots
panel.add(slot1);
panel.add(name);
name.setFont(new Font("Serif", Font.PLAIN, 20));
name.setForeground(Color.white);
panel.add(enemyHealthLabel);
panel.add(redHealthLabel);
panel.add(fireSpellBookLabel);
panel.add(iceSpellBookLabel);
panel.add(spiderLabel);
panel.add(appleLabel);
panel.add(fireMagicLabel);
panel.add(swordLabel);
// Character
panel.add(redCharacterLabel);
// Interface
panel.add(inventoryLabel);
panel.add(chatboxLabel);
// Background
panel.add(backgroundLabel);
frame.setContentPane(panel);
frame.getContentPane().invalidate();
frame.getContentPane().validate();
frame.getContentPane().repaint();
//I WOULD LIKE THE LOADING OF THE PANEL SOMEWHERE IN THIS CONSTRUCTOR.
new ResetEntities();
frame.repaint();
panel.setLayout(null);
Run.loadKeyListener();
Player.px = Connect.x;
Player.py = Connect.y;
new Mouse();
TextualMenu.rect = new Rectangle(Frame.inventoryLabel.getX() + 80,
Frame.inventoryLabel.getY() + 100,
Frame.inventoryLabel.getWidth(),
Frame.inventoryLabel.getHeight());
Player.startMessage();
}
Don't use static variables.
Don't use a null layout.
Use appropriate layout managers. Maybe the main panel uses a BorderLayout. Then you add your main component to the CENTER and a second panel to the EAST. The second panel can also use a BorderLayout. You can then add the two components to the NORTH, CENTER or SOUTH as you require.
For example, using a custom Border:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.RadialGradientPaint;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.AbstractBorder;
#SuppressWarnings("serial")
public class FrameEg extends JPanel {
public static final String FRAME_URL_PATH = "http://th02.deviantart.net/"
+ "fs70/PRE/i/2010/199/1/0/Just_Frames_5_by_ScrapBee.png";
public static final int INSET_GAP = 120;
private BufferedImage frameImg;
private BufferedImage smlFrameImg;
public FrameEg() {
try {
URL frameUrl = new URL(FRAME_URL_PATH);
frameImg = ImageIO.read(frameUrl);
final int smlFrameWidth = frameImg.getWidth() / 2;
final int smlFrameHeight = frameImg.getHeight() / 2;
smlFrameImg = new BufferedImage(smlFrameWidth, smlFrameHeight,
BufferedImage.TYPE_INT_ARGB);
Graphics g = smlFrameImg.getGraphics();
g.drawImage(frameImg, 0, 0, smlFrameWidth, smlFrameHeight, null);
g.dispose();
int top = INSET_GAP;
int left = top;
int bottom = top;
int right = left;
Insets insets = new Insets(top, left, bottom, right);
MyBorder myBorder = new MyBorder(frameImg, insets);
JTextArea textArea = new JTextArea(50, 60);
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);
for (int i = 0; i < 300; i++) {
textArea.append("Hello world! How is it going? ");
}
setLayout(new BorderLayout(1, 1));
setBackground(Color.black);
Dimension prefSize = new Dimension(frameImg.getWidth(),
frameImg.getHeight());
JPanel centerPanel = new MyPanel(prefSize);
centerPanel.setBorder(myBorder);
centerPanel.setLayout(new BorderLayout(1, 1));
centerPanel.add(new JScrollPane(textArea), BorderLayout.CENTER);
MyPanel rightUpperPanel = new MyPanel(new Dimension(smlFrameWidth,
smlFrameHeight));
MyPanel rightLowerPanel = new MyPanel(new Dimension(smlFrameWidth,
smlFrameHeight));
top = top / 2;
left = left / 2;
bottom = bottom / 2;
right = right / 2;
Insets smlInsets = new Insets(top, left, bottom, right);
rightUpperPanel.setBorder(new MyBorder(smlFrameImg, smlInsets));
rightUpperPanel.setLayout(new BorderLayout());
rightLowerPanel.setBorder(new MyBorder(smlFrameImg, smlInsets));
rightLowerPanel.setBackgroundImg(createBackgroundImg(rightLowerPanel
.getPreferredSize()));
JTextArea ruTextArea1 = new JTextArea(textArea.getDocument());
ruTextArea1.setWrapStyleWord(true);
ruTextArea1.setLineWrap(true);
rightUpperPanel.add(new JScrollPane(ruTextArea1), BorderLayout.CENTER);
JPanel rightPanel = new JPanel(new GridLayout(0, 1, 1, 1));
rightPanel.add(rightUpperPanel);
rightPanel.add(rightLowerPanel);
rightPanel.setOpaque(false);
add(centerPanel, BorderLayout.CENTER);
add(rightPanel, BorderLayout.EAST);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private BufferedImage createBackgroundImg(Dimension preferredSize) {
BufferedImage img = new BufferedImage(preferredSize.width,
preferredSize.height, BufferedImage.TYPE_INT_ARGB);
Point2D center = new Point2D.Float(img.getWidth()/2, img.getHeight()/2);
float radius = img.getWidth() / 2;
float[] dist = {0.0f, 1.0f};
Color centerColor = new Color(100, 100, 50);
Color outerColor = new Color(25, 25, 0);
Color[] colors = {centerColor , outerColor };
RadialGradientPaint paint = new RadialGradientPaint(center, radius, dist, colors);
Graphics2D g2 = img.createGraphics();
g2.setPaint(paint);
g2.fillRect(0, 0, img.getWidth(), img.getHeight());
g2.dispose();
return img;
}
private static void createAndShowGui() {
FrameEg mainPanel = new FrameEg();
JFrame frame = new JFrame("FrameEg");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.setResizable(false);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class MyPanel extends JPanel {
private Dimension prefSize;
private BufferedImage backgroundImg;
public MyPanel(Dimension prefSize) {
this.prefSize = prefSize;
}
public void setBackgroundImg(BufferedImage background) {
this.backgroundImg = background;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (backgroundImg != null) {
g.drawImage(backgroundImg, 0, 0, this);
}
}
#Override
public Dimension getPreferredSize() {
return prefSize;
}
}
#SuppressWarnings("serial")
class MyBorder extends AbstractBorder {
private BufferedImage borderImg;
private Insets insets;
public MyBorder(BufferedImage borderImg, Insets insets) {
this.borderImg = borderImg;
this.insets = insets;
}
#Override
public void paintBorder(Component c, Graphics g, int x, int y, int width,
int height) {
g.drawImage(borderImg, 0, 0, c);
}
#Override
public Insets getBorderInsets(Component c) {
return insets;
}
}
Which would look like:

creating and displaying objects during runtime using swing

I am trying to create a simple GUI for a BST tree allowing insertions and deletions. However, I am having a lot of trouble inserting components onto the GUI during runtime.
What I thought of doing was to "refresh" the GUI every time an insertion or deletion happened. I created a method called printBst that creates Jlabels to display the numbered indexes as shown below, but they are not showing up.
I've tried to revalidate and validate the GUI afterwards but it still doesn't work. Anyone have any ideas?
package source;
import javax.swing.*;
import source.BST.BSTnode;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;
public class Frame2 extends JFrame implements ActionListener{
BST bst;
JPanel displayPanel, buttonPanel, totalGUI;
JButton insertButton, deleteButton, resetButton;
JTextField insertField, deleteField;
public JPanel createContentPane (){
bst = new BST();
totalGUI = new JPanel();
totalGUI.setLayout(null);
displayPanel = new JPanel();
displayPanel.setLayout(null);
displayPanel.setLocation(10, 80);
displayPanel.setSize(400, 300);
totalGUI.add(displayPanel);
buttonPanel = new JPanel();
buttonPanel.setLayout(null);
buttonPanel.setLocation(10, 0);
buttonPanel.setSize(800, 80);
totalGUI.add(buttonPanel);
insertField = new JTextField(1);
insertField.addActionListener(this);
insertField.setLocation(0, 10);
insertField.setSize(150, 30);
buttonPanel.add(insertField);
insertButton = new JButton("Insert");
insertButton.setLocation(160, 10);
insertButton.setSize(150, 30);
insertButton.addActionListener(this);
buttonPanel.add(insertButton);
deleteField = new JTextField(1);
deleteField.addActionListener(this);
deleteField.setLocation(320, 10);
deleteField.setSize(150, 30);
buttonPanel.add(deleteField);
deleteButton = new JButton("Delete");
deleteButton.setLocation(480, 10);
deleteButton.setSize(150, 30);
deleteButton.addActionListener(this);
buttonPanel.add(deleteButton);
resetButton = new JButton("Reset");
resetButton.setLocation(640, 10);
resetButton.setSize(150, 30);
resetButton.addActionListener(this);
buttonPanel.add(resetButton);
totalGUI.setOpaque(true);
return totalGUI;
}
public void printBst(BSTnode node, int x, int x2, int y) {
if (node != null) {
JLabel current = new JLabel(""+ node.data);
current.setLocation((x+x2)/2, y);
current.setSize(100, 30);
current.setHorizontalAlignment(0);
displayPanel.add(current);
printBst(node.left, x, (x2+x)/2, y+60);
printBst(node.right, (x2+x)/2, x2, y+60);
System.out.println("here");
}
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == insertButton)
{
bst.insert(Integer.valueOf(insertField.getText()));
displayPanel.removeAll();
printBst(bst.root, 0, 800, 0);
totalGUI.revalidate();
validate();
}
else if(e.getSource() == deleteButton)
{
bst.delete(Integer.valueOf(deleteField.getText()));
displayPanel.removeAll();
printBst(bst.root, 0, 800, 0);
totalGUI.revalidate();
validate();
}
else if(e.getSource() == resetButton)
{
bst.clear();
displayPanel.removeAll();
printBst(bst.root, 0, 800, 0);
totalGUI.revalidate();
validate();
}
}
private static void createAndShowGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("[=] JButton Scores! [=]");
Frame2 demo = new Frame2();
frame.setContentPane(demo.createContentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(900, 400);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Make sure you call revalidate() and repaint() after you remove components from displayPanel ie:
displayPanel.removeAll();
printBst(0, 800, 0);
displayPanel.revalidate();
displayPanel.repaint();
Also, note that:
printBst(0, 800, 0);
results in invalid (not in bounds) coordinates inside displayPanel, which size is defined as (400, 300) The top-left corner of a window is 0,0. Try the following and you should see your label somewhere in the middle of the panel:
printBst(0, 400, 0);
Absolute positioning can be very difficult to manage. Check out A Visual Guide to Layout Managers and see if you can find an appropriate layout to help you.
You may also consider ready to go frameworks that can give you 2D canvas to work on. For example JGraph, JFreeChart or Piccolo2D.

Categories

Resources