Java JFrame refuses to refresh - java

I am making a monopoly game in Java and for some reason I cant seem to get this JFrame popup to refresh. When I click the button, the popup will appear, but when I close it and click it again later on it the game, it continues to show the features of the 1st JFrame. I assume that a totally new JFrame is created every time you click the button, but I cant seem to refresh the content. How do I fix this?
final static JButton tradeButton = new JButton("Click to Trade Property");
tradeButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0){
final JPanel tradePanelcombo = new JPanel();
for(int x = 1; x< Player.Props.size(); x++)
{
if(x != Player.CurrentPlayer)
{
ArrayList<Property> props = Player.Props.get(x);
ArrayList<String> propnames = new ArrayList<String>();
for(Property prop : props)
{
propnames.add(prop.getName());
}
String[] strings = new String[propnames.size()];
for (int y = 0; y<propnames.size(); y++)
{
strings[y] = propnames.get(y);
}
JLabel confirmLabel = new JLabel("Player :" + x);
JComboBox petList = new JComboBox(strings);
petList.setPreferredSize(new Dimension(100, 150));
tradeFrame.add(confirmLabel);
tradePanelcombo.add(petList);
}
}
tradeFrame.add(tradePanelcombo, BorderLayout.PAGE_END);
tradeFrame.setPreferredSize(new Dimension(500,500));
tradeFrame.setResizable(true);
tradeFrame.pack();
tradeFrame.setVisible(true);
}
});

It appears to me that a new frame and components are created every time.
So, if the frame doesn't update, then I guess it would be because your Properties are not updated so the data added to the components doesn't change.
Edit:
You need to create a new JFrame every time, or you need to remove all the old components from the frame before adding the new components.
When you add a component to a BorderLayout, the previous component doesn't get removed. So you actually have two components in the container. When Swing paints components it actually paints the components in the reverse order that they where added to the container (this is how Z-Ordering works).
If you remove the setResizable() method, and then resize the frame I believe you should see the new components start to show given that they should increase in size as the frame size increases.

Related

JPanel(null) not displaying JLabels

I am adding JLabels from an Arraylist to a JPanel and they will only display if i set a layout on the panel but i want to set the location of the labels myself when i try panel = new JPanel(null); all labels are not displayed.
Frame:
public static void Frame(){
panel = new JPanel(null);
JFrame frame = new JFrame("New");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.pack();
frame.setSize(400,400);
frame.add(panel);
}
ArrayList iteration that adds labels to panel
private static void printArray() {
for(int i = 0; i < food.size(); i++){
component = new JLabel(new Food(food.get(i).getColor(),
food.get(i).getIconHeight(), food.get(i).getIconWidth(),
food.get(i).getLocationX(), food.get(i).getLocationY()));
panel.add(component);
component.setLocation(food.get(i).getLocationX(),
food.get(i).getLocationY());
}
}
I can see from Debug it is definitely getting the location information, so why is it not putting it in this location.
The reason to set layout as null is so i can update the position of the label so i can "move" it around with keyboard input
The first thing you need to do is understand what job the layout manager actually does, because if you're going to remove it, you're going to need to take over it's work.
Layout managers are responsible for determining both the size and position of the components. They do this through a variety of means, but can make use of the getPreferred/Minimum/MaximumSize methods of the components.
So this would suggest you need to make your own determinations about these values, for example...
component = new JLabel(new Food(food.get(i).getColor(),
food.get(i).getIconHeight(), food.get(i).getIconWidth(),
food.get(i).getLocationX(), food.get(i).getLocationY()));
component.setSize(component.getPreferredSize());
component.setLocation(food.get(i).getLocationX(), food.get(i).getLocationY());
I'd also recommend using the Key Bindings over KeyListener, it doesn't suffer from the same focus related issues

How to drag and drop an image from label to label?

I'm new in using the DnD in java.I'm trying to drag an drop an image from a label to another. The first label is the source, the second is the destination. My trouble is that I need to drag the image from the source and recognize that i'm dropping on the correct destination; if the destination is correct the image from the source must disappear, else must come back to the source and notify it to the user using a window message or just a System.out.println(). I've tried using TransferHandler, DragSource, but I didn't get a single good result.
How to drag and drop an image from label to label?
The Drag Listener
public class DragMouseAdapter extends MouseAdapter {
public void mousePressed(MouseEvent e) {
JComponent c = (JComponent) e.getSource();
TransferHandler handler = c.getTransferHandler();
handler.exportAsDrag(c, e, TransferHandler.COPY);
}
}
The Source labels that contain the images
public ShipsGUI() {
// setBorder(new EmptyBorder(10,10,10,10));
setLayout(new GridLayout(2, 5));
MouseListener listener = new DragMouseAdapter();
for (int i = 0; i < 10; i++) {
JPanel p = new JPanel(new BorderLayout(5, 0));
JLabel a = new JLabel(ship,JLabel.CENTER);
a.setName("ship");
JLabel n = new JLabel("[" + Integer.toString(i + 1) + "]");
n.setForeground(Color.BLUE);
// a.setBorderPainted(false);
// a.setBackground(Color.white);
// a.setOpaque(true);
//a.setIcon(ship,JLabel.CENTER);
a.setTransferHandler(new TransferHandler("icon"));
a.addMouseListener(listener);
p.add(a);
p.add(n, BorderLayout.LINE_START);
add(p);
}
}
The destination (it's a grid fo labels)
public NewAreaGioco(int r,int c, boolean enable){
this.setLayout(new GridLayout(r,c,1,1));
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
JLabel l= new JLabel(" ");
l.setSize(30, 30);
l.setBorder(BorderFactory.createLineBorder(Color.BLUE));
if(enable)l.setTransferHandler(new TransferHandler("icon"));
add(l);
}//fine for
}//fine for
}
Well, you can't use the default TransferHandler class. You need to make your own.
I would start by looking at the DropDemo and ListTransferHandler class found on the examples page of the Drag and Drop tutorial.
A couple of change that I think you will need to make:
export an image instead of text. I think the link provided by Sergiy above might help.
The key point is in the exportDone(...) method. Your cleanup code would set the icon of the source component to null.
You will probably need to read the tutorial to understand the concept of these two classes.

Creating Square Buttons in Swing

I would like to create something like the following in Swing:
The top part is relatively easy: I can just create a table and display it. What I'm having trouble with is the square plus and minus buttons at the bottom, which are designed to add a new item or remove the selected item respectively. In particular, I haven't been able to make the square shape because on Mac OS X and some other platforms, JButtons are rectangles with rounded corners and I can't find a way to change that. Also, I'm wanting to make sure it's a perfect square and without any space in between buttons.
How can this be accomplished in a cross-platform way on Swing?
JButtons are rectangles with rounded corners and I can't find a way to change that.
Change the Border:
button.setBorder( new LineBorder(Color.BLACK) );
Edit.
Another approach is to create your own icon from an existing button. Something like the following:
JButton button = new JButton("+");
Dimension size = button.getPreferredSize();
size.x += 6;
size.y += 6;
button.setPreferredSize(size);
Rectangle rectangle = new Rectangle(3, 3, size.x - 3, size.y - 3);
ScreenImage buttonImage = ScreenImage(button, rectangle);
ImageIcon icon = new ImageIcon(buttonImage);
JButton plus = new JButton(icon);
plus.setBorder( ... );
The above code should create an image of your button on any platform. I increased the preferred size to avoid taking an image of the border.
You will need to use the Screen Image class.
This is most easily achieved by returning a preferred size that is NxN - where N is the larger of preferred width or height.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
class SquareButton extends JButton {
SquareButton(String s) {
super(s);
}
#Override
public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
int s = (int)(d.getWidth()<d.getHeight() ? d.getHeight() : d.getWidth());
return new Dimension (s,s);
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
JComponent gui = new JPanel(new FlowLayout());
for (int ii=0; ii<5; ii++) {
gui.add(new SquareButton("" + ii));
}
gui.setBorder(new EmptyBorder(4, 8, 4, 8));
JFrame f = new JFrame("Square Buttons");
f.add(gui);
// Ensures JVM closes after frame(s) closed and
// all non-daemon threads are finished
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// See http://stackoverflow.com/a/7143398/418556 for demo.
f.setLocationByPlatform(true);
// ensures the frame is the minimum size it needs to be
// in order display the components within it
f.pack();
// should be done last, to avoid flickering, moving,
// resizing artifacts.
f.setVisible(true);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
You can set the size of a button using using setPreferredSize():
JButton button = new JButton("+");
button.setPreferredSize(new Dimension(10, 10));
You might be able to remove the rounded corners using:
button.setBorder(BorderFactory.createEmptyBorder());
If this does not work then you can override the paintComponent() method on JButton.
Well in order to make them square, you have 2 options: 1. Make the button hold an icon image of just a square image of a transparent image. 2. you could set the button dimensions on your own. I am not sure how to set the dimensions, but that is a an option you could choose. You can just create a JToolBar that is set on the BorderLayout.SOUTH end of the window whenever you add, and whatever buttons are added onto that, will be right next to each other. To add the buttons do this:
JButton button1 = new JButton("+");
JButton button2 = new JButton("-");
JToolBar toolbar = new JToolBar();
<JPanel,JFrame,Whatever>.add(toolbar, BorderLayout.SOUTH);
toolbar.add(button1);
toolbar.add(button2);
This will add the toolbar onto the JFrame, JPanel, or whatever you're adding it onto, and it will set it to the bottom of the screen as you see above.
Hope this helps!

Is there any 'top to bottom' and 'right to left' in boxlayout?

I have some tables which should draw from right to left and top to bottom at the frame. Right now I used absolute layout and working with coordination. Is there any BoxLayout or any other Java layout can do it? I should mention that the number of tables is dynamic.
My second question is how can I dock these tables to frame? I mean I want when the frame resize, tables keep their positions on the screen.
Most layout managers will respect the orientation of the component:
panel.setComponentOrientation( ComponentOrientation.RIGHT_TO_LEFT );
panel.add(...);
Or you can always just add the components to the beginning of the container
panel.add(component1, 0);
panel.add(component2, 0);
You may want to use a grid if you are arranging things into a table. All of the elements in a grid should be the same size.
To arrange some items vertically where the size of each row can vary, try this:
static JPanel buildPanel() {
JPanel vPanel = new JPanel();
BoxLayout layout = new BoxLayout(vPanel, BoxLayout.Y_AXIS);
vPanel.setLayout(layout);
JPanel[] rowPanels = new JPanel[5];
int counter=1;
for (int i = 0; i < rowPanels.length; i++) {
rowPanels[i] = new JPanel();
rowPanels[i].setLayout(new FlowLayout(FlowLayout.LEFT, 2, 2));
rowPanels[i].add(new JButton("button " + counter++));
rowPanels[i].add(new JButton("Your button " + counter++));
rowPanels[i].add(new JButton("Shabutton"));
vPanel.add(rowPanels[i]);
}
return vPanel;
}
public static void main(String[] args) {
JFrame gridFrame = new JFrame();
gridFrame.add(buildPanel() );
gridFrame.pack();
gridFrame.setVisible(true);
}
You can prevent the whole JFrame from resizing using gridFrame.setResizable(false);
You can prevent sapce from being added between the rows when the window is resized with a method call like this:
rowPanels[i].setMaximumSize(new Dimentsion(400,32));

Repainting JPanels (or JFrames?) after user input?

I'm currently programming a Calendar in Java. The Calendar itself fills out perfectly fine with the Month and Year being displayed in JComboBoxes above the grid below it. The Grid itself is full of empty JLabels or JButtons (for the days of the month). The JComboBoxes are linked to ActionListeners, which detect the user changing information (confirmed by System.out.print statements). However, I cannot find a way to "redraw" the JPanel after this occurs. The method being called completely creates a new JPanel and adds in the new JLabels/JButtons, but nothing on the JFrame is updated after this happens. I have attempted using both the repaint and revalidate on the whole JPanel (which includes the JComboBoxes and the grid below it in a BorderLayout), the JPanel with only the grid, and the JFrame, but nothing happens. Does anyone have any ideas what is wrong?
// This code is within the build() method that builds the GUI.
// This method adds the centerPanel into the mainPanel
yearChoice.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
int i = yearChoice.getSelectedIndex();
if (i >= 0) {
yy = Integer.parseInt(yearChoice.getSelectedItem()
.toString());
//System.out.println("Year=" + yy);
compute();
}
}
});
private void compute(){
elements = new int[6][7];
// OMITTED is the code that determines whether a cell in the array should be an empty
// JLabel or a JButton. This code is based on the Calendar, and does work properly,
// but I can't figure out how to get the new Month/Year to show up on a new Panel
centerPanel = new JPanel(new GridLayout(7, 7));
JLabel sunday = new JLabel("S"),
monday = new JLabel("M"),
tuesday = new JLabel("T"),
wednesday = new JLabel("W"),
thursday = new JLabel("Th"),
friday = new JLabel("F"),
saturday = new JLabel("S");
centerPanel.add(sunday);
centerPanel.add(monday);
centerPanel.add(tuesday);
centerPanel.add(wednesday);
centerPanel.add(thursday);
centerPanel.add(friday);
centerPanel.add(saturday);
for(int i = 0; i < 6; i++){
for(int j = 0; j < 7; j++){
if(elements[i][j] == -1){
centerPanel.add(new JLabel(" "));
}else{
centerPanel.add(new JButton("" + elements[i][j]));
}
}
}
// Here is where I attempt to repaint the centerPanel for the JPanel, but it
// doesn't work
}
The method being called completely creates a new JPanel and adds in the
new JLabels/JButtons, but nothing on the JFrame is updated after this
happens. I have attempted using both the repaint and revalidate on the
whole JPanel (which includes the JComboBoxes and the grid below it in
a BorderLayout), the JPanel with only the grid, and the JFrame, but
nothing happens. Does anyone have any ideas what is wrong?
you call another JPanel for (re)validate & repaint
updates are out of visible rectangle on the screen, put JPanel to the JScrollPane
if updates are out of visible rectangle you can to call JFrame.pack(), but in this case JFrame will be changed its Dimension on the screen
The method being called completely creates a new JPanel and adds in
the new JLabels/JButtons, but nothing on the JFrame is updated after
this happens.
for why reason you re_create a JPanel, create that once time and to play with setVisible(false/true)
don't re_create a JPanel, put these (two or three JPanels) to the CardLayout, then any changes will be only switch betweens views
for better help sooner post an SSCCE, short, runnable, compilable
code example

Categories

Resources