Java GUI paint picture on labels - java

I want to add a picture that will be in the panel and also on labels but I don't know how to do that.
my code:
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JPanel mainPanel = new JPanel();
panel.setLayout(new GridLayout(5, 5));
for (int i = 0; i < 5; i++)
for (int j = 0; j < 5; j++)
{
JLabel label = new JLabel();
label.setPreferredSize(new Dimension(50, 50));
label.setBorder(BorderFactory.createLineBorder(Color.BLACK));
panel.add(label);
}
mainPanel.add(panel);
frame.add(mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
My Picture:
https://i.stack.imgur.com/w0Ssy.png
What I want to make:
https://i.stack.imgur.com/ZLPqF.png

If you're going to use components do to this job, then you're going to need to do some juggling with the layout managers. Because of it's flexibility, I would use GridBagLayout, in fact, I'm pretty sure it's the only inbuilt layout that will allow you to do something like this...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.MatteBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new GamePane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class GamePane extends JPanel {
public GamePane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
for (int y = 0; y < 10; y++) {
for (int x = 0; x < 10; x++) {
GridPane gridPane;
if (y == 9) {
if (x == 9) {
gridPane = new GridPane(1, 1, 1, 1);
} else {
gridPane = new GridPane(1, 1, 1, 0);
}
} else if (x == 9) {
gridPane = new GridPane(1, 1, 0, 1);
} else {
gridPane = new GridPane(1, 1, 0, 0);
}
gbc.gridx = x;
gbc.gridy = y;
add(gridPane, gbc);
}
}
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 1;
gbc.gridheight = 4;
gbc.fill = GridBagConstraints.HORIZONTAL;
add(new ShipPane(1, 4), gbc, 0);
gbc = new GridBagConstraints();
gbc.gridx = 2;
gbc.gridy = 1;
gbc.gridwidth = 3;
gbc.gridheight = 1;
gbc.fill = GridBagConstraints.BOTH;
add(new ShipPane(3, 1), gbc, 0);
}
}
public class Configuration {
public static int GRID_SIZE = 50;
}
public class GridPane extends JPanel {
public GridPane(int top, int left, int bottom, int right) {
setBorder(new MatteBorder(top, left, bottom, right, Color.DARK_GRAY));
}
#Override
public Dimension getPreferredSize() {
return new Dimension(Configuration.GRID_SIZE, Configuration.GRID_SIZE);
}
}
public class ShipPane extends JPanel {
private int gridWidth, gridHeight;
public ShipPane(int gridWidth, int gridHeight) {
this.gridWidth = gridWidth;
this.gridHeight = gridHeight;
setOpaque(false);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(Configuration.GRID_SIZE * gridWidth, Configuration.GRID_SIZE * gridHeight);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(new Color(255, 0, 0, 128));
g.fillRect(0, 0, getWidth(), getHeight());
}
}
}
Now, I'm just using a panel, but without much work, you could add a JLabel to the ShipPane
Now, having said that. I think I would approach this problem from an entirely "custom painting" route

The way to do this is to use JLabel.setIcon
JLabel l = ...;
l.setIcon(myIcon);
You can make an Icon from an Image using ImageIcon.
You can get an image by loading it from disk/url, or by creating your own by creating a BufferedImage and drawing to its Graphics object.

Related

Panels take equal space

I have two panels. The first one looks like this.
public class BoardPanel extends JPanel
{
public BoardPanel()
{
setLayout(null);
this.setOpaque(false);
Button button = new JButton("..");
button.setLocation(...);
button.setSize(...);
add(button);
}
public void paintComponent( Graphics g )
{
/*
* Painting some stuff here.
*/
}
}
The other panel is something like this:
public class OtherPanel extends JPanel
{
public OtherPanel()
{
super();
this.setLayout(null);
this.setOpaque(false);
JPanel panel1 = new JPanel();
panel1.setLocation(...);
panel1.setSize(...);
panel1.setOpaque( .. );
JPanel panel2 = new JPanel();
panel2.setLocation(...);
panel2.setSize(...);
panel2.setOpaque( .. );
add(panel1):
add(panel2);
}
}
After that , I put both my panels in a frame. But I want my BoardPanel to occupy more screen than OtherPanel. So I used GridBagLayout for the frame
public class MainFrame extends JFrame
{
private GridBagLayout aGridLayout = new GridBagLayout();
private GridBagConstraints constraints = new GridBagConstraints();
public MainFrame()
{
super("Quoridor");
setLayout(gridLayout);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(1366, 768);
setVisible(true);
setResizable(false);
this.getContentPane().setBackground(Color.decode("#b2a6a6"));
BoardPanel boardPanel = new BoardPanel();
OtherPanel otherPanel = new OtherPanel();
this.addComponent(boardPanel, 1, 1, 2, 1);
this.addComponent(otherPanel, 1, 3, 1, 1);
}
public void addComponent(Component component , int row , int column , int width
, int height)
{
constraints.gridx = column;
constraints.gridy = row;
constraints.gridwidth = width;
constraints.gridheight = height;
aGridLayout.setConstraints(component, constraints);
add(component);
}
}
The problem is , that the frame gives equal space to both panels , and dont give more space to the boardPanel.
Why is this happening ? Doest it have to do with the bounds of the panels ?
Here is a good tutorial on GridBagLayout: https://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html . Also see the code below and screenshot. The anchor field positions the component at the first line. The weightx field gives more space to the columns for boardPanel. The ipady field specifies how much to add to the height of the component. Here, boardPanel gets most of the width and all of the height. The otherPanel panel gets half of the height.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GridExample {
private JFrame mainFrame;
private JPanel boardPanel, otherPanel;
public GridExample(){
mainFrame = new JFrame();
mainFrame.setSize(600,400);
mainFrame.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
boardPanel = new JPanel();
boardPanel.add(new JLabel("board panel"));
boardPanel.setBackground(Color.yellow);
otherPanel = new JPanel();
otherPanel.add(new JLabel("other panel"));
otherPanel.setBackground(Color.green);
c.anchor = GridBagConstraints.FIRST_LINE_START;
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.75;
c.ipady = 400;
c.gridx = 0;
c.gridy = 0;
mainFrame.add(boardPanel, c);
c.anchor = GridBagConstraints.FIRST_LINE_START;
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.25;
c.ipady = 200;
c.gridx = 1;
c.gridy = 0;
mainFrame.add(otherPanel, c);
mainFrame.setVisible(true);
}
public static void main(String[] args){
GridExample swingContainerDemo = new GridExample();
}
}

JFrame not refreshing with repaint

I have a visual class Gameboard that consists of a frame, representing a 'board'. The idea is that when a button is clicked the players on the board will move, and so when the button is clicked the board must refresh. This is the frame:
public Gameboard(Game game, int size, ArrayList<Enemy> e, Ogre o){
this.ogre = o.getPosition();
if(this.enemies.isEmpty() == false){
this.enemies.clear();
}
if(e.isEmpty() == false){
for(Enemy en : e){
this.enemies.add(en.getPosition());
}
}
this.game = game;
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Swamp Escape!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new GridPane(size));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setResizable(false);
}
});
}
public class GridPane extends JPanel {
public GridPane(int size) {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
gbc.gridx = col;
gbc.gridy = row;
if(col == ogre.getX() && row == ogre.getY()) {
OgrePane ogre = new OgrePane();
Border border = null;
if (row < size - 1) {
if (col < size - 1) {
border = new MatteBorder(1, 1, 0, 0, Color.GRAY);
} else {
border = new MatteBorder(1, 1, 0, 1, Color.GRAY);
}
} else {
if (col < size - 1) {
border = new MatteBorder(1, 1, 1, 0, Color.GRAY);
} else {
border = new MatteBorder(1, 1, 1, 1, Color.GRAY);
}
}
ogre.setBorder(border);
add(ogre, gbc);
} else {
CellPane cellPane = new CellPane();
Border border = null;
if (row < size - 1) {
if (col < size - 1) {
border = new MatteBorder(1, 1, 0, 0, Color.GRAY);
} else {
border = new MatteBorder(1, 1, 0, 1, Color.GRAY);
}
} else {
if (col < size - 1) {
border = new MatteBorder(1, 1, 1, 0, Color.GRAY);
} else {
border = new MatteBorder(1, 1, 1, 1, Color.GRAY);
}
}
cellPane.setBorder(border);
add(cellPane, gbc);
}
}
}
JButton newGame = new JButton("New Game");
newGame.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
game.newGame();
ogre = game.getHek().getPosition();
if(enemies != null) enemies.clear();
for(Enemy en : game.enemies){
enemies.add(en.getPosition());
}
revalidate();
repaint();
}
});
gbc.gridx = 0;
gbc.gridy = size + 1;
add(newGame, gbc);
JButton move = new JButton("Next Move");
move.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
game.nextMove();
}
});
gbc.gridx = 1;
gbc.gridy = size + 1;
add(move, gbc);
JButton undo = new JButton("Undo");
gbc.gridx = 2;
gbc.gridy = size + 1;
add(undo, gbc);
JButton diet = new JButton("Change Diet");
gbc.gridx = 3;
gbc.gridy = size + 1;
add(diet, gbc);
}
}
The newGame method is working correctly but when the button tries to repaint the frame nothing happens. Specifically the new Game button.
The frame consists of a grid, each of which are populated with one a three types of cells, each extending the jpanel class.
The repaint is being called in the JButton "new game". The Cells are added in a loop fashion.
Any help is welcome!
If anyone has a similar issue this is how I fixed it:
Rather than repainting the JFrame, I simply disposed of the the current frame and created a new one with the updated positions. Its a bit of a 'Gaffer-tape' fix but it work how I want it to.
Instead of simply calling invalidate() and repaint() from the JPanel level, call them from the JFrame level. Like so:
JButton newGame = new JButton("New Game");
newGame.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
game.newGame();
ogre = game.getHek().getPosition();
if(enemies != null) enemies.clear();
for(Enemy en : game.enemies){
enemies.add(en.getPosition());
}
JFrame frame = (JFrame) getRootPane().getParent();
frame.pack();
}
});

Moving JPasswordField to absolute position

I have this code:
import java.awt.Color;
import java.awt.Component;
import java.awt.Dialog.ModalityType;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
public class DialogExample extends JPanel {
private static final int COLUMN_COUNT = 10;
private static final int I_GAP = 3;
public static final String BKG_IMG_PATH = "http://upload.wikimedia.org/wikipedia/commons/"
+ "thumb/9/92/Camels_in_Jordan_valley_%284568207363%29.jpg/800px-Camels_in_Jordan_valley_"
+ "%284568207363%29.jpg";
private BufferedImage backgrndImage;
private JTextField userNameField = new JTextField();
private JPasswordField passwordField = new JPasswordField();
private JPanel mainPanel = new JPanel(new GridBagLayout());
private JButton okButton = new JButton("OK");
private JButton cancelButton = new JButton("Cancel");
public DialogExample(BufferedImage backgrndImage) {
this.backgrndImage = backgrndImage;
userNameField.setColumns(COLUMN_COUNT);
passwordField.setColumns(COLUMN_COUNT);
JPanel btnPanel = new JPanel(new GridLayout(1, 0, 5, 5));
btnPanel.setOpaque(false);
btnPanel.add(okButton);
btnPanel.add(cancelButton);
GridBagConstraints gbc = getGbc(0, 0, GridBagConstraints.BOTH);
mainPanel.add(createLabel("User Name", Color.white), gbc);
gbc = getGbc(1, 0, GridBagConstraints.HORIZONTAL);
mainPanel.add(userNameField, gbc);
gbc = getGbc(0, 1, GridBagConstraints.BOTH);
mainPanel.add(createLabel("Password:", Color.white), gbc);
gbc = getGbc(1, 1, GridBagConstraints.HORIZONTAL);
mainPanel.add(passwordField, gbc);
gbc = getGbc(0, 2, GridBagConstraints.BOTH, 2, 1);
mainPanel.add(btnPanel, gbc);
mainPanel.setOpaque(false);
add(mainPanel);
}
private JLabel createLabel(String text, Color color) {
JLabel label = new JLabel(text);
label.setForeground(color);
return label;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (backgrndImage != null) {
g.drawImage(backgrndImage, 0, 0, this);
}
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet() || backgrndImage == null) {
return super.getPreferredSize();
}
int imgW = backgrndImage.getWidth();
int imgH = backgrndImage.getHeight();
return new Dimension(imgW, imgH);
}
public static GridBagConstraints getGbc(int x, int y, int fill) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.insets = new Insets(I_GAP, I_GAP, I_GAP, I_GAP);
gbc.fill = fill;
return gbc;
}
public static GridBagConstraints getGbc(int x, int y, int fill, int width,
int height) {
GridBagConstraints gbc = getGbc(x, y, fill);
gbc.gridwidth = width;
gbc.gridheight = height;
return gbc;
}
private static void createAndShowGui() throws IOException {
final JFrame frame = new JFrame("Frame");
final JDialog dialog = new JDialog(frame, "User Sign-In", ModalityType.APPLICATION_MODAL);
URL imgUrl = new URL(BKG_IMG_PATH);
BufferedImage img = ImageIO.read(imgUrl);
final DialogExample dlgExample = new DialogExample(img);
dialog.add(dlgExample);
dialog.pack();
JPanel mainPanel = new JPanel();
mainPanel.add(new JButton(new AbstractAction("Please Press Me!") {
#Override
public void actionPerformed(ActionEvent e) {
dialog.setVisible(true);
}
}));
mainPanel.setPreferredSize(new Dimension(800, 650));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
createAndShowGui();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
Ho can I move the JPasswordField to a absolute position (X,Y)?? I've been trying different things like setPosition(int X, int Y) and nothing worked. I tryed playing too with the layout but not success either. I would like to have just a JPasswordField object and a button object on his right. that's it
Thank you
Start by creating a panel for the password field and button to reside on. Next, randomise a EmptyBorder and the Insets of a GridBagConstraints to define different locations within the parent container. Add the password/button panel to this container with these randomised constraints...
public class TestPane extends JPanel {
public TestPane() {
Random rnd = new Random();
JPanel panel = new JPanel();
JPasswordField pf = new JPasswordField(10);
JButton btn = new JButton("Login");
panel.add(pf);
panel.add(btn);
panel.setBorder(new EmptyBorder(rnd.nextInt(10), rnd.nextInt(10), rnd.nextInt(10), rnd.nextInt(10)));
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(rnd.nextInt(100), rnd.nextInt(100), rnd.nextInt(100), rnd.nextInt(100));
add(panel, gbc);
}
}
The other choice would be to write your own custom layout manager...but if you can avoid it, the above example is MUCH simpler...
ps- You could randomise either the border OR the insets, maybe using a larger random range and get the same effect, I've simpler used both to demonstrate the point ;)
Updated with layout manager example
public class TestPane extends BackgroundImagePane {
public TestPane() throws IOException {
super(ImageIO.read(new File("Path/to/your/image")));
Random rnd = new Random();
JPanel panel = new JPanel();
panel.setOpaque(false);
JPasswordField pf = new JPasswordField(10);
JButton btn = new JButton("Login");
panel.add(pf);
panel.add(btn);
setLayout(new RandomLayoutManager());
Dimension size = getPreferredSize();
size.width -= panel.getPreferredSize().width;
size.height -= panel.getPreferredSize().height;
add(panel, new Point(rnd.nextInt(size.width), rnd.nextInt(size.height)));
}
}
public class RandomLayoutManager implements LayoutManager2 {
private Map<Component, Point> mapConstraints;
public RandomLayoutManager() {
mapConstraints = new WeakHashMap<>(25);
}
#Override
public void addLayoutComponent(String name, Component comp) {
throw new UnsupportedOperationException("Not supported yet.");
}
#Override
public void removeLayoutComponent(Component comp) {
mapConstraints.remove(comp);
}
#Override
public Dimension preferredLayoutSize(Container parent) {
Area area = new Area();
for (Component comp : mapConstraints.keySet()) {
Point p = mapConstraints.get(comp);
Rectangle bounds = new Rectangle(p, comp.getPreferredSize());
area.add(new Area(bounds));
}
Rectangle bounds = area.getBounds();
Dimension size = bounds.getSize();
size.width += bounds.x;
size.height += bounds.y;
return size;
}
#Override
public Dimension minimumLayoutSize(Container parent) {
return preferredLayoutSize(parent);
}
#Override
public void layoutContainer(Container parent) {
for (Component comp : mapConstraints.keySet()) {
Point p = mapConstraints.get(comp);
comp.setLocation(p);
comp.setSize(comp.getPreferredSize());
}
}
#Override
public void addLayoutComponent(Component comp, Object constraints) {
if (constraints instanceof Point) {
mapConstraints.put(comp, (Point) constraints);
} else {
throw new IllegalArgumentException("cannot add to layout: constraint must be a java.awt.Point");
}
}
#Override
public Dimension maximumLayoutSize(Container target) {
return preferredLayoutSize(target);
}
#Override
public float getLayoutAlignmentX(Container target) {
return 0.5f;
}
#Override
public float getLayoutAlignmentY(Container target) {
return 0.5f;
}
#Override
public void invalidateLayout(Container target) {
}
}
public class BackgroundImagePane extends JPanel {
private Image image;
public BackgroundImagePane(Image img) {
this.image = img;
}
#Override
public Dimension getPreferredSize() {
return image == null ? super.getPreferredSize() : new Dimension(image.getWidth(this), image.getHeight(this));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null) {
int x = (getWidth() - image.getWidth(this)) / 2;
int y = (getHeight() - image.getHeight(this)) / 2;
g.drawImage(image, x, y, this);
}
}
}
The BackgroundImagePane is based on this example, allowing the background image panel to be the container for the field panel and you should be well on your way...
You could use a null layout, but that takes too long and it doesn't re-size with the frame.
Like this:
public class TestPane{
public static void main (String[] args) {
Random rnd = new Random();
JFrame frame = new JFrame();
JPasswordField pf = new JPasswordField();
JButton btn = new JButton("Login");
frame.setSize(500, 500);
frame.setLayout(null);
btn.setBounds(y, x, width, height);
pf.setBounds(y, x, width, height);
frame.add(btn);
frame.add(pf);
}
}
And that should work.
If you want to use a null layout.

Update frame or revalidate/repaint panel

How to update a Java frame with changed content?
I want to update a frame or just the panel with updated content. What do I use for this
Here is where I want to revalidate the frame or repaint mainpanel or whatever will work
I have tried a number of things, but none of them have worked.
public void actionPerformed(ActionEvent e) {
//System.out.println(e.getActionCommand());
if (e.getActionCommand().equals("advance")) {
multi--;
// Revalidate update repaint here <<<<<<<<<<<<<<<<<<<
}
else if (e.getActionCommand().equals("reverse")) {
multi++;
// Revalidate update repaint here <<<<<<<<<<<<<<<<<<<
}
else {
openURL(e.getActionCommand());
}
}
Here is the whole java file
/*
*
*
*/
package build;
import java.lang.reflect.Method;
import javax.swing.JOptionPane;
import java.util.Arrays;
import java.util.*;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.AbstractButton;
import javax.swing.JScrollPane;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.ImageIcon;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
/*
* ButtonDemo.java requires the following files:
* images/right.gif
* images/middle.gif
* images/left.gif
*/
public class StockTable extends JPanel
implements ActionListener {
static int multi = 1;
int roll = 0;
static TextVars textvars = new TextVars();
static final String[] browsers = { "firefox", "opera", "konqueror", "epiphany",
"seamonkey", "galeon", "kazehakase", "mozilla", "netscape" };
JFrame frame;
JPanel mainpanel, panel1, panel2, panel3, panel4, panel2left, panel2center, panel2right;
JButton stknames_btn[] = new JButton[textvars.getNumberOfStocks()];
JLabel label[] = new JLabel[textvars.getNumberOfStocks()];
JLabel headlabel, dayspan, namelabel;
JRadioButton radioButton;
JButton button;
JScrollPane scrollpane;
int wid = 825;
public JPanel createContentPane() {
mainpanel = new JPanel();
mainpanel.setPreferredSize(new Dimension(wid, 800));
mainpanel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
panel1 = new JPanel();
panel1.setPreferredSize(new Dimension(wid, 25));
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(0,0,0,0);
mainpanel.add(panel1, c);
// Panel 2------------
panel2 = new JPanel();
panel2.setPreferredSize(new Dimension(wid, 51));
c.gridx = 0;
c.gridy = 1;
c.insets = new Insets(0,0,0,0);
mainpanel.add(panel2, c);
panel2left = new JPanel();
panel2left.setPreferredSize(new Dimension(270, 51));
c.gridx = 0;
c.gridy = 1;
c.insets = new Insets(0,0,0,0);
panel2.add(panel2left, c);
panel2center = new JPanel();
panel2center.setPreferredSize(new Dimension(258, 51));
c.gridx = 1;
c.gridy = 1;
c.insets = new Insets(0,0,0,0);
panel2.add(panel2center, c);
panel2right = new JPanel();
panel2right.setPreferredSize(new Dimension(270, 51));
c.gridx = 2;
c.gridy = 1;
c.insets = new Insets(0,0,0,0);
panel2.add(panel2right, c);
// ------------------
panel3 = new JPanel();
panel3.setLayout(new GridBagLayout());
scrollpane = new JScrollPane(panel3);
scrollpane.setPreferredSize(new Dimension(wid, 675));
c.gridx = 0;
c.gridy = 2;
c.insets = new Insets(0,0,0,0);
mainpanel.add(scrollpane, c);
ImageIcon leftButtonIcon = createImageIcon("images/right.gif");
//b1 = new JButton("Disable middle button", leftButtonIcon);
//b1.setVerticalTextPosition(AbstractButton.CENTER);
//b1.setHorizontalTextPosition(AbstractButton.LEADING); //aka LEFT, for left-to-right locales
//b1.setMnemonic(KeyEvent.VK_D);
//b1.setActionCommand("disable");
//Listen for actions on buttons 1
//b1.addActionListener(this);
//b1.setToolTipText("Click this button to disable the middle button.");
//Add Components to this container, using the default FlowLayout.
//add(b1);
headlabel = new JLabel("hellorow1");
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(0, 0, 0, 0);
panel1.add(headlabel, c);
radioButton = new JRadioButton("Percentage");
c.gridx = 2;
c.gridy = 0;
c.insets = new Insets(0, 0, 0, 0);
panel1.add(radioButton, c);
radioButton = new JRadioButton("Days Range");
c.gridx = 3;
c.gridy = 0;
c.insets = new Insets(0, 0, 0, 0);
panel1.add(radioButton, c);
radioButton = new JRadioButton("Open / Close");
c.gridx = 4;
c.gridy = 0;
c.insets = new Insets(0, 0, 0,0 );
panel1.add(radioButton, c);
button = new JButton("<<");
button.setPreferredSize(new Dimension(50, 50));
button.setActionCommand("reverse");
button.addActionListener(this);
c.gridx = 0;
c.gridy = 1;
c.insets = new Insets(0, 0, 0, 0);
panel2left.add(button, c);
dayspan = new JLabel("hellorow2");
dayspan.setHorizontalAlignment(JLabel.CENTER);
dayspan.setVerticalAlignment(JLabel.CENTER);
dayspan.setPreferredSize(new Dimension(270, 50));
c.gridx = 1;
c.gridy = 1;
c.insets = new Insets(0, 0, 0, 0);
panel2center.add(dayspan, c);
button = new JButton(">>");
button.setPreferredSize(new Dimension(50, 50));
button.setActionCommand("advance");
button.addActionListener(this);
if (multi == 0) {
button.setEnabled(false);
}
else {
button.setEnabled(true);
}
c.gridx = 2;
c.gridy = 1;
c.insets = new Insets(0, 0, 0, 0);
panel2right.add(button, c);
int availSpace_int = textvars.getStocks().size()-textvars.getNumberOfStocks()*7;
ArrayList<String[]> stocknames = textvars.getStockNames();
ArrayList<String[]> stocks = textvars.getStocks();
for (int column = 0; column < 8; column++) {
for (int row = 0; row < textvars.getNumberOfStocks(); row++) {
if (column==0) {
if (row==0) {
namelabel = new JLabel(stocknames.get(0)[0]);
namelabel.setVerticalAlignment(JLabel.CENTER);
namelabel.setHorizontalAlignment(JLabel.CENTER);
namelabel.setPreferredSize(new Dimension(100, 25));
c.gridx = column;
c.gridy = row;
c.insets = new Insets(0, 0, 0, 0);
panel3.add(namelabel, c);
}
else {
stknames_btn[row] = new JButton(stocknames.get(row)[0], leftButtonIcon);
stknames_btn[row].setVerticalTextPosition(AbstractButton.CENTER);
stknames_btn[row].setActionCommand(stocknames.get(row)[1]);
stknames_btn[row].addActionListener(this);
stknames_btn[row].setToolTipText("go to Google Finance "+stocknames.get(row)[0]);
stknames_btn[row].setPreferredSize(new Dimension(100, 25));
c.gridx = column;
c.gridy = row;
c.insets = new Insets(0, 0, 0, 0);
//scrollpane.add(stknames[row], c);
panel3.add(stknames_btn[row], c);
}
}
else {
label[row]= new JLabel(textvars.getStocks().get(columnMulti(multi))[1]);
label[row].setBorder(BorderFactory.createLineBorder(Color.black));
label[row].setVerticalAlignment(JLabel.CENTER);
label[row].setHorizontalAlignment(JLabel.CENTER);
label[row].setPreferredSize(new Dimension(100, 25));
c.gridx = column;
c.gridy = row;
c.insets = new Insets(0,0,0,0);
panel3.add(label[row], c);
}
}
}
return mainpanel;
}
public void actionPerformed(ActionEvent e) {
//System.out.println(e.getActionCommand());
if (e.getActionCommand().equals("advance")) {
multi--;
}
else if (e.getActionCommand().equals("reverse")) {
multi++;
}
else {
openURL(e.getActionCommand());
}
}
/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = StockTable.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
public static void openURL(String url) {
String osName = System.getProperty("os.name");
try {
if (osName.startsWith("Mac OS")) {
Class<?> fileMgr = Class.forName("com.apple.eio.FileManager");
Method openURL = fileMgr.getDeclaredMethod("openURL",
new Class[] {String.class});
openURL.invoke(null, new Object[] {url});
}
else if (osName.startsWith("Windows")) {
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
}
else { //assume Unix or Linux
boolean found = false;
for (String browser : browsers)
if (!found) {
found = Runtime.getRuntime().exec(
new String[] {"which", browser}).waitFor() == 0;
if (found)
Runtime.getRuntime().exec(new String[] {browser, url});
}
if (!found)
throw new Exception(Arrays.toString(browsers));
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(null,
"Error attempting to launch web browser\n" + e.toString());
}
}
int reit = 0;
int start = textvars.getStocks().size()-((textvars.getNumberOfStocks()*5)*7)-1;
public int columnMulti(int multi) {
reit++;
start++;
if (reit == textvars.getNumberOfStocks()) {
reit = 0;
start=start+64;
}
//start = start - (multi*(textvars.getNumberOfStocks()));
return start;
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Stock Table");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
StockTable newContentPane = new StockTable();
//newContentPane.setOpaque(true); //content panes must be opaque
//frame.setContentPane(newContentPane);
frame.setContentPane(newContentPane.createContentPane());
frame.setSize(800, 800);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
The moment you find yourself wanting to "re-create" a UI based on a small change, should raise alarm bells. There are situations when this is going to be a good idea, but in most cases, it's a sign of a bad design.
Let's start with...
frame.setContentPane(newContentPane.createContentPane());
This is a bad idea. You create a JPanel just to create another JPanel. All of sudden, you've not lost context to the UI.
Instead of the createContentPane, simple construct you UI from the constructor of the StockTable pane and add that to the frame...More like...
frame.setContentPane(newContentPane);
Get rid of mainPanel and use the StockTable panel directly.
I can't run your code, but it looks speciously like your trying to "emulate" a table layout. Instead, simplify your life and learn to use JTable. Updating the table more be significantly easier (not to mention look nicer) if you do...
My suggestion is if you want to update a swing component always use the Event Dispatcher Thread.
I think this may helps you
public void actionPerformed(ActionEvent e) {
//System.out.println(e.getActionCommand());
if (e.getActionCommand().equals("advance")) {
multi--;
Runnable edt = new Runnable() {
public void run() {
/*Update your components here*/
}
};
SwingUtilities.invokeLater(edt);
}
else if (e.getActionCommand().equals("reverse")) {
multi++;
Runnable edt= new Runnable() {
public void run() {
/*Update your components here*/
}
};
SwingUtilities.invokeLater(edt);
}
else {
openURL(e.getActionCommand());
}
}
}

How to prevent Boxlayout/Box from stretching children components?

As you can see in the runnable code below, i try to have a Box with expandable child-boxes. The children Boxes can change they size and this all works good. The main problem is that the size is always relative to the parent. But I want them to have a specific size and in case there is no place anymore use the JScrollPane. At the moment they shrink the other children-boxes only.
I tried Glue and Filler, but it didn't work. The glue just had no effect and the filler had the side effect to keep always some place at the (even when the ScrollPane is in action). That is pretty ugly to have there so much free space.
So, do you know a good way to prevent the Boxes from stretching the children?
Thank you in advance!
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.TitledBorder;
public class ExpandableMenueDemo {
Box allBoxes;
ExpandableMenueDemo(){
allBoxes = Box.createVerticalBox();
TitledBorder title;
title = BorderFactory.createTitledBorder("Filter");
allBoxes.setBorder(title);
for (int i = 0 ;i<3;i++){
//generate collapsable components
SubBox b = new SubBox("SubBox"+i);
allBoxes.add(b.getSwingBox());
}
allBoxes.add(Box.createVerticalGlue());
}
public Container getMenue(){
return allBoxes;
}
public static void main(String[] args) {
JFrame frame = new JFrame();
ExpandableMenueDemo m = new ExpandableMenueDemo();
Box mainBox = Box.createHorizontalBox();
mainBox.add(new JScrollPane(m.getMenue()));
mainBox.add(new JTable(20,5));
frame.setContentPane(mainBox);
frame.pack();
frame.setVisible(true);
}
class SubBox{
Box box;
Box header;
String name;
JButton cBtn;
boolean isCollapsed = true;
JLabel headerLine;
SubBox(String name) {
this.name= name;
box = Box.createVerticalBox();
headerLine = new JLabel(name+" () :");
header= Box.createHorizontalBox();
cBtn = new JButton("v");
cBtn.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
if (isCollapsed)show();
else collapse();
}
});
collapse();
header.add(cBtn);
header.add(Box.createHorizontalStrut(10));
header.add(headerLine);
header.add(Box.createHorizontalGlue());
}
Box getSwingBox() {
Box b = Box.createVerticalBox();
b.add(header);
b.add(box);
return b;
}
public void collapse(){
System.out.println("collapse");
box.removeAll();
this.isCollapsed=true;
cBtn.setText("v");
}
public void show(){
System.out.println("show");
box.removeAll();
this.isCollapsed=false;
cBtn.setText("^");
for (int i = 0; i<3;i++) {
Box b = Box.createHorizontalBox();
b.add(Box.createHorizontalStrut(20));
b.add(new JCheckBox("checkBox "+i));
b.add(Box.createHorizontalGlue());
box.add(b);
}
}
}
}
BoxLayout can accepting setXxxSize,
maybe better example for expanding/collapsing JPanels nests another JComponents
import java.awt.*;
import java.awt.event.*;
import java.awt.font.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class ExpandingPanels extends MouseAdapter {
private ActionPanel[] aps;
private JPanel[] panels;
public ExpandingPanels() {
assembleActionPanels();
assemblePanels();
}
#Override
public void mousePressed(MouseEvent e) {
ActionPanel ap = (ActionPanel) e.getSource();
if (ap.target.contains(e.getPoint())) {
ap.toggleSelection();
togglePanelVisibility(ap);
}
}
private void togglePanelVisibility(ActionPanel ap) {
int index = getPanelIndex(ap);
if (panels[index].isShowing()) {
panels[index].setVisible(false);
} else {
panels[index].setVisible(true);
}
ap.getParent().validate();
}
private int getPanelIndex(ActionPanel ap) {
for (int j = 0; j < aps.length; j++) {
if (ap == aps[j]) {
return j;
}
}
return -1;
}
private void assembleActionPanels() {
String[] ids = {"level 1", "level 2", "level 3", "level 4"};
aps = new ActionPanel[ids.length];
for (int j = 0; j < aps.length; j++) {
aps[j] = new ActionPanel(ids[j], this);
}
}
private void assemblePanels() {
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(2, 1, 2, 1);
gbc.weightx = 1.0;
gbc.weighty = 1.0;
JPanel p1 = new JPanel(new GridBagLayout());
gbc.gridwidth = GridBagConstraints.RELATIVE;
p1.add(new JButton("button 1"), gbc);
gbc.gridwidth = GridBagConstraints.REMAINDER;
p1.add(new JButton("button 2"), gbc);
gbc.gridwidth = GridBagConstraints.RELATIVE;
p1.add(new JButton("button 3"), gbc);
gbc.gridwidth = GridBagConstraints.REMAINDER;
p1.add(new JButton("button 4"), gbc);
JPanel p2 = new JPanel(new GridBagLayout());
gbc.gridwidth = 1;
gbc.anchor = GridBagConstraints.EAST;
p2.add(new JLabel("enter"), gbc);
gbc.anchor = GridBagConstraints.WEST;
p2.add(new JTextField(8), gbc);
gbc.anchor = GridBagConstraints.CENTER;
p2.add(new JButton("button 1"), gbc);
gbc.gridwidth = GridBagConstraints.REMAINDER;
p2.add(new JButton("button 2"), gbc);
JPanel p3 = new JPanel(new BorderLayout());
JTextArea textArea = new JTextArea(8, 12);
textArea.setLineWrap(true);
p3.add(new JScrollPane(textArea));
JPanel p4 = new JPanel(new GridBagLayout());
addComponents(new JLabel("label 1"), new JTextField(12), p4, gbc);
addComponents(new JLabel("label 2"), new JTextField(16), p4, gbc);
gbc.gridwidth = 2;
gbc.gridy = 2;
p4.add(new JSlider(), gbc);
gbc.gridy++;
JPanel p5 = new JPanel(new GridBagLayout());
p5.add(new JButton("button 1"), gbc);
p5.add(new JButton("button 2"), gbc);
p5.add(new JButton("button 3"), gbc);
p5.add(new JButton("button 4"), gbc);
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
p4.add(p5, gbc);
panels = new JPanel[]{p1, p2, p3, p4};
}
private void addComponents(Component c1, Component c2, Container c, GridBagConstraints gbc) {
gbc.anchor = GridBagConstraints.EAST;
gbc.gridwidth = GridBagConstraints.RELATIVE;
c.add(c1, gbc);
gbc.anchor = GridBagConstraints.WEST;
gbc.gridwidth = GridBagConstraints.REMAINDER;
c.add(c2, gbc);
gbc.anchor = GridBagConstraints.CENTER;
}
private JPanel getComponent() {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(1, 3, 0, 3);
gbc.weightx = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = GridBagConstraints.REMAINDER;
for (int j = 0; j < aps.length; j++) {
panel.add(aps[j], gbc);
panel.add(panels[j], gbc);
panels[j].setVisible(false);
}
JLabel padding = new JLabel();
gbc.weighty = 1.0;
panel.add(padding, gbc);
return panel;
}
public static void main(String[] args) {
Runnable doRun = new Runnable() {
#Override
public void run() {
ExpandingPanels test = new ExpandingPanels();
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new JScrollPane(test.getComponent()));
f.setSize(360, 500);
f.setLocation(200, 100);
f.setVisible(true);
}
};
SwingUtilities.invokeLater(doRun);
}
}
class ActionPanel extends JPanel {
private static final long serialVersionUID = 1L;
private String text;
private Font font;
private boolean selected;
private BufferedImage open, closed;
public Rectangle target;
final int OFFSET = 30,
PAD = 5;
ActionPanel(String text, MouseListener ml) {
this.text = text;
addMouseListener(ml);
font = new Font("sans-serif", Font.PLAIN, 12);
selected = false;
setBackground(new Color(200, 200, 220));
setPreferredSize(new Dimension(200, 20));
setBorder(BorderFactory.createRaisedBevelBorder());
setPreferredSize(new Dimension(200, 20));
createImages();
setRequestFocusEnabled(true);
}
public void toggleSelection() {
selected = !selected;
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
int w = getWidth();
int h = getHeight();
if (selected) {
g2.drawImage(open, PAD, 0, this);
} else {
g2.drawImage(closed, PAD, 0, this);
}
g2.setFont(font);
FontRenderContext frc = g2.getFontRenderContext();
LineMetrics lm = font.getLineMetrics(text, frc);
float height = lm.getAscent() + lm.getDescent();
float x = OFFSET;
float y = (h + height) / 2 - lm.getDescent();
g2.drawString(text, x, y);
}
private void createImages() {
int w = 20;
int h = getPreferredSize().height;
target = new Rectangle(2, 0, 20, 18);
open = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = open.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(getBackground());
g2.fillRect(0, 0, w, h);
int[] x = {2, w / 2, 18};
int[] y = {4, 15, 4};
Polygon p = new Polygon(x, y, 3);
g2.setPaint(Color.green.brighter());
g2.fill(p);
g2.setPaint(Color.blue.brighter());
g2.draw(p);
g2.dispose();
closed = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
g2 = closed.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(getBackground());
g2.fillRect(0, 0, w, h);
x = new int[]{3, 13, 3};
y = new int[]{4, h / 2, 16};
p = new Polygon(x, y, 3);
g2.setPaint(Color.red);
g2.fill(p);
g2.setPaint(Color.blue.brighter());
g2.draw(p);
g2.dispose();
}
}
Instead of re-inventing the wheel, you might consider to use JXTaskPane/-Container contained in SwingX. Its demo shows it in action (as taskPanes) at the left - that's the part for choosing the demos.

Categories