I am trying to make a JFrame with a 30px JPanel at the top, then add the Minecraft Applet underneath, Both need to resize automatically, I am trying to achieve this with a GridBagLayout, so far I have:
public void start(Applet mcApplet, String user, String session) throws MalformedURLException {
JLabel label = new JLabel();
Thread animation = new Thread();
Dimension size = new Dimension(900, 540);
JPanel basic = new JPanel(new GridBagLayout());
basic.setPreferredSize(size);
GridBagConstraints c = new GridBagConstraints();
// ADD MINEBOOK MENU
JLabel menu = new JLabel(new ImageIcon(new URL("http://modpacks.minebook.co.uk/images/menu.png")));
if(!animationname.equalsIgnoreCase("empty")) {
try {
animation.start();
label = new JLabel(new ImageIcon(animationname));
label.setBounds(0, 0, size.width, size.height);
fixSize(size);
getContentPane().setBackground(Color.black);
add(label);
animation.sleep(3000);
animation.stop();
} catch (Exception e) {
label.add(label);
} finally {
remove(label);
}
}
try {
appletWrap = new Launcher(mcApplet, new URL("http://www.minecraft.net/game"));
} catch (MalformedURLException ignored) { }
appletWrap.setParameter("username", user);
appletWrap.setParameter("sessionid", session);
appletWrap.setParameter("stand-alone", "true");
mcApplet.setStub(appletWrap);
mcApplet.setPreferredSize(size);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
c.ipady = 30;
basic.add(menu, c);
c.fill = GridBagConstraints.BOTH;
c.gridx = 0;
c.gridy = 1;
c.ipady = 0;
basic.add(appletWrap, c);
add(basic);
pack();
validate();
appletWrap.init();
appletWrap.start();
fixSize(size);
setVisible(true);
}
I suggest that you use a BorderLayout, and place your 30px panel in the NORTH position, while your Minecraft applet in the CENTER position.
Related
For a simple GUI I am currently making I want a design similar to this.
The blue and the green area are supposed to be just text and numbers.
The red area is supposed to be an image. Currently, I am creating scaled instances of an Image, create an ImageIcon out of this and then add this to a label to fit an image into different spaces.
The problem is, that without a width I can not create a scaled instance of the picture.
My current GridBagLayout code looks like this:
private static void createAndShowUI()
{
JFrame frame = new JFrame();
JLabel map = new javax.swing.JLabel();
JLabel data = new javax.swing.JLabel();
JLabel menu = new javax.swing.JLabel();
GridBagConstraints c;
frame = new JFrame("Risiko");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.getContentPane().setLayout(new GridBagLayout());
map.setText("MAP");
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.weightx = 0.75;
c.weighty = 0.75;
frame.getContentPane().add(map, c);
data.setText("DATA");
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 1;
c.weighty = 0.25;
frame.getContentPane().add(data, c);
menu.setText("MENU");
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 0;
c.gridheight = 2;
c.weightx = 0.25;
frame.getContentPane().add(menu, c);
frame.setVisible(true);
}
I create the three areas and now I want to create an image with the exact width and height of the red area.
So my question is, how can I get the width and height of the red area so I can create a scaled instance of the picture so that it fits into this area?
Test the dynamic layout of the following mre by resizing the frame.
The background image used as background for MapPane is resized to fill the JPanels width and height.
This is achieved by overriding paintComponent:
import java.awt.*;
import java.awt.image.*;
import java.net.URL;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class SwingTestPane extends JPanel {
public SwingTestPane() {
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.rowWeights = new double[]{0.75, .25};
gridBagLayout.columnWeights = new double[]{0.75, 0.25};
setLayout(gridBagLayout);
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.gridx = 0;
c.gridy = 0;
JPanel mapPane = new MapPane();
add(mapPane, c);
c.gridx = 0;
c.gridy = 1;
JLabel data = new javax.swing.JLabel("DATA");
JPanel dataPane = new JPanel();
dataPane.add(data);
dataPane.setBackground(Color.YELLOW);
dataPane.setOpaque(true);
add(dataPane, c);
c.gridx = 1;
c.gridy = 0;
c.gridheight = 2;
JLabel menu = new JLabel("MENU");
JPanel menuPane = new JPanel();
menuPane.add(menu);
menuPane.setBackground(Color.GREEN);
menuPane.setOpaque(true);
add(menuPane, c);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400,400);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
frame.getContentPane().add(new SwingTestPane());
frame.pack();
frame.setVisible(true);
}
}
class MapPane extends JPanel {
String imageUrlString = "https://findicons.com/files/icons/345/summer/128/cake.png";
BufferedImage image = null;
MapPane() {
URL url;
try {
url = new URL(imageUrlString);
image = ImageIO.read(url);
} catch (IOException ex) {
ex.printStackTrace();
}
}
#Override //Override to paint image as the background
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
}
}
My code is meant to but the JButton at the top but when I add a image it goes on top of the image which is good but instead of being at the top it is in the middle and you can't get a value for gridy so I don't know how to make it go to the top. I have got lots of buttons on the Container but I will just put the code for one to make it shorter but if you need full code I will provide it. Thank you Here is my code
public void add(Container pane){
setBackground(Color.black);
pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
URL resource = getClass().getResource("Graphitebackground.v2.jpg");
ImageIcon i2 = new ImageIcon(resource);
URL resource3 = getClass().getResource("Graphitebackground.v4.jpg");
ImageIcon i3 = new ImageIcon(resource3);
URL resource1 = getClass().getResource("Graphitebackground.v3.jpg");
ImageIcon i1 = new ImageIcon(resource1);
JLabel background = new JLabel(i2);
background.setSize(new Dimension(1000,1000));
background.setVisible(true);
background.setLayout(new GridBagLayout());
JButton button;
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
//natural height, maximum width
c.fill = GridBagConstraints.HORIZONTAL;
JButton label2 = new JButton(i1);
c.weightx = 0.5;
label2.setText("Level1");
label2.setPreferredSize(new Dimension(100,100));
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
label2.setForeground(Color.RED);
label2.setFont(new Font("Arial", Font.BOLD,100));
label2.setHorizontalTextPosition(JButton.CENTER);
label2.setVerticalTextPosition(JButton.CENTER);
label2.setBorderPainted(false);
label2.addMouseListener(new java.awt.event.MouseAdapter(){
public void mouseEntered(java.awt.event.MouseEvent evt){
label2.setBorderPainted(true);
label2.setBorder(BorderFactory.createLineBorder(Color.red,3));
}
public void mouseExited(java.awt.event.MouseEvent evt){
label2.setBorderPainted(false);
}
});
background.add(label2,c);
pane.add(background);
}
So I'm originally using a BorderLayout for the mainscreen, but once the user hits start, it converts to a GridBagLayout with the intention of being 80% game screen on the left and 20% menu, score, etc on the right.
| --- GameScreen --- | Score |
However I'm having difficulty getting this as either I can't resize the score screen or it doesn't print out correctly at all. This is the code I'm currently using.
public Launcher(String title) {
super(title);
this.setResizable(false);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
cp = getContentPane();
// cp.setSize((int)(1920*0.5), (int)(1080*0.5));
cp.setLayout(new BorderLayout());
panel = new JPanel();
panel.setBackground(Color.YELLOW);
// panel.setSize(this.getWidth()/4, this.getHeight());
panel.add(startButton);
panel.add(pauseButton);
panel.add(quitButton);
setSize(1920, 1100);
cp.add(panel, BorderLayout.SOUTH);
this.getContentPane().setBackground(Color.GREEN);
//ActionListenerStuff for buttons
.
.
.
This is the ACtionListenerMethod that calls the updateGui method.
else if (e.getSource() == startButton) {
cp.remove(panel);
panel.setSize(1200, getHeight());
state = STATE.RUNNING;
updateState();
updateGui();
createGameLoop();
}
This is the method where I change the layout and add the JPanels.
private void updateGui() {
cp.setLayout(new GridBagLayout());
GridBagConstraints layoutConstraints = new GridBagConstraints();
layoutConstraints.fill = GridBagConstraints.VERTICAL;
layoutConstraints.weighty = 1;
layoutConstraints.weightx = 0.8;
cp.add(house, layoutConstraints);
layoutConstraints.weighty = 1;
layoutConstraints.weightx = 0.2;
cp.add(panel, layoutConstraints);
}
It ends up with the 'house' JPanel being 80% but the 'panel' variable is still on the border of the bottom from the previous borderlayout. Not sure why though.
I'm not entirely sure if that's enough information and will gladly post whatever information that's required.
Edit: Tried adding layoutConstraints.gridy = 1; but that didn't work either.
private void updateGui() {
cp.setLayout(new GridBagLayout());
GridBagConstraints layoutConstraints = new GridBagConstraints();
layoutConstraints.fill = GridBagConstraints.VERTICAL;
layoutConstraints.weighty = 1;
layoutConstraints.weightx = 0.8;
house.setMinimumSize(new Dimension(1600, 1080));
cp.add(house, layoutConstraints);
GridBagConstraints layoutConstraints2 = new GridBagConstraints();
layoutConstraints2.fill = GridBagConstraints.VERTICAL;
layoutConstraints2.weighty = 1;
layoutConstraints2.weightx = 0.2;
layoutConstraints.gridy = 1;
cp.add(panel, layoutConstraints2);
}
private void updateState() {
if (roomGenerator == null) {
roomGenerator = new RoomGenerator();
}
roomGenerator.updateRoom();
Room room = roomGenerator.getRoom();
house = (House) roomGenerator.getRoom();
house.setSize(300, getHeight());
this.getContentPane().add(house, BorderLayout.CENTER);
startButton.setVisible(false);
// this plugin puts the buttons in the House JPanel
// house.add(pauseButton);
// house.add(quitButton);
}
This is what I currently have. This is what's displaying.
The drawing should be the "80%" portion and the yellow should be the 20%.
Edit 2: Using Camickr's changes I end up with this.
It's a step in the right direction, but it's not setting the size of the house JPanel correctly as far as I can tell.
private void updateGui() {
cp.add(panel, BorderLayout.LINE_END);
panel.setVisible(true);
cp.revalidate();
}
private void updateState() {
if (roomGenerator == null) {
roomGenerator = new RoomGenerator();
}
roomGenerator.updateRoom();
Room room = roomGenerator.getRoom();
house = (House) roomGenerator.getRoom();
house.setSize(1500, getHeight());
this.getContentPane().add(house, BorderLayout.CENTER);
startButton.setVisible(false);
}
If anyone was curious I figured it out. I did it via this way...
cp.setLayout(new GridBagLayout());
GridBagConstraints layoutConstraints = new GridBagConstraints();
layoutConstraints.fill = GridBagConstraints.BOTH;
layoutConstraints.gridx = 0;
layoutConstraints.gridy = 0;
layoutConstraints.weighty = 1;
layoutConstraints.weightx = 0.8;
house.setMinimumSize(new Dimension(1500, 1080));
cp.add(house, layoutConstraints);
GridBagConstraints layoutConstraints2 = new GridBagConstraints();
layoutConstraints2.fill = GridBagConstraints.BOTH;
layoutConstraints2.weighty = 1;
layoutConstraints2.weightx = 0.2;
layoutConstraints2.gridx = 1;
layoutConstraints2.gridy = 0;
cp.add(dataPanel, layoutConstraints2);
dataPanel.setVisible(true);
cp.revalidate();
What I want to do is load an image into a JScrollPane, surrounded by other components, and when the window is smaller than the image, it should be surrounded by scrollbars so that you can view the entire image by scrolling around.
I am doing this by constructing a JScrollPane with my own class ImagePanel, which extends JPanel, which paints the image. The image is loaded and displayed correctly, but the scrollbars disappear. Is there some part of JComponents that I've misunderstood or what is wrong?
public class ImagePanel extends JPanel {
private BufferedImage img;
public ImagePanel () {
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, this);
}
public void setImage(BufferedImage img) {
this.img = img;
}
}
public class MainGUI extends JPanel {
private ImagePanel imgP;
private JScrollPane pane;
public MainGUI () {
setLayout(new GridBagLayout());
//Create local components
//JComponents
JButton hideButton = new JButton("Hide");
JButton hidecategoryButton = new JButton ("Hide Category");
JButton removeButton = new JButton("Remove");
JButton searchButton = new JButton("Search");
JButton whatishereButton = new JButton("What is here?");
JComboBox<String> placeComboBox;
JLabel categoriesLabel = new JLabel("Categories");
JLabel newLabel = new JLabel("New: ");
JTextArea categoriesArea = new JTextArea();
JTextField searchField = new JTextField(10);
//Other
String[] placeTypes = {"Named Place", "Described Place"};
//Initialize and add behaviour
searchButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String s = searchField.getText();
}
});
categoriesArea.setEditable(false);
placeComboBox = new JComboBox<>(placeTypes);
searchField.setToolTipText("Search...");
searchField.setMinimumSize(new Dimension(5, 1));
//Just fileloading test
BufferedImage bi2 = null;
try {
bi2 = ImageIO.read(new File("dafoe.jpg"));
}
catch (Exception ex) {
}
imgP = new ImagePanel();
imgP.setImage(bi2);
pane = new JScrollPane(imgP);
//Add to panel
GridBagConstraints gc;
//Top row
JPanel toprowPanel = new JPanel();
toprowPanel.add(newLabel);
toprowPanel.add(placeComboBox);
toprowPanel.add(searchField);
toprowPanel.add(searchButton);
toprowPanel.add(hideButton);
toprowPanel.add(removeButton);
toprowPanel.add(whatishereButton);
gc = new GridBagConstraints();
gc.gridx = 0;
gc.gridy = 0;
gc.weightx = 1;
//gc.gridwidth = 6;
add(toprowPanel, gc);
//Hide category
gc = new GridBagConstraints();
gc.anchor = GridBagConstraints.NORTH;
gc.gridx = 7;
gc.gridy = 3;
gc.weightx = 0;
gc.weighty = 0;
add(hidecategoryButton, gc);
//Category Label
gc = new GridBagConstraints();
gc.anchor = GridBagConstraints.BELOW_BASELINE;
gc.gridx = 7;
gc.gridy = 1;
gc.weightx = 0;
gc.weighty = 0;
add(categoriesLabel, gc);
//categoriesarea
gc = new GridBagConstraints();
gc.anchor = GridBagConstraints.BASELINE_TRAILING;
gc.fill = GridBagConstraints.BOTH;
gc.gridx = 7;
gc.gridy = 2;
gc.ipadx = 5;
gc.ipady = 70;
gc.weightx = 0;
gc.weighty = 0;
add(categoriesArea, gc);
//Image
gc = getImageConstraints();
add(pane, gc);
}
public void updateImage(BufferedImage bi) {
imgP.setImage(bi);
//imgP.repaint();
pane.repaint();
}
private GridBagConstraints getImageConstraints() {
GridBagConstraints gc = new GridBagConstraints();
gc.fill = GridBagConstraints.BOTH;
gc.gridheight = 3;
gc.gridwidth = 1;
gc.gridx = 0;
gc.gridy = 1;
gc.weightx = 1;
gc.weighty = 1;
return gc;
}
}
my own class ImagePanel, which extends JPanel, which paints the image. The image is loaded and displayed correctly, but the scrollbars disappear.
The scrollbars will appear automatically when the preferred size of the component added to the scroll pane is greater than the size of the scroll pane.
Your custom component has a preferred size of (0, 0) so the scrollbars will never appear.
You need to override the getPreferredSize() of your ImagePanel class to return the size of the image.
Or even easier just use a JLabel with an ImageIcon and add the label to the scroll pane. A JLabel already implements the getPreferredSize() method correctly.
You can not use the scrollbar when the layout is GridBagLayout. You must use the BorderLayout or FlowLayout
Link example with jtable (similar to the image):
http://myquestionjava.blogspot.com/2016/04/jscrollbars-and-jtable-in-java.html
So yeah, I'm trying to write a rock paper scissors program with images, but I'm having trouble at putting in the pictures. There seems to only be a small white square on the JPanel.
Here's the code for my Main Class:
public class Practice extends JPanel implements ActionListener {
// Images
final ImageIcon rockPic = new ImageIcon("D:\\JOVO\\RPS\\src\\rock.png");
final ImageIcon paperPic = new ImageIcon("D:\\JOVO\\RPS\\src\\paper.png");
// variables
String results = null;
Image pic = null;
//Image Panel
ImagePanel youPic = new ImagePanel();
public Practice() {
// FRAME
JFrame frame = new JFrame();
frame.setSize(400, 400);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("RPS");
frame.setLayout(new BorderLayout());
frame.setVisible(true);
// SUPER JPANEL
setLayout(new GridBagLayout());
setBackground(Color.WHITE);
GridBagConstraints c = new GridBagConstraints();
frame.add(this);
// JPANELS - RPS title, JButton, PICTURES
JPanel rpsTitle = new JPanel();
c.fill = GridBagConstraints.CENTER;
c.gridy = 0;
c.gridx = 1;
rpsTitle.setBackground(Color.WHITE);
add(rpsTitle, c);
JPanel jbuts = new JPanel();
c.gridy = 3;
jbuts.setLayout(new BorderLayout());
add(jbuts, c);
// ImagePanels
c.gridy = 2;
c.gridx = 0;
add(youPic,c);
c.gridy = 0;
c.gridx = 1;
// JBUTTONS
JButton rock = new JButton(" Rock ");
JButton paper = new JButton(" Paper ");
JButton scissors = new JButton("Scissors");
jbuts.add(rock, BorderLayout.WEST);
jbuts.add(paper, BorderLayout.CENTER);
jbuts.add(scissors, BorderLayout.EAST);
paper.addActionListener(this);
JButton resultB = new JButton("RES");
c.gridy = 2;
c.weighty = 10;
add(resultB, c);
c.weighty = 0;
// FONTS
Font rps = new Font(null, Font.BOLD, 28);
Font labels = new Font(null, Font.ITALIC, 18);
// JLABELS
JLabel rpsTit = new JLabel("Rock, Paper, Scissors");
rpsTit.setFont(rps);
rpsTitle.add(rpsTit);
JLabel you = new JLabel("You: ");
you.setFont(labels);
JLabel com = new JLabel("Com: ");
com.setFont(labels);
c.gridy = 1;
c.gridx = 0;
add(you, c);
c.gridx = 2;
add(com, c);
// PICTURES
// comPic.setPic(rockPic);
// youPic.setPic(pic);
}
public String test(String name) {
// test the game
return results;
}
public static void main(String[] args) {
// main stuffs
Practice prac = new Practice();
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Works");
ImageIcon pic = null;
pic = paperPic;
youPic.setPic(pic);
}
}
And my other class:
public class ImagePanel extends JPanel {
Image pic = null;
public ImagePanel() {
repaint();
}
public void setPic(ImageIcon pic) {
// set picture for painting
this.pic = pic.getImage();
System.out.println("Set Pic");
repaint();
}
public void paintComponent(Graphics g) {
// paint
super.paintComponent(g);
System.out.println("Painting");
g.drawImage(pic, 0, 0, this);
}
}
Thanks in advance! :)