I am working on a little card game and I have been having some trouble: when I try to add dynamic components to my JLayeredPane it does not display them.
I have a custom component that represents a card and I want to display 2 of them in a layered fashion. For that I have the following class:
public class PairView extends JPanel {
private JLayeredPane layeredPane;
private CardView attackCard;
private CardView defenceCard;
private static Point origin = new Point(0, 0);
private static int offset = 10;
public PairView() {
}
public PairView(Card attackCard) {
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
layeredPane = new JLayeredPane();
layeredPane.setPreferredSize(new Dimension(120, 170));
this.defenceCard = null;
this.attackCard = new CardView(attackCard);
this.attackCard.setOpaque(true);
this.attackCard.setForeground(Color.black);
this.attackCard.setBorder(BorderFactory.createLineBorder(Color.black));
this.attackCard.setBounds(origin.x, origin.y, 100, 150);
layeredPane.add(this.attackCard, 0);
this.origin.x += offset;
this.origin.y += offset;
}
public void addDefenceCard(Card defenceCard) throws DurakException {
if (this.defenceCard == null) {
this.defenceCard = new CardView(defenceCard);
this.defenceCard.setOpaque(true);
this.defenceCard.setForeground(Color.black);
this.defenceCard.setBorder(BorderFactory.createLineBorder(Color.black));
this.defenceCard.setBounds(origin.x, origin.y, 100, 150);
layeredPane.add(this.defenceCard, 1);
} else {
throw new DurakException("A defence Card is already present");
}
}
I tested this via the drag and drop interface in NetBeans and I have the following problem:
From what I understand, the default constructor is always called, so when I create 2 random CardView components and add them to the layered pane in the default constructor the parent JFrame display them just fine.
If I use the overwritten constructor or try to add another component (like the addDefenceCard method) it does not display the added component.
calling revalidate() or repaint() isn't doing anything.
How to get the components to show?
Your class extend JPanel, but you never add any components to the panel so there is nothing to display.
You need to add the JLayeredPane to the panel:
layeredPane = new JLayeredPane();
this.add( layeredPane );
I don't know if you need the set the layout to a BoxLayout. The default FlowLayout of the panel will respect the preferredSize of any component added to it.
this.attackCard.setOpaque(true);
this.attackCard.setForeground(Color.black);
this.attackCard.setBorder(BorderFactory.createLineBorder(Color.black));
You may want to consider setting these properties in the constructor of the CardView class. That way the default properties are set in one place and can easily be changed.
Instead of using a layered pane you may want to consider using the Overlap Layout. It was designed to support the requirement of overlapping components.
Related
I have an application where I use two JPanels. One of them is a PaintPanel. The second panel,the jtextfield and the jtextarea work fine but they look too cramped against the right side. I tried changing the sizes with setSize() but it didn't work.
The code for the paintpanel
public void center() {
jpCenter = new PaintPanel();
jpCenter.addMouseListener(this);
jpCenter.setSize(100, 100);
jpCenter.setBackground(Color.white);
add(jpCenter, BorderLayout.CENTER);
}
The code for the panel of the chatbox
public void east() {
// CREATE EAST Panel
gl = new GridLayout(4, 1);
jpEast = new JPanel();
jpEast.setSize(200, 200);
jpEast.setLayout(gl);
jpEast.setBackground(Color.white);
label = new JLabel("Number of shapes: ");
jpEast.add(label);
// ADD TEXT FIELD
jtf = new JTextField();
jtf.setText("");
jtf.setSize(200, 200);
jpEast.add(jtf);
// ADD BUTTON
jbSend = new JButton("Send");
jbSend.setEnabled(false);
jbSend.setSize(20, 60);
jpEast.add(jbSend);
jbSend.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
send(jtf.getText());
jtf.setText("");
}
});
// ADD TEXT AREA
jta = new JTextArea("");
jta.setSize(100, 100);
jpEast.add(jta);
// ADD EAST panel
add(jpEast, BorderLayout.EAST);
}
Avoid setting the size of components since it can make them not work well on all platforms, and with JTextArea in particular, it will not allow it to expand correctly if held within a JScrollPane (which is where a JTextArea belongs). Note also that most layout managers don't even respect a component's size but rather its preferred size.
Instead, set the row and column properties of your JTextAreas (done most easily via the JTextArea(int row, int column) constructor), the column property of your JTextField, the font sizes of other components (if need be). Then allow your container (JPanel) layout managers and component's own preferred sizes size all appropriately when you call pack() on your top-level window (often a JFrame), after adding all components but before setting it visible.
For more specific help, consider posting an image of the GUI you're getting vs. the one you're trying to achieve.
After a lot of research I only could get that board image with using label. Now I cannot change it's position. I tried a lot of functions. What is the exact function do I need
public class Board extends JFrame {
private ImageIcon image;
private JLabel label;
public Board() {
image = new ImageIcon(getClass().getResource("board.png"));
label = new JLabel(image);
label.setLocation(200, 0); //This is the one that I expected to do the thing
add(label);
}
public static void main(String [] args) {
Board b = new Board();
b.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b.setVisible(true);
b.setSize(1280, 1000);
}
}
Don't try to manually set the location of a component. Swing was designed to be used with layout managers. Read the section from the Swing tutorial on Using Layout Managers for more information.
One way to position a component is to give the component a Border. So you could do something like:
label.setBorder( new EmptyBorder(200, 0, 0, 0) );
The tutorial also has a section on How to Use Borders.
First of all: you shouldn't move components manually. This should be left to the layoutmanager. But you can. The basic problem you're facing is - or atleast i think so - : you're board still has an layoutmanager set, which will continue to layout the board and due to this aswell move (and handle the size of) you're component. Just call setLayout(null); before positioning the label and specify the size and it should work.
I have a JPanel (myPanel) with a lot of button inside (this panel is contained in another panel that contain other components). I would insert this JPanel (myPanel) into a scroll to control better the button.
This is a part of my code:
JPanel firstPanel = new JPanel(null);
......
......
JPanel myPanel = new JPanel(null);
myPanel.setBounds(0, position+22, 400, 500);
for (int i=0; i<size; i++) {
JButton button = new JButton(myList.get(i));
if (counter%4 == 0) {
button.setBounds(270, 0+(4*i), 90, 18);
} else if (counter%3 == 0) {
button.setBounds(180, 4+(4*i), 90, 18);
} else if (counter%2 == 0) {
button.setBounds(90, 8+(4*i), 90, 18);
} else {
button.setBounds(0, 12+(4*i), 90, 18);
}
myPanel.add(bottone);
}
......
......
firstPanel.add(myPanel);
So, how can i do to insert it into a scroll?
Your question appears to ask about how to add a JPanel to a JScrollPane when the JPanel uses null layout, and the answer is easy:
First and foremost DON'T use a null layout. Use of null layouts almost guarantees that the component held by the JScrollPane won't scroll appropriately since the JScrollPane mechanics require the use of this.
Either this or you will be required to create a class that extends JPanel and implements the Scrollable interface, and this will require far more work, and completely unnecessary work.
Instead you really are forced to learn how to use and then use an appropriate mix of layout managers to have your JPanels hold and display their components. Note that you can nest JPanels, each using its own layout, thereby easily creating complex but easy to maintain GUI's. Please check the layout manager tutorial for more on this.
Adding a JPanel to a JScrollPane is easy. Either pass the JPanel into the JScrollPane's constructor: JScrollPane scrollpane = new JScrollPane(myPanel); or else pass the JPanel into the JScrollPane's viewport view via setViewportView(myPanel). Here's the JScrollPane tutorial for more on this, and the general Swing tutorials.
Whenever I set the panel's Layout to FlowLayout, the JTable appears, however my imageBackground and buttons are misplaced. And when I set the layout to null, the the table doesn't appear, but the buttons and imageBackground are where I wanted them to be. What am I'm going to do with this?
public class AssetPanel extends JPanel implements ActionListener{
private ArrayList<AssetDetails> assetList;
private Frame frame;
private Database db;
private JTable assetTable;
private JScrollPane scrollPane;
private JButton btnBack;
private JButton btnView;
public AssetPanel (Frame frame){
super();
this.frame = frame;
initialize();
}
public void initialize(){
setName("Assets");
setSize(700, 475);
setLayout(null);
setVisible(true);
db = new Database();
btnView = new JButton("View");
btnView.addActionListener(this);
btnView.setBounds(450, 400, 90, 20);
add(btnView);
btnBack = new JButton("Back");
btnBack.setFont(new Font("Tahoma", Font.BOLD, 12));
btnBack.setBounds(550, 400, 90, 20);
btnBack.addActionListener(this);
add(btnBack);
ImageIcon imageBackground = new ImageIcon(AssetPanel.class.getResource("/resources/assets.png"));
JLabel jlBackground = new JLabel(imageBackground);
jlBackground.setBounds(0,0, 700, 475);
add(jlBackground);
initializeTable();
}
#Override
public void actionPerformed(ActionEvent ae) {
if(ae.getSource() == btnBack){
frame.changePanel("Main Menu");
}
}
public void initializeTable(){
Object[][] assetData;
assetList = new ArrayList<>();
String[] columnNames = {"Asset Name", "Date Acquired", "Type", "Classification"};
assetList = db.getAssetTable();
assetData = new Object[assetList.size()][columnNames.length];
for(int i = 0; i < assetList.size(); i++){
assetData[i][0] = assetList.get(i).getAssetName();
assetData[i][1] = assetList.get(i).getDateAcquired();
assetData[i][2] = assetList.get(i).getType();
assetData[i][3] = assetList.get(i).getClassification();
}
assetTable = new JTable(assetData, columnNames);
assetTable.setPreferredScrollableViewportSize(new Dimension(400, 100));
assetTable.setLocation(150, 100);
assetTable.setFillsViewportHeight(true);
scrollPane = new JScrollPane(assetTable);
add(scrollPane);
}
}
Don't use a null layout or use the setBounds() method to position and size components.
however my imageBackground and buttons are misplaced
A background is a Container component. That is you create it as a component and paint an image as the background. Then you add other components to the background component. Now the image will appear in the background and the other components appear on top of it.
See the Background Panel to give an example of creating a background component.
On possible solution: I recommend switching to Mig Layout as a solution to all java layout problems. I now use it for the layout of every single container component in my apps. If you switch you'll probably be glad you did (will never again have problems like that listed in this question).
http://www.miglayout.com/
MigLayout may be included in the JDK in a future version of java.
null layouts mean you have to explicitly place all the components.
I recommend BoxLayout. it's really simple, and you can put in spacers to create space between objects, and glue to fill in all remaining space.
you can also nest the boxes, as well.
if you look at java sample code (and at the source for things);
they nest a lot of JPanels to get the complicated layouts.
Try adding this before trying the steps below if it does not work:
// Set your flow layout thus:
setLayout(new FlowLayout(FlowLayout.LEFT,5,5));
// Set your table Auto Resize Mode to OFF
assetTable.setAutoResizeMode(assetTable.AUTO_RESIZE_OFF);
EXTRA: Try if above tips does not help
Technically, your class should extend a JFrame.
Add a root layout to the class(i.e. the JFrame):
setLayout(new FlowLayout(FlowLayout.LEFT,5,5));
Create two panels; one should contain your label and buttons components.
The other should contain the JScrollPane that contains your table.
Both panels can have their Layout which determines how the components will be laid out.
You can use FlowLayout.
Then you can add both panels to the mother layout (JFrame).
Why my JFrame 'frame' is diplaying empty window, when it should give me 3 menu buttons and my own painted JComponent below ? What am I missing here ?
import java.awt.*;
import javax.swing.*;
public class Eyes extends JFrame {
public static void main(String[] args) {
final JFrame frame = new JFrame("Eyes");
frame.setPreferredSize(new Dimension(450, 300));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel players = new JPanel(new GridLayout(1, 3));
players.add(new JButton("Eyes color"));
players.add(new JButton("Eye pupil"));
players.add(new JButton("Background color"));
JPanel eyes = new JPanel();
eyes.add(new MyComponent());
JPanel content = new JPanel();
content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
content.add(players);
content.add(eyes);
frame.getContentPane();
frame.pack();
frame.setVisible(true);
}
}
class MyComponent extends JComponent {
public MyComponent(){
}
#Override
public void paint(Graphics g) {
int height = 120;
int width = 120;
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
BasicStroke bs = new BasicStroke(3.0f);
g2d.setStroke(bs);
g2d.setColor(Color.yellow);
g2d.fillOval(200, 200, height, width);
g2d.setColor(Color.black);
g2d.drawOval(60, 60, height, width);
}
}
Your line:
frame.getContentPane();
doesnt do anything but access the content pane of the frame. Instead of getting the content pane, you should set your content pane, like this:
frame.setContentPane(content);
EDIT:
alternatively, as #trashgod points out, you could use the getContentPane method to access the default content pane and add your content component to that:
frame.getContentPane().add(content);
I think you are attempting to use nested JPanels. This is certainly a way to organize your components, but downside to is the fact that it gets difficult to manage in some cases. You could try this snippet of code below. In the program you will find:
1) An array of JLabel
2) An array of JTextField
3) Nested JPanels
At the end of the program I use the Container to add the final product of these object to my Graphics Window.
The most efficient way I can think of is to define these components at the top of my program so that I can reuse them later as I need to.
To achieve this you can try this snippet of code:
import javax.swing.*; //Required to use Swing Components
public class TestGUI extends JFrame
{
JLabel[] label; //Define this with an array
JTextField[] textField; //Define this with an array as well
private int nLabels; //Number of labels preferred
private int nTextFields; //Number of text fields preferred
public testGUI(int amt)
{
//Assuming that you want equal amounts of each,
//set these two variables to the "ant" input parameter
nLabels = amt;
nTextFields = amt;
//Set component attributes
label = new JLabel[2]; //Label compared text fields
textField = new JTextField[2]; //Use two of these for comparison
textField[0].setEnabled(false); //Disabled editing
//Do nothing with the second text field
JPanel labels = new JPanel(); //Place JLabels here
//Use this to align the labels vertically
labels.setLayout(new GridLayout(2, 1));
//Use this for loop to add the labels to this JPanel
for(int i = 0; i < nLabels; i++)
{
labels.add(label[i]);
//You can also define and apply additional properties
//to labels inside this loop. TIP: You can do this in
//any loop
}
JPanel txtFields = new JPanel(); //Place JTextFields here
//Use this to align the text fields vertically
txtFields.setLayout(new GridLayout(2, 1));
//Use this for loop to add the labels to this JPanel
for(int i = 0; i < nTextFields; i++)
{
textFields.add(textField[i]);
//You can also define and apply additional properties
//to text fields inside this loop. TIP: You can do
//this in any loop
}
//Now we have the two components, you asked for help with, set up
//Next, we will need another JPanel to add these to panels to.
//This JPanel will be added to the JFrame Container
//You probably know how to run this via the "main" method
JPanel window = new JPanel();
//Place the JPanel for the labels and text fields
//This requires a horizontal grid
window.setLayout(new GridLayout(1, 2));
//Add the the two JPanels: "labels" and "txtFields"
window.add(labels);
window.add(txtFields);
//Define the Container object to set up the GUI
Container container = getContentPane();
//Apply the "window" JPanel object to the container
container.add(window, BorderLayout.CENTER);
//Center this in the Graphics Window when displayed
}
//Any other methods and/or functions can be added as well
//If they are, they must placed in the constructor method above
}
This is the approach that I would use when trying to go at making and manipulating my Graphics Windows that I write. Sometimes I write applets, but only after making sure that I have everything functioning properly in a plain Graphics Window.
I hope this helps.
If you have any other questions, just let me know and I will answer the to the best of my ability, thanks.