importing images causes rendering issues - java

Modifiers.java
package game;
import java.awt.*;
import java.io.*;
import javax.swing.*;
public class Modifiers extends Data{
public static void setupJcomponents(){
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
try{
PixelFont = Font.createFont(Font.TRUETYPE_FONT, new File("src/game/PixelFont.ttf"));
ge.registerFont(PixelFont);
} catch (IOException | FontFormatException e) {
PixelFont = new Font("OCR A Extended", Font.PLAIN, heightUnits*2);
ge.registerFont(PixelFont);
}
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setUndecorated(true);
frame.setSize(MW,MH);
frame.setResizable(false);
frame.setVisible(true);
frame.setLayout(null);
uiPanelMenu.setLayout(null);
uiPanelMenu.setVisible(true);
uiPanelMenu.setBounds(0,0,MW,MH);
uiPanelMenu.setOpaque(false);
for(int btn=0; btn<4; btn++) {
try {
buttonImage[btn] = new ImageIcon(Frame.class.getResource("/game/SelectionButton.png"));
} catch (Exception e) {
e.printStackTrace();
}
buttons[btn] = new JPanel();
buttonLabel[btn] = new JLabel("",SwingConstants.CENTER);
buttonLabel[btn].setIcon(buttonImage[btn]);
buttons[btn].setBounds(widthUnits*15,(heightUnits*13)+(heightUnits*3*btn),widthUnits*15,heightUnits*3);
buttonLabel[btn].setBounds(0,0,buttons[btn].getWidth(),buttons[btn].getHeight());
buttons[btn].setLayout(null);
uiPanelMenu.add(buttons[btn]);
buttons[btn].add(buttonLabel[btn]);
buttonLabel[btn].setForeground(Color.black);
buttons[btn].setBackground(Color.white);
buttonLabel[btn].setText("Button "+(btn+1));
buttonLabel[btn].setFont(new Font("PixelFont", Font.PLAIN, heightUnits*2));
buttons[btn].setVisible(true);
buttonLabel[btn].setVisible(true);
}
menuBackground.setBounds(0,0,MW,MH);
menuBackground.setBackground(Color.black);
menuBackground.setVisible(true);
uiPanelMenu.add(menuBackground);
healthIndicator.setText(String.valueOf(healthValue));
healthIndicator.setFont(new Font("PixelFont", Font.PLAIN, heightUnits*2));
healthIndicator.setBounds(widthUnits*20,heightUnits*20,widthUnits*5,heightUnits*2);
healthIndicator.setVisible(true);
healthIndicator.setOpaque(false);
healthIndicator.setForeground(Color.blue);
uiPanelFight.add(healthIndicator);
frame.getContentPane().add(uiPanelMenu);
}
}
data.java
package game;
import java.awt.*;
import javax.swing.*;
public class Data {
// this is where I will declare and alter all variable that will be used
public static JFrame frame = new JFrame();
public static JLabel healthIndicator = new JLabel("",SwingConstants.CENTER);
public static JPanel buttons[] = new JPanel[5];
public static JLabel buttonLabel[] = new JLabel[5];
public static JPanel menuBackground = new JPanel();
public static JPanel title = new JPanel();
public static JPanel uiPanelMenu = new JPanel();
public static JPanel uiPanelFight = new JPanel();
public static ImageIcon buttonImage[] = new ImageIcon[5];
public static final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
public static final int MW = (int) screenSize.getWidth();
public static final int MH = (int) screenSize.getHeight();
public static final int widthUnits = MW/45;
public static final int heightUnits = MH/25;
public static Font PixelFont;
public static int maxHealth = 100;
public static int healthValue = maxHealth;
}
frame.java
package game;
public class Frame {
public static void main(String[] args) {
Modifiers.setupJcomponents();
}
}
whenever i try to reference the image here:
buttonImage[btn] = new ImageIcon(Frame.class.getResource("/game/SelectionButton.png"));
if it is wrong then it will just give me a NullPointerException, but if the image name is correct then the entire panel that holds everything disappears, all of the objects i used are properly declared in a separate Data.java class, i know it is instantiated correctly but i dont know why everything is not rendering when the line hits the image location.

So your code raises so many questions it's not funny. However, your basic problem(s) come down to lack of understanding in how the basic Swing API works.
Swing is lazy. It won't update the UI when you add/remove components from containers, that's up to you.
So, your basic code currently looks like...
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
//frame.setUndecorated(true);
frame.setSize(MW, MH);
//frame.setResizable(false);
frame.setVisible(true);
// ?? Why ?? Besides, it's not doing what you think it is
frame.setLayout(null);
// Add all the stuff to uiPanelMenu ...
frame.getContentPane().add(uiPanelMenu);
The problem is, once you make the window visible, you are responsible for triggering layout and paint passes.
You can fix the basic problem by adding
frame.getContentPane().revalidate();
frame.getContentPane().repaint();
after frame.getContentPane().add(uiPanelMenu); or moving frame.setVisible(true); after frame.getContentPane().add(uiPanelMenu); which will probably produce a more desirable result.
I know you think you're making your life easier by using null layouts, but your not, nor are you taking into considerations all the differences in how text is rendered on different platforms/hardware.
You're doing yourself a massive disservice by not making use of the layout management API (and will end up having to replicate much of its functionality yourself).
Instead, take the time learn more about the available layout managers - Laying Out Components Within a Container

Related

Java Swing JLabel.setIcon() not working the way I expect

I have a probably easy to solve problem. I used Intellij Idea to build a GUI form. Now I am trying to change the imageIcon of the imageLabel JLabel.
I don't really understand why but when I use the JLabel.setIcon() it neither throws an exception nor displays the image. I have no idea what is wrong with it. It seems like a very simple command.
( I added ico.getImage().flush(); line because when I was searching around people said you have to flush the image before displaying it. I don't actually know what that line does.)
Thanks for any help.
public class App
{
private JPanel mainPanel;
private JPanel imagePanel;
private JPanel optionsPanel;
private JPanel palletesPanel;
private JPanel buttonsPanel;
private JPanel originalPalletePanel;
private JPanel newPalletePanel;
private JLabel originalPalleteLabel;
private JLabel newPalleteLabel;
private JPanel leftButtonsPanel;
private JPanel rightButtonsPanel;
private JButton previewButton;
private JButton revertButton;
private JButton convertImageButton;
private JButton matchPalleteButton;
private JLabel originalPalleteImageLabel;
private JLabel newPalleteImageLabel;
private JLabel imageLabel;
public static void main(String[] args)
{
App app = new App();
JFrame frame = new JFrame("Pixel Pigeon");
frame.setContentPane(new App().mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
pigeon pigey = new pigeon();
try
{
app.loadImage(frame, app);
}
catch(java.io.IOException e)
{
e.printStackTrace();
}
}
private void loadImage(JFrame frame, App app) throws IOException
{
JFileChooser chooser = new JFileChooser();
if(chooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION)
{
BufferedImage img = ImageIO.read(chooser.getSelectedFile());
ImageIcon ico = new ImageIcon(img);
ico.getImage().flush();
app.imageLabel.setIcon(ico);
}
}
}
There were a lot of problems with that short section of code. After removing the many redundant components, the reference to a class not in evidence, fixing the two instances of NullPointerException, removing the call to flush the image, and fixing the problem with the new creation of an App() that already existed, it 'works'. But it is still so bad I'd recommend tossing the lot out and starting again with reference to the JavaDocs for investigating things random people recommend, and the Java Tutorial for the basics of GUI development.
So here is the 'fixed' code: It will load an image, but the GUI then needs to be stretched to make the image visible.
import java.awt.image.BufferedImage;
import java.io.*;
import javax.swing.*;
import javax.imageio.ImageIO;
public class App {
private JPanel mainPanel = new JPanel();
private JLabel imageLabel = new JLabel();
public static void main(String[] args) {
App app = new App();
JFrame frame = new JFrame("Pixel Pigeon");
app.mainPanel.add(app.imageLabel);
frame.setContentPane(app.mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
try {
app.loadImage(frame, app);
}
catch(java.io.IOException e) {
e.printStackTrace();
}
}
private void loadImage(JFrame frame, App app) throws IOException {
JFileChooser chooser = new JFileChooser();
if(chooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
BufferedImage img = ImageIO.read(chooser.getSelectedFile());
ImageIcon ico = new ImageIcon(img);
app.imageLabel.setIcon(ico);
}
}
}

Setting location for objects/images on a background

I'm currently working on a version of the game Ludo/Dude don't get mad, I've ran into a few problems one of the bigger ones being the fact that I cannot place the tokens where I want them to be. I need to set the tokens in certain positions for the start and will need a method with which I will calculate where to move them on the screen here is the code:
public class Ludo extends JFrame{
private BackgroundPanel imagePanel=null;
private JLabel jlTokenBlue1=null;
private JLabel jlTokenBlue2=null;
...
public Ludo(){
try{
//Creating background panel
imagePanel = new BackgroundPanel("ludoBoard.png");
add(imagePanel);
//create tokens for play
BufferedImage imageTokenBlue1 = ImageIO.read(new File("blue1.png"));
jlTokenBlue1 = new JLabel(new ImageIcon(imageTokenBlue1));
BufferedImage imageTokenBlue2 = ImageIO.read(new File("blue2.png"));
jlTokenBlue2 = new JLabel(new ImageIcon(imageTokenBlue2));
BufferedImage imageTokenBlue3 = ImageIO.read(new File("blue3.png"));
jlTokenBlue3 = new JLabel(new ImageIcon(imageTokenBlue3));
BufferedImage imageTokenBlue4 = ImageIO.read(new File("blue4.png"));
jlTokenBlue4 = new JLabel(new ImageIcon(imageTokenBlue4));
BufferedImage imageTokenRed1 = ImageIO.read(new File("red1.png"));
jlTokenRed1 = new JLabel(new ImageIcon(imageTokenRed1));
BufferedImage imageTokenRed2 = ImageIO.read(new File("red2.png"));
jlTokenRed2 = new JLabel(new ImageIcon(imageTokenRed2));
BufferedImage imageTokenRed3 = ImageIO.read(new File("red3.png"));
jlTokenRed3 = new JLabel(new ImageIcon(imageTokenRed3));
BufferedImage imageTokenRed4 = ImageIO.read(new File("red4.png"));
jlTokenRed4 = new JLabel(new ImageIcon(imageTokenRed4));
imagePanel.add(jlTokenBlue1);
imagePanel.add(jlTokenBlue2);
imagePanel.add(jlTokenBlue3);
imagePanel.add(jlTokenBlue4);
imagePanel.add(jlTokenRed1);
imagePanel.add(jlTokenRed2);
imagePanel.add(jlTokenRed3);
imagePanel.add(jlTokenRed4);
jlTokenRed1.setLocation(250,500);
}//End of try
catch(IOException ioe){
System.out.println("The background image cannot be loaded...");
}catch(NullPointerException npe){
npe.getMessage();
}
.
.
.
class BackgroundPanel extends JPanel
{
Image image;
public BackgroundPanel(String imageName)
{
try
{
image = javax.imageio.ImageIO.read(new java.net.URL(getClass().getResource(imageName), imageName));
}
catch (Exception e) { /*handled in paintComponent()*/ }
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
if (image != null)
g.drawImage(image, 0,0,this.getWidth(),this.getHeight(),this);
}
}
I've tried using setLocation and repaint but was unable to set the tokens to be placed where I want them to be. I'd like to place the tokens into the white fields in their respective colors any help and/or suggestion is greatly appreciated. Below is a picture of how it looks right now.
Here is the link to the drive containing everything if you wish to check the files your self. drive.google.com/open?id=1xap_xz2K3SF37XQfRN3Y_LHoTHg0HNox
!
I've started some code for your game. You'll have to complete the code.
Here's the GUI I created.
The first thing I did was to employ a model / view / controller pattern. By separating the logical functions of the game, I could concentrate on one part at a time.
Here's the model I created. It's not complete, but I think you can see what I'm trying to do herd. I put his class in its own model package.
package com.ggl.ludo.model;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
public class LudoModel {
private final BufferedImage gameBoard;
private final BufferedImage[] imageTokenBlue;
public LudoModel() {
imageTokenBlue = new BufferedImage[4];
imageTokenBlue[0] = getImage("blue1.png");
imageTokenBlue[1] = getImage("blue2.png");
imageTokenBlue[2] = getImage("blue3.png");
imageTokenBlue[3] = getImage("blue4.png");
gameBoard = getImage("ludoBoard.png");
}
public BufferedImage getGameBoard() {
return gameBoard;
}
public BufferedImage[] getImageTokenBlue() {
return imageTokenBlue;
}
private BufferedImage getImage(String fileName) {
try {
return ImageIO.read(getClass().getResourceAsStream("/" + fileName));
} catch (IOException e) {
return null;
}
}
}
All this code does is read in the images, and eventually, create the logical model of your game. It's not concerned with the view or the controller code at all.
The next class I created was the DrawingPanel class. This class draws the game board and eventually, draws the pieces on the board. The location of the pieces information goes into the model.
package com.ggl.ludo.view;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JPanel;
import com.ggl.ludo.model.LudoModel;
public class DrawingPanel extends JPanel {
private static final long serialVersionUID = 1L;
private LudoFrame frame;
private LudoModel model;
public DrawingPanel(LudoFrame frame, LudoModel model) {
this.frame = frame;
this.model = model;
int width = model.getGameBoard().getWidth();
int height = model.getGameBoard().getHeight();
this.setPreferredSize(new Dimension(width, height));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(model.getGameBoard(), 0, 0, this);
// Your piece drawing code goes here
}
}
Next, I created a class to hold the JFrame. The JScrollPane code can be removed. My old laptop can't display a game board as large as yours. Something to keep in mind if you want others to play this game.
I put the menu code in its own method. I like to keep separate things separate. My feeble mind can't handle too many processes at one time.
package com.ggl.ludo.view;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import com.ggl.ludo.model.LudoModel;
public class LudoFrame {
private DrawingPanel drawingPanel;
private LudoModel ludoModel;
public LudoFrame(LudoModel ludoModel) {
this.ludoModel = ludoModel;
generateGUIControl();
}
private void generateGUIControl() {
JFrame frame = new JFrame("Ludo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(createMenu());
drawingPanel = new DrawingPanel(this, ludoModel);
JScrollPane scrollPane = new JScrollPane(drawingPanel);
scrollPane.setPreferredSize(new Dimension(400, 400));
frame.add(scrollPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JMenuBar createMenu() {
JMenuBar ludoMenuBar = new JMenuBar();
JMenu ludoMenuFirst = new JMenu("Information");
ludoMenuBar.add(ludoMenuFirst);
JMenuItem jmiDescription = new JMenuItem("Description");
JMenuItem jmiHelp = new JMenuItem("Help");
JMenuItem jmiRestart = new JMenuItem("Restart");
JMenuItem jmiExit = new JMenuItem("Exit");
ludoMenuFirst.add(jmiDescription);
ludoMenuFirst.add(jmiHelp);
ludoMenuFirst.add(jmiRestart);
ludoMenuFirst.add(jmiExit);
ludoMenuBar.add(ludoMenuFirst);
return ludoMenuBar;
}
}
Finally, the driver class that starts the whole process. You must start a Swing application on the Event Dispatch Thread(EDT). The call to SwingUtilities invokeLater ensures that your application starts on the EDT.
package com.ggl.ludo;
import javax.swing.SwingUtilities;
import com.ggl.ludo.model.LudoModel;
import com.ggl.ludo.view.LudoFrame;
public class Ludo implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Ludo());
}
#Override
public void run() {
new LudoFrame(new LudoModel());
}
}
I hope this has been helpful to you. As far as the controllers, I suggest that you use a mouse listener and draw the game pieces on the game board.
Remember, information about the game piece locations goes into the model. The view drawing code draws from the information in the model.

Get the maximum screen size with JFrame

I have been working on making Pong in Java, but I can't seem to accurately set the size of the JFrame. Here is my main class:
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
public class Pong extends JFrame {
private final Game panel;
private final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
public Pong() {
setTitle("Pong");
setSize(screenSize);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel = new Game(this);
add(panel);
}
public static void main(String[] args) {
new Pong();
}
}
When I run my program, the window takes up the whole screen, but when I try to get the dimensions of the screen, they are larger than those of the window, causing anything set at the lower extents of the window to get cut off. The only way I have found to get the true dimensions is to call this.getHeight(), this.getWidth(), or this.getSize() within the panel class. How can I get the true dimensions right off the bat?
You could use JFrame#setExtendedState(JFrame.MAXIMIZED_BOTH)
f.setExtendedState(JFrame.MAXIMIZED_BOTH);
It has the same effect as when you enlarge a window in your OS
With this method, you can now have the "real" dimensions by calling the different methods mentionned above in the question.
Try to call method setExtendedState.
public class Pong extends JFrame {
private final Game panel;
public Pong() {
setTitle("Pong");
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel = new Game(this);
add(panel);
setExtendedState(java.awt.Frame.MAXIMIZED_BOTH);
//setVisible(true);
}
public static void main(String[] args) {
Pong pong = new Pong();
pong.setVisible(true);
}
}
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
public class Pong extends JFrame {
private final Game panel;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double width = screenSize.getWidth();
double height = screenSize.getHeight();
public Pong() {
setTitle("Pong");
setSize((int)width,(int)height);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel = new Game(this);
add(panel);
}
public static void main(String[] args) {
new Pong();
}
}
check this question How can I get screen resolution in java?
Put in your code:
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
Details you can find in documentation.
Another questions on same subject is here.

Java Swing JSplitPane not showing as intended

I'm trying to make a program thats based upon 5 Jsplitpanes and internal components, but they don't seem to get along well. Since when I run the application all the split panes are concentrated on the upper left corner
The code is really simple:
projectExplorer = new ProjectExplorer();
editorExplorer = new EditorExplorer();
favDownload = new FavDownload();
favDownloadExplorer = new FavDownloadExplorer();
//Define the listeners
addComponentListener(new ResizeListener());
horTopPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
horTopPane.setLeftComponent(projectExplorer);
horTopPane.setRightComponent(editorExplorer);
horBotPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
horBotPane.setLeftComponent(favDownload);
horBotPane.setRightComponent(favDownloadExplorer);
verticalPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
verticalPane.setTopComponent(horTopPane);
verticalPane.setBottomComponent(horBotPane);
setContentPane(verticalPane);
new Timer().schedule(new TimerTask() {
#Override
public void run() {
resizeComponents();
}
}, 100);
the resizeComponents method is
public void resizeComponents(){
int width = getWidth();
int height = getHeight();
horTopPane.setMinimumSize(new Dimension(width, (height/2)+(height/4)));
horTopPane.setSize(horTopPane.getMinimumSize());
horBotPane.setMinimumSize(new Dimension(width, (height/8)));
horBotPane.setSize(horBotPane.getMinimumSize());
projectExplorer.setMinimumSize(new Dimension(width/8, horTopPane.getHeight()));
projectExplorer.setSize(projectExplorer.getMinimumSize());
editorExplorer.setMinimumSize(new Dimension(width/2, horTopPane.getHeight()));
editorExplorer.setSize(editorExplorer.getMinimumSize());
favDownload.setMinimumSize(new Dimension(width/8, horBotPane.getHeight()));
favDownload.setSize(favDownload.getMinimumSize());
favDownloadExplorer.setMinimumSize(new Dimension(width/2, horBotPane.getHeight()));
favDownloadExplorer.setSize(favDownloadExplorer.getMinimumSize());
}
it started just as setSize, but for some reason it didn't resize them at all, then I putted setMinimumSize and it didn't resize it either, but when i move the elements a bit on the program they all go to its minimum size, am I missing something?
I've already made a few Java GUI programs, but this one just doesn't want to work properly.
What did I do wrong?
To start with, don't mess with setMinimum/Maximum/PreferredSize, have a look at Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing? for more details
Next, don't update the state of UI components from any thread other than the Event Dispatching Thread, Swing is not thread safe. java.util.Timer will trigger event notification within it's own thread context.
Next, consider overriding (at least), getPreferredSize from your custom components and return a default value, for example...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class SplitPaneTest {
public static void main(String[] args) {
new SplitPaneTest();
}
public SplitPaneTest() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private final ProjectExplorer projectExplorer;
private final EditorExplorer editorExplorer;
private final FavDownload favDownload;
private final FavDownloadExplorer favDownloadExplorer;
private final JSplitPane horTopPane;
private final JSplitPane horBotPane;
private final JSplitPane verticalPane;
public TestPane() {
projectExplorer = new ProjectExplorer();
editorExplorer = new EditorExplorer();
favDownload = new FavDownload();
favDownloadExplorer = new FavDownloadExplorer();
horTopPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
horTopPane.setLeftComponent(projectExplorer);
horTopPane.setRightComponent(editorExplorer);
horBotPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
horBotPane.setLeftComponent(favDownload);
horBotPane.setRightComponent(favDownloadExplorer);
verticalPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
verticalPane.setTopComponent(horTopPane);
verticalPane.setBottomComponent(horBotPane);
setLayout(new BorderLayout());
add(verticalPane);
}
}
protected abstract class AbstractPane extends JPanel {
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
public class ProjectExplorer extends AbstractPane {
public ProjectExplorer() {
setBackground(Color.RED);
}
}
public class EditorExplorer extends AbstractPane {
public EditorExplorer() {
setBackground(Color.BLUE);
}
}
public class FavDownload extends AbstractPane {
public FavDownload() {
setBackground(Color.MAGENTA);
}
}
public class FavDownloadExplorer extends AbstractPane {
public FavDownloadExplorer() {
setBackground(Color.CYAN);
}
}
}
If you have to modify the divider's location consider using JSplitSpane#setDividerLocation(double) or JSplitSpane#setDividerLocation(int)
Take a look at How to Use Split Panes for more details

Java: JTextField won't appear

public class HandleUI {
public static void setUpUI(){
JPanel jPan = new JPanel();
FlowLayout flow = new FlowLayout();
jPan.setLayout(flow);
txtFld = new JTextField();
txtFld.setSize(550,5);
jPan.add(txtFld);
jPan.setSize(10,200);
MainClass.mainFrame.add(jPan);
int gapX = MainClass.mainFrame.getX()-(txtFld.getX()/2);
}
//Instance variables.
public static JTextField txtFld;
public JButton [] buttons;
}
public class MainClass {
public static void main (String [] args){
int frameX = Constants.FRAME_WIDTH;
int frameY = Constants.FRAME_HEIGHT;
mainFrame = new JFrame();
mainFrame.setSize(frameX,frameY);
mainFrame.setResizable(false);
mainFrame.setVisible(true);
HandleUI.setUpUI();
}
//Instance variables
public static JFrame mainFrame;
}
It's supposed to show JTextField, but as you might have guessed - JFrame shows nothing. I didn't type in imports on purpose, but they are all there. I can't find the problem. Can anyone help?
1.) Simply write:
JTextField tField = new JTextField(10);
Here In the constructor you are passing the number of columns, which is sufficient for a layout like FlowLayout to set the size of the JTextField
2.) The line mainFrame.setVisible(true); must be the last line of the main method. You need to put the code at main() method, inside SwingUtilities.invokeLater(...) thingy.
3.) Instead of setting size on the JFrame use JFrame.pack(), to set the window to the preferred size.
4.) Creation of unnecessary static members is a design flaw. Try to keep yourself away from such thingies.
5.) Read a bit about Concurrency in Swing
One Example Program for help(Use the order of lines as specified in this answer):
import java.awt.*;
import javax.swing.*;
public class Example {
private void displayGUI() {
JFrame frame = new JFrame("Example Demo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel();
JTextField tField = new JTextField(10);
contentPane.add(tField);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
new Example().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
You have to call setVisible(true) on your JFrame AFTER having initialised your UI.
Simply pulling the following line:
HandleUI.setUpUI();
... right before:
mainFrame.setVisible(true);
... will do the trick.
As a side note, I'd like to point out that setting the size of your text field won't really work like you did. You probably would use setPreferredSize(Dimension) instead. Or, even better, organise your UI only using Layouts and not manually setting any component's size.

Categories

Resources