I'm Writing a game where there are a set of islands and there are 5 workers on each island when i left click on a worker a cursor appears on it and when i right click on somewhere in the island the selected worker moves there..i want a JPanel to show on the right side of the screen every time i left click on a worker.the panel will show the workers stats such as Health and carrying weight but the problem is i can't make the panel appear.this is the code where i left click on a worker:
if(SwingUtilities.isLeftMouseButton(e)){
if(canSelect){
for (int j = 0; j < countries.size(); j++) {
for (int i = 0; i < countries.elementAt(j).getMen().size(); i++) {
if(m==countries.elementAt(j).getMen().elementAt(i).getX() && n==countries.elementAt(j).getMen().elementAt(i).getY()) {
countries.elementAt(j).getMen().elementAt(i).setY(countries.elementAt(j).getMen().elementAt(i).getY()+1);
countries.elementAt(j).getMen().elementAt(i).setSelected(true);
getGraphics().drawImage(arrow.getImage(), (countries.elementAt(j).getMen().elementAt(i).getX()+mapX)*20+5,(countries.elementAt(j).getMen().elementAt(i).getY()+mapY)*20-12,null);
canSelect = false;
}
}
}
}
}
I tried the below code on a jbutton click within JFrame and it didn't worked as expected. (that is to dynamically creating a panel with 2 labels and show in a JFrame)
JPanel p = new JPanel();
p.setLayout(new GridLayout(2, 1));
p.add(new JLabel("Health : 90%"));
p.add(new JLabel("Carrying weight : 4 Kg"));
this.add(p); //JFrame
p.setSize(100, 50);
p.setLocation(100, 100);
p.setVisible(true);
But adding the code this.validate(); at the end of the above code, it worked fine.
if, is this your problem, then it may help you.
Reference Link
May be your JPanel is created by below your existing JPanel so it can't be seen. Place your new JPanel on your existing JPanel . Like this
JPanel nPanel = new JPanel();
nPanel.setBounds(x,y,w,h); //your desired location and size
mainPanel.add(nPanel);
nPanel.setVisible(false);
Your can make it visible again with your event
Related
I have a JPanel in a JScrollPane, and the JPanel contains many small JPanels. But the default position of scrollbar is not at the top, thus the small JPanels isn't shown from the first one. How to let scrollbar's default position be at top?
My code is simplified and looks like this:
JFrame resultFrame = new JFrame("Searching Result");
JPanel listPanel = new JPanel();
listPanel.setLayout(new BoxLayout(listPanel, BoxLayout.Y_AXIS));
for (int i=0; i<5; i++) {
listPanel.add(smallPanel) // smallPanel is created in another class, which is related to i.
}
JScrollPane scrollPanel = new JScrollPane(listPanel);
scrollPanel.setPreferredSize(new Dimension(500, 750));
resultFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
resultFrame.setContentPane(scrollPanel);
resultFrame.pack();
resultFrame.setLocationRelativeTo(null);
resultFrame.setVisible(true);
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));
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
I am trying to position 2 JButtons under a grid of 9x9, but when I add the buttons, the grid is changed to accomodate the buttons, placing everything, including the buttons in a rectangle.
What i want is to have a grid and two buttons below the grid itself.
mainPanel.setBorder(BorderFactory.createLineBorder(Color.black, BORDER_WIDTH));
mainPanel.setLayout(new GridLayout(3, 3));
for (int i = 0; i < subPanels.length; i++)
{
for (int j = 0; j < subPanels[i].length; j++)
{
subPanels[i][j] = new JPanel(new GridLayout(3, 3));
subPanels[i][j].setBorder(
BorderFactory.createLineBorder(Color.black, BORDER_WIDTH));
mainPanel.add(subPanels[i][j]);
}
}
buttonPanel.add(clear);
buttonPanel.add(solve);
buttonPanel.setLayout(new GridLayout(1,1));
mainPanel.add(buttonPanel);
The buttonPanel is what is supposed to be under the mainPanel..
The easiest thing is probably to put your mainPanel into the center of a BorderLayout, and then put the buttonPanel in the south.
Also, you're currently setting the GridLayout for your buttonPanel to 1 row x 1 column. You should probably set the layout before adding the buttons, and set it to 1 row x 2 columns.
Every component on a form has a parent. If you place button1 on form1, button1.parent will be 'form1'.
change the parent of the buttons you want to the appropriate parent
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.