JFrame not refreshing with repaint - java

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();
}
});

Related

Java GUI paint picture on labels

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.

How do I make a JFrame transparent / Opaque without having to setUndecorated(true)

Is there a way that I can set the JFrame to be transparent while still leaving the Buttons / text unaffected?
If not, how can I make the JFrame transparent without using .setUndecorated(true)?
This is a totally different question, but how would I go about adding a gradient as the background color instead of having it be set to one solid color?
Click here to see what the JFrame looks like when the program runs!
class PlayAgain extends JPanel
{
private JFrame nextFrame;
public PlayAgain()
{
nextFrame = new JFrame("Tic-Tac-Toe");
nextFrame.setSize(250,125);
nextFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridBagLayout());
nextFrame.add(panel);
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(10,10,10,10);
class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
nextFrame.dispose();
frame.dispose();
XorOFrameGRID obj = new XorOFrameGRID();
}
}
class ClickNo implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
frame.dispose();
nextFrame.dispose();
}
}
//CREATING BUTTONS & LABELS
JLabel WLT;
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 3;
JLabel title = new JLabel("Would you like to play again?");
if (isWin() == 1)
{
WLT = new JLabel("YOU WON!");
panel.add(WLT,c);
}
else if (isWin() == 2)
{
WLT = new JLabel("YOU LOST!");
panel.add(WLT,c);
}
else if (isWin() == 3)
{
WLT = new JLabel("YOU TIED!");
panel.add(WLT,c);
}
JLabel or = new JLabel("or");
JButton yes = new JButton("Yes");
ActionListener listener1 = new ButtonListener();
yes.addActionListener(listener1);
JButton no = new JButton("No");
ActionListener listener2 = new ClickNo();
no.addActionListener(listener2);
c.gridwidth = 0;
//1ST COLUMN
c.anchor = GridBagConstraints.LINE_END;
c.weighty = 10;
c.gridx = 0;
c.gridy = 2;
panel.add(no,c);
//2ND COLUMN
//adds "or"
c.anchor = GridBagConstraints.CENTER;
c.gridx = 1;
c.gridy = 2;
panel.add(or,c);
//adds title
c.weighty = 0;
c.gridwidth = 3;
c.gridx = 0;
c.gridy = 1;
panel.add(title,c);
//3RD COLUMN
c.gridwidth = 0;
c.weighty = 3; // changes weight
c.anchor = GridBagConstraints.LINE_START;
c.gridx = 2;
c.gridy = 2;
panel.add(yes,c);
nextFrame.pack();
nextFrame.setLocationRelativeTo(null);
nextFrame.setResizable(false);
nextFrame.setVisible(true);
nextFrame.toFront();
}
Here is the Source code for transparent JFrame:
public class Example extends JFrame {
public Example() {
super("TranslucentWindowDemo");
setLayout(new GridBagLayout());
setSize(500,300);
setLocationRelativeTo(null);
setUndecorated(true);
getContentPane().setBackground(Color.blue);
JButton Close = new JButton("Close");
add(Close);
ActionListener al;
al = new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
};
Close.addActionListener (al);
}
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
GroupLayout layout = new GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
pack();
}
public static void main(String args[]) {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
if (!gd.isWindowTranslucencySupported(TRANSLUCENT)) {
System.err.println("Translucency is not supported");
System.exit(0);
}
try {
for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Example.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
Example e = new Example();
e.setOpacity(0.55f);
e.setVisible(true);
}
});
}
}
For the Opacity, you can try Pane.setOpaque(false);
And for the contents you should change to setBackground(new Color(0, 0, 0, 0));
You can read more here

Java add buttons dynamically as an array [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
java - How would I dynamically add swing component to gui on click?
I want to add array of buttons dynamically.
I tried like this:
this.pack();
Panel panel = new Panel();
panel.setLayout(new FlowLayout());
this.add(panel);
panel.setVisible(true);
for (int i = 0; i < Setting.length; i++) {
for (int j = 0; j < Setting.width; j++) {
JButton b = new JButton(i+"");
b.setSize(30, 30);
b.setLocation(i * 30, j * 30);
panel.add(b);
b.setVisible(true);
}
}
but didn't get anything , what mistake did I make?
Edit
I have jFrame class "choices" on it i have a button , when I press the button, this is supposed to happen:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
structure.Setting s = new Setting(8, 8, 3, 1, 1);
Game g = new Game();
g.setSetting(s);
this.dispose();
g.show();
}
then i go to the Game class (also jFrame class) to the function setSetting and it is like this:
void setSetting(Setting s) {
this.setting = s;
structure.Game game = new structure.Game(setting);
JPanel panel = new JPanel(new GridLayout(5, 5, 4, 4));
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
JButton b = new JButton(String.valueOf(i));
panel.add(b);
}
}
add(panel);
pack();
setVisible(true);
}
structure.Setting setting;
}
You may use GridLayout to add equal height/width buttons:
public class Game extends JFrame {
private JPanel panel;
public Game(int rows,int cols,int hgap,int vgap){
panel=new JPanel(new GridLayout(rows, cols, hgap, vgap));
for(int i=1;i<=rows;i++)
{
for(int j=1;j<=cols;j++)
{
JButton btn=new JButton(String.valueOf(i));
panel.add(btn);
}
}
add(panel);
pack();
setVisible(true);
}
}
and code in button's handler should be:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Game g = new Game(5,5,3,3);
}
Note that you can also pass Setting object reference via Game constructor (when you may add widgets dynamically) instead of calling setSetting method.
The JPanel is already under the control of a layout manager, setting the size and position of the buttons is irrelevant, as they will changed once the panel is validated.
Try, instead, adding the panel AFTER you've populated it with buttons..
UPDATED with Example
Without further evidence, we are only guessing...You now have two people who have no issues.
Panel panel = new Panel();
for (int i = 0; i < Setting.length; i++) {
for (int j = 0; j < Setting.width; j++) {
jButton b = new jButton(i + "");
panel.add(b);
}
}
this.add(panel);
public class BadBoy {
public static void main(String[] args) {
new BadBoy();
}
public BadBoy() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
int buttonCount = (int) Math.round(Math.random() * 20);
int columnCount = (int) Math.round(Math.random() * 20);
JPanel buttonPane = new JPanel(new GridLayout(0, columnCount));
for (int i = 0; i < buttonCount; i++) {
JButton b = new JButton(i + "");
buttonPane.add(b);
}
frame.add(buttonPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ButtonPane extends JPanel {
public ButtonPane() {
}
}
}
I am guessing that this extens or is some kind of frame?
First step is to pack the frame by doing this.pack(); sets the frame size ti just fit all objects.
I assume you have set it to visible?
Now you should be able to see the buttons.
If you want a different layout use panel.setLayout(new SomeLayout);
Try to use setBounds(x,y,width,heigth) method
setBound method
for (int i = 0; i < 1; i++) {
for (int j = 0; j <1; j++) {
JButton b = new JButton("button");
b.setBounds(500, 500, 100, 20);
this.add(b);
}
}
this.repaint();
this.validate()

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());
}
}
}

Radio button issue

So for this class in java, here is my code
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
import javax.swing.border.*;
public class RadioSelection extends JFrame implements ActionListener
{
private ActionListener action;
private JButton[][] button;
private JPanel bottomPanel;
private LineBorder lineBorder;
private int randomRowLimit;
private int randomColumnLimit;
private Random random;
private int size;
JLabel label = new JLabel("Select the no. of Grid");
public RadioSelection()
{
randomRowLimit = 0;
randomColumnLimit = 0;
random = new Random();
size = 0;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
lineBorder = new LineBorder(Color.BLUE.darker());
JPanel topPanel = new JPanel();
topPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
bottomPanel = new JPanel();
final JRadioButton threeSquareButton = new JRadioButton("3 X 3", false);
final JRadioButton fourSquareButton = new JRadioButton("4 X 4", false);
final JRadioButton fiveSquareButton = new JRadioButton("5 X 5", false);
threeSquareButton.setBorder(lineBorder);
fourSquareButton.setBorder(lineBorder);
fiveSquareButton.setBorder(lineBorder);
label.setFont(null);
action = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
if (ae.getSource() == threeSquareButton)
{
remove(bottomPanel);
bottomPanel = getCenterPanel(3);
add(bottomPanel, BorderLayout.CENTER);
}
else if (ae.getSource() == fourSquareButton)
{
remove(bottomPanel);
bottomPanel = getCenterPanel(4);
add(bottomPanel, BorderLayout.CENTER);
}
else if (ae.getSource() == fiveSquareButton)
{
remove(bottomPanel);
bottomPanel = getCenterPanel(5);
add(bottomPanel, BorderLayout.CENTER);
}
invalidate(); // If you are using JDK 1.7 +
//getContentPane().revalidate(); // if you using JDK 1.6 or lower
repaint();
}
};
threeSquareButton.addActionListener(action);
fourSquareButton.addActionListener(action);
fiveSquareButton.addActionListener(action);
ButtonGroup bg = new ButtonGroup();
bg.add(threeSquareButton);
bg.add(fourSquareButton);
bg.add(fiveSquareButton);
topPanel.add(label);
topPanel.add(threeSquareButton);
topPanel.add(fourSquareButton);
topPanel.add(fiveSquareButton);
add(topPanel, BorderLayout.PAGE_START);
add(bottomPanel, BorderLayout.CENTER);
setSize(300, 300);
//pack();
setVisible(true);
}
private JPanel getCenterPanel(int size)
{
JPanel bottomPanel = new JPanel(new GridLayout(size, size));
button = new JButton[size][size];
this.size = size;
for (int row = 0; row < size; row++)
{
for (int column = 0; column < size; column++)
{
button[row][column] = new JButton();
button[row][column].setBorder(lineBorder);
button[row][column].setMargin(new Insets(2, 2, 2, 2));
button[row][column].addActionListener(this);
bottomPanel.add(button[row][column]);
}
}
randomRowLimit = random.nextInt(size);
randomColumnLimit = random.nextInt(size);
button[randomRowLimit][randomColumnLimit].setText("mouse");
return bottomPanel;
}
public void actionPerformed(ActionEvent ae)
{
JButton button = (JButton) ae.getSource();
if ((button.getText()).equals("mouse"))
{
randomRowLimit = random.nextInt(size);
randomColumnLimit = random.nextInt(size);
System.out.println("Row : " + randomRowLimit);
System.out.println("Column : " + randomColumnLimit);
button.setText("");
this.button[randomRowLimit][randomColumnLimit].setText("mouse");
}
else
{
JOptionPane.showMessageDialog(this, "Catch the mouse!", "Small Game : ", JOptionPane.ERROR_MESSAGE);
}
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new RadioSelection();
}
});
}
}
This one is working but if you notice, I used invalidate(); here. If it is revalidate();, it will not run. However, my concern here is when a radio-button is clicked (e.g 3x3), the button will not show automatically. The frame should be adjusted first before the gird buttons appear. How can I work with this one?
Try your hands on this code :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class RadioSelection extends JFrame
{
private ActionListener action;
private JPanel bottomPanel;
private LineBorder lineBorder ;
public RadioSelection()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
lineBorder = new LineBorder(Color.BLUE.darker());
JPanel topPanel = new JPanel();
topPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
bottomPanel = new JPanel();
final JRadioButton threeSquareButton = new JRadioButton("3 X 3", false);
final JRadioButton fourSquareButton = new JRadioButton("4 X 4", false);
threeSquareButton.setBorder(lineBorder);
fourSquareButton.setBorder(lineBorder);
action = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
if (ae.getSource() == threeSquareButton)
{
remove(bottomPanel);
bottomPanel = getCenterPanel(3);
add(bottomPanel, BorderLayout.CENTER);
}
else if (ae.getSource() == fourSquareButton)
{
remove(bottomPanel);
bottomPanel = getCenterPanel(4);
add(bottomPanel, BorderLayout.CENTER);
}
revalidate(); // If you are using JDK 1.7 +
// getContentPane().revalidate(); // if you using JDK 1.6 or lower
repaint();
}
};
threeSquareButton.addActionListener(action);
fourSquareButton.addActionListener(action);
ButtonGroup bg = new ButtonGroup();
bg.add(threeSquareButton);
bg.add(fourSquareButton);
topPanel.add(threeSquareButton);
topPanel.add(fourSquareButton);
add(topPanel, BorderLayout.PAGE_START);
add(bottomPanel, BorderLayout.CENTER);
setSize(300, 300);
setVisible(true);
}
private JPanel getCenterPanel(int size)
{
JPanel bottomPanel = new JPanel(new GridLayout(size, size));
for (int row = 0; row < size; row++)
{
for (int column = 0; column < size; column++)
{
JButton button = new JButton("Button " + row + " " + column);
button.setBorder(lineBorder);
button.setMargin(new Insets(2, 2, 2, 2));
bottomPanel.add(button);
}
}
return bottomPanel;
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new RadioSelection();
}
});
}
}
Here is the output of this :
and
Added this new code to answer a new thing :
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
import javax.swing.border.*;
public class RadioSelection extends JFrame implements ActionListener
{
private ActionListener action;
private JButton[][] button;
private JPanel bottomPanel;
private LineBorder lineBorder;
private int randomRowLimit;
private int randomColumnLimit;
private Random random;
private int size;
public RadioSelection()
{
randomRowLimit = 0;
randomColumnLimit = 0;
random = new Random();
size = 0;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
lineBorder = new LineBorder(Color.BLUE.darker());
JPanel topPanel = new JPanel();
topPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
bottomPanel = new JPanel();
final JRadioButton threeSquareButton = new JRadioButton("3 X 3", false);
final JRadioButton fourSquareButton = new JRadioButton("4 X 4", false);
final JRadioButton fiveSquareButton = new JRadioButton("5 X 5", false);
threeSquareButton.setBorder(lineBorder);
fourSquareButton.setBorder(lineBorder);
fiveSquareButton.setBorder(lineBorder);
action = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
if (ae.getSource() == threeSquareButton)
{
remove(bottomPanel);
bottomPanel = getCenterPanel(3);
add(bottomPanel, BorderLayout.CENTER);
}
else if (ae.getSource() == fourSquareButton)
{
remove(bottomPanel);
bottomPanel = getCenterPanel(4);
add(bottomPanel, BorderLayout.CENTER);
}
else if (ae.getSource() == fiveSquareButton)
{
remove(bottomPanel);
bottomPanel = getCenterPanel(5);
add(bottomPanel, BorderLayout.CENTER);
}
revalidate(); // If you are using JDK 1.7 +
// getContentPane().revalidate(); // if you using JDK 1.6 or lower
repaint();
}
};
threeSquareButton.addActionListener(action);
fourSquareButton.addActionListener(action);
fiveSquareButton.addActionListener(action);
ButtonGroup bg = new ButtonGroup();
bg.add(threeSquareButton);
bg.add(fourSquareButton);
bg.add(fiveSquareButton);
topPanel.add(threeSquareButton);
topPanel.add(fourSquareButton);
topPanel.add(fiveSquareButton);
add(topPanel, BorderLayout.PAGE_START);
add(bottomPanel, BorderLayout.CENTER);
setSize(300, 300);
//pack();
setVisible(true);
}
private JPanel getCenterPanel(int size)
{
JPanel bottomPanel = new JPanel(new GridLayout(size, size));
button = new JButton[size][size];
this.size = size;
for (int row = 0; row < size; row++)
{
for (int column = 0; column < size; column++)
{
button[row][column] = new JButton();
button[row][column].setBorder(lineBorder);
button[row][column].setMargin(new Insets(2, 2, 2, 2));
button[row][column].addActionListener(this);
bottomPanel.add(button[row][column]);
}
}
randomRowLimit = random.nextInt(size);
randomColumnLimit = random.nextInt(size);
button[randomRowLimit][randomColumnLimit].setText("X");
return bottomPanel;
}
public void actionPerformed(ActionEvent ae)
{
JButton button = (JButton) ae.getSource();
if ((button.getText()).equals("X"))
{
randomRowLimit = random.nextInt(size);
randomColumnLimit = random.nextInt(size);
System.out.println("Row : " + randomRowLimit);
System.out.println("Column : " + randomColumnLimit);
button.setText("");
this.button[randomRowLimit][randomColumnLimit].setText("X");
}
else
{
JOptionPane.showMessageDialog(this, "Please Click on X Mark to follow it.", "Small Game : ", JOptionPane.ERROR_MESSAGE);
}
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new RadioSelection();
}
});
}
}
I'm not sure I understand the question or the code, but I'd expect to see an ActionListener on the 3x3 button that would create an array of JRadioButton instances using a method that's something like this:
private JRadioButton [][] createRadioButtonArray(int squareSize) {
JRadioButton [][] arrayOfButtons = new JRadioButton[squareSize][squareSize];
for (int i = 0; i < squareSize; ++i) {
for (int j = 0; j < squareSize; ++j) {
arrayOfButtons[i][j] = new JRadioButton("button" + i + "," + j,false);
}
}
return arrayOfButtons;
}

Categories