Java swing resize ImageIcon for different Windows Scaling settings - java

I am trying to create a small swing application using Zulu JDK 11. In the bottom right part of it I am having an image (logo). My problem is that the logo is displayed poorly when the user changes the scaling to a value greater than 100% (125%, 150%, 175% etc.)
Here is my source code.
Main class:
public class Main {
public static void main(String[] args) {
FrameServer frameServer = new FrameServer();
frameServer.setVisible(true);
}}
FrameServer class:
public class FrameServer extends JFrame {
private JPanel contentPane;
private JPanel centerPane = new JPanel();
private JPanel southPane = new JPanel();
private JPanel rightPane = new JPanel();
private JButton btnOK = new JButton("OK");
private JTabbedPane jTabbedPane1 = new JTabbedPane();
private Tab1 tab1Page = new Tab1();
private Tab2 tab2Page = new Tab2();
public FrameServer() {
enableEvents(AWTEvent.WINDOW_EVENT_MASK);
jbInit();
pack();
centerFrame();
this.repaint();
}
private void jbInit() {
setTitle("Test Scaling App");
contentPane = (JPanel) this.getContentPane();
contentPane.setLayout(new BorderLayout());
centerPane.setLayout(new BorderLayout());
centerPane.add(jTabbedPane1, BorderLayout.CENTER);
southPane.setLayout(new BorderLayout());
rightPane.setLayout(new FlowLayout(FlowLayout.RIGHT, 5, 5));
rightPane.add(btnOK);
CustomStatusBar statusBar = new CustomStatusBar();
southPane.add(statusBar, BorderLayout.CENTER);
southPane.add(rightPane, BorderLayout.EAST);
jTabbedPane1.addTab("Tab 1", tab1Page);
jTabbedPane1.addTab("Tab 2", tab2Page);
contentPane.add(centerPane, BorderLayout.CENTER);
contentPane.add(southPane, BorderLayout.SOUTH);
}
private void centerFrame() {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = this.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
this.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
}
class Tab2 extends JScrollPane {
public Tab2() {
super(new JTextArea(10, 60));
super.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
super.getViewport().setPreferredSize(new Dimension(500, 300));
}
}
class Tab1 extends JPanel {
public Tab1() {
contentPane = this;
JScrollPane centerScrollPane = new JScrollPane(new JTable());
centerScrollPane.getViewport().setBackground(Color.white);
JPanel eastPane = new JPanel();
eastPane.setLayout(new FlowLayout());
JPanel topPane = new JPanel();
topPane.setLayout(new BoxLayout(topPane, BoxLayout.Y_AXIS));
eastPane.add(topPane, FlowLayout.LEFT);
contentPane.setLayout(new BorderLayout());
contentPane.add(centerScrollPane, BorderLayout.CENTER);
contentPane.add(eastPane, BorderLayout.EAST);
}
}
class CustomStatusBar extends JPanel {
JLabel label0 = new JLabel("", SwingConstants.CENTER);
JLabel label1 = new JLabel();
JLabel label2 = new JLabel();
JLabel label3 = new JLabel("", SwingConstants.CENTER);
JLabel labelLogo = new JLabel();
private static final int HEIGHT = 21;
public CustomStatusBar() {
setCommonFeatures(label0, 40, "Stuff 0");
setCommonFeatures(label1, 120, "Stuff 1");
setCommonFeatures(label2, 120, "Stuff 2");
setCommonFeatures(label3, 90, "Stuff 3");
labelLogo.setFont(new java.awt.Font("Dialog", 3, 12));
labelLogo.setForeground(Color.black);
labelLogo.setBorder(BorderFactory.createLoweredBevelBorder());
ImageIcon image = new ImageIcon("small.png");
labelLogo.setIcon(image);
labelLogo.setPreferredSize(new Dimension(40, HEIGHT));
labelLogo.setHorizontalAlignment(SwingConstants.CENTER);
setLayout(new GridBagLayout());
setMaximumSize(new Dimension(800, 40));
add(label0, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 50, 0));
add(label1, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 50, 0));
add(label2, new GridBagConstraints(2, 0, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 50, 0));
add(label3, new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 50, 0));
add(labelLogo, new GridBagConstraints(4, 0, GridBagConstraints.REMAINDER, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 50, 0));
}
private void setCommonFeatures(JLabel label, int width, String msg) {
label.setBackground(UIManager.getColor("ScrollBar.track"));
label.setForeground(Color.black);
label.setBorder(BorderFactory.createLoweredBevelBorder());
label.setPreferredSize(new Dimension(width, HEIGHT));
label.setText(" " + msg);
}
}}
Small.png image file:
When opened at scaling 100%, it looks good:
But when changing the scaling to 175%:
the pixels start to show up (open link to the picture to see better)
Now, what I have done is to replace the logo with one with a higher resolution:
Now, I am struck as I do not know how to make it fit in the space available for it and display properly when scaled. If i redimension the image from the java code as seen here, it will display properly for 100%, but for 175% scaling the pixels become visible again, like using the small.png file.
Which is the correct way of solving this?
Thank you.

The workaround is the following (only tested on Windows 10):
Locate the javaw.exe that the application is using (it very important to apply the following to javaw.exe, not java.exe)
Right click -> Properties -> Compatibility tab
Click button Change high DPI settings
Check Override high DPI scaling behavior. Scaling performed by: Select System in the combobox.
Press OK twice and restart the application

Related

JLabel & JButton setPreferredSize not working properly

I'm building a Java GUI calculator. UI is complex and I'm doing it using Layouts instead of drag and drop. Everything is working fine except
1.mode_error_label.setPreferredSize(new Dimension(46, 55)); 2.backButton.setPreferredSize(new Dimension(45, 55));
Why is height not set to 55?
What am I missing?
Look at the top left and top right corner of the image.
My Result:
Desired Result:
public class CalculatorViewController extends JPanel {
private JTextField display1;
private JTextField display2;
private JLabel mode_error_label;
private JButton dotButton;
public CalculatorViewController() {
this.setLayout(new BorderLayout());
this.setBorder(BorderFactory.createMatteBorder(5, 5, 5, 5, Color.BLACK));
mode_error_label = new JLabel("F", JLabel.CENTER);
mode_error_label.setPreferredSize(new Dimension(46, 55));
mode_error_label.setBackground(Color.YELLOW);
mode_error_label.setOpaque(true);
mode_error_label.setBorder(BorderFactory.createMatteBorder(0, 0, 0, 5, Color.BLACK));
JButton backButton = new JButton(Character.toString('\u21DA'));
backButton.setPreferredSize(new Dimension(45, 55));
backButton.setBackground(Color.YELLOW);
backButton.setBorder(BorderFactory.createMatteBorder(0, 5, 0, 0, Color.BLACK));
backButton.setToolTipText("Backspace (Alt-B)");
display1 = new JTextField(16);
display1.setEditable(false);
display1.setHorizontalAlignment(JTextField.RIGHT);
display1.setBackground(Color.WHITE);
display1.setBorder(BorderFactory.createEmptyBorder());
display2 = new JTextField(16);
display2.setEditable(false);
display2.setHorizontalAlignment(JTextField.RIGHT);
display2.setBackground(Color.WHITE);
display2.setBorder(BorderFactory.createEmptyBorder());
display2.setText("0.0");
Box displayBox = Box.createVerticalBox();
displayBox.add(display1);
displayBox.add(display2);
Box upperBox = Box.createHorizontalBox();
upperBox.add(mode_error_label);
upperBox.add(displayBox);
upperBox.add(backButton);
upperBox.setBorder(BorderFactory.createMatteBorder(0, 0, 5, 0, Color.black));
JCheckBox modeCheckBox = new JCheckBox("int");
modeCheckBox.setPreferredSize(new Dimension(40, 0));
modeCheckBox.setBackground(Color.green);
JRadioButton _0RadioButton = new JRadioButton(".0", false);
_0RadioButton.setBackground(Color.YELLOW);
JRadioButton _00RadioButton = new JRadioButton(".00", true);
_00RadioButton.setBackground(Color.YELLOW);
JRadioButton sciRadioButton = new JRadioButton("Sci", false);
sciRadioButton.setBackground(Color.YELLOW);
ButtonGroup radioButtonGroup = new ButtonGroup();
radioButtonGroup.add(_0RadioButton);
radioButtonGroup.add(_00RadioButton);
radioButtonGroup.add(sciRadioButton);
Box lowerBox = Box.createHorizontalBox();
lowerBox.add(modeCheckBox);
lowerBox.add(Box.createGlue());
lowerBox.add(_0RadioButton);
lowerBox.add(_00RadioButton);
lowerBox.add(sciRadioButton);
lowerBox.setBackground(Color.BLACK);
lowerBox.setOpaque(true);
lowerBox.setBorder(BorderFactory.createMatteBorder(5, 0, 5, 0, Color.black));
JPanel lowerPanel = new JPanel();
lowerPanel.add(lowerBox);
lowerPanel.setBackground(Color.BLACK);
lowerPanel.setOpaque(true);
lowerPanel.setBorder(BorderFactory.createEmptyBorder());
Box superBox = Box.createVerticalBox();
superBox.add(upperBox);
superBox.add(lowerBox);
this.add(superBox, BorderLayout.PAGE_START);
}
}
I searched for it but found no luck. Any help would be appreciated. Thanks
For the top bar where you have the back button and label, set the container layout a border layout. Border layout should resize the component to its container. Or you can post a code that shows the problem and we can try to solve your problem. Good luck.
public class CalculatorViewController extends JPanel {
private JTextField display1;
private JTextField display2;
private JLabel mode_error_label;
private JButton dotButton;
private JPanel topPanel;
public CalculatorViewController() {
this.setLayout(new BorderLayout());
this.setBorder(BorderFactory.createMatteBorder(5, 5, 5, 5, Color.BLACK));
mode_error_label = new JLabel("F", JLabel.CENTER);
mode_error_label.setPreferredSize(new Dimension(46, 55));
mode_error_label.setBackground(Color.YELLOW);
mode_error_label.setOpaque(true);
mode_error_label.setBorder(BorderFactory.createMatteBorder(0, 0, 0, 5, Color.BLACK));
JButton backButton = new JButton(Character.toString('\u21DA'));
backButton.setPreferredSize(new Dimension(45, 55));
backButton.setBackground(Color.YELLOW);
backButton.setBorder(BorderFactory.createMatteBorder(0, 5, 0, 0, Color.BLACK));
backButton.setToolTipText("Backspace (Alt-B)");
display1 = new JTextField(16);
display1.setEditable(false);
display1.setHorizontalAlignment(JTextField.RIGHT);
display1.setBackground(Color.WHITE);
display1.setBorder(BorderFactory.createEmptyBorder());
display2 = new JTextField(16);
display2.setEditable(false);
display2.setHorizontalAlignment(JTextField.RIGHT);
display2.setBackground(Color.WHITE);
display2.setBorder(BorderFactory.createEmptyBorder());
display2.setText("0.0");
Box displayBox = Box.createVerticalBox();
displayBox.add(display1);
displayBox.add(display2);
Box upperBox = Box.createHorizontalBox();
topPanel.add(mode_error_label, BorderLayout.WEST);
topPanel.add(displayBox, BorderLayout.CENTER);
topPanel.add(backButton, BorderLayout.EAST);
upperBox.add(topPanel);
upperBox.setBorder(BorderFactory.createMatteBorder(0, 0, 5, 0, Color.black));
JCheckBox modeCheckBox = new JCheckBox("int");
modeCheckBox.setPreferredSize(new Dimension(40, 0));
modeCheckBox.setBackground(Color.green);
JRadioButton _0RadioButton = new JRadioButton(".0", false);
_0RadioButton.setBackground(Color.YELLOW);
JRadioButton _00RadioButton = new JRadioButton(".00", true);
_00RadioButton.setBackground(Color.YELLOW);
JRadioButton sciRadioButton = new JRadioButton("Sci", false);
sciRadioButton.setBackground(Color.YELLOW);
ButtonGroup radioButtonGroup = new ButtonGroup();
radioButtonGroup.add(_0RadioButton);
radioButtonGroup.add(_00RadioButton);
radioButtonGroup.add(sciRadioButton);
Box lowerBox = Box.createHorizontalBox();
lowerBox.add(modeCheckBox);
lowerBox.add(Box.createGlue());
lowerBox.add(_0RadioButton);
lowerBox.add(_00RadioButton);
lowerBox.add(sciRadioButton);
lowerBox.setBackground(Color.BLACK);
lowerBox.setOpaque(true);
lowerBox.setBorder(BorderFactory.createMatteBorder(5, 0, 5, 0, Color.black));
JPanel lowerPanel = new JPanel();
lowerPanel.add(lowerBox);
lowerPanel.setBackground(Color.BLACK);
lowerPanel.setOpaque(true);
lowerPanel.setBorder(BorderFactory.createEmptyBorder());
Box superBox = Box.createVerticalBox();
superBox.add(upperBox);
superBox.add(lowerBox);
this.add(superBox, BorderLayout.PAGE_START);
}
}

How to create custom panel layout with Swing? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
public class BattleShipsMain {
public static void main(String[] args) {
// JButton arrays to hold buttons
JButton[] userButtons = new JButton[100];
JButton[] compButtons = new JButton[100];
// Text for ships label
String shipsText = "Ships Size (Squares)" + "Carrier 5"
+ "Battleship 4" + "Destroyer 3"
+ "Patrol Boat 2";
// Draw main window and set layout
JFrame window = new JFrame("Battle Ships");
window.setSize(1200, 1900);
window.getContentPane().setLayout(new BorderLayout());
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Draw top game panel
JPanel gridPanTop = new JPanel();
gridPanTop.setLayout(new BorderLayout());
gridPanTop.setPreferredSize(new Dimension(1300, 400));
gridPanTop.setBackground(Color.GRAY);
// Top panel text
JLabel ships = new JLabel();
ships.setText(shipsText);
// Bottom panel buttons
JButton submit = new JButton("Submit");
Dimension submitSize = new Dimension(20, 20);
submit.setSize(submitSize);
// Draw bottom game panel
JPanel panBottom = new JPanel();
panBottom.setBackground(Color.WHITE);
panBottom.setLayout(new BorderLayout());
panBottom.setPreferredSize(new Dimension(200, 200));
panBottom.add(submit);
// Set position of game panels
window.getContentPane().add(gridPanTop, BorderLayout.PAGE_START);
window.getContentPane().add(panBottom, BorderLayout.CENTER);
// Set border for grid buttons
Border border = new LineBorder(Color.gray);
// Draw panel for grids
JPanel user = new JPanel();
JPanel comp = new JPanel();
user.setBackground(Color.gray);
comp.setBackground(Color.gray);
user.setBorder(border);
comp.setBorder(border);
// Set layout for grid panels
user.setLayout(new GridLayout(10, 10));
comp.setLayout(new GridLayout(10, 10));
int x = userButtons.length;
// Set user buttons as JButtons, set size and add to grid
for (int i = 0; i < x; i++) {
userButtons[i] = new JButton();
userButtons[i].setPreferredSize(new Dimension(40, 40));
user.add(userButtons[i]);
}
// Set computer buttons as JButtons, set size and add to grid
for (int i = 0; i < x; i++) {
compButtons[i] = new JButton();
compButtons[i].setPreferredSize(new Dimension(40, 40));
comp.add(compButtons[i]);
}
// Add panels to main frame and set visible
window.pack();
window.add(gridPanTop);
window.add(panBottom);
gridPanTop.add(user, BorderLayout.WEST);
gridPanTop.add(comp, BorderLayout.EAST);
gridPanTop.setVisible(true);
panBottom.setVisible(true);
window.setVisible(true);
user.setVisible(true);
comp.setVisible(true);
// Start main game
MainGame start = new MainGame();
}
}
I have an assignment and am having lot of trouble creating the below panel layout in Java Swing. I have had no luck using any of the layouts.
Could anyone help my with this layout?
At present the code displays the following output:
You can probably tell I am a beginner so please excuse rookie errors. The panel layout I have at the moment LOOKS like the ideal one I attached but clearly is not the correct layout as I'd like.
You can achive this with different layouts and compound of layouts (using subpanels). I would have used GridBagLayout, that is definitely one of the most versatile layouts.
Example code
public class TestLayout extends JFrame {
private static final long serialVersionUID = -7619921429181915663L;
public TestLayout(){
super("TestLayout");
super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
init();
}
private void init() {
this.getContentPane().setLayout(new GridBagLayout());
//Setup some test panel with labels
JPanel panel1 = new JPanel(new BorderLayout());
panel1.setBorder(BorderFactory.createEtchedBorder());
JLabel label1 = new JLabel("Panel 1");
label1.setHorizontalAlignment(SwingConstants.CENTER);
panel1.add(label1,BorderLayout.CENTER);
JPanel panel2 = new JPanel(new BorderLayout());
panel2.setBorder(BorderFactory.createEtchedBorder());
JLabel label2 = new JLabel("Panel 2");
label2.setHorizontalAlignment(SwingConstants.CENTER);
panel2.add(label2,BorderLayout.CENTER);
JPanel panel3 = new JPanel(new BorderLayout());
panel3.setBorder(BorderFactory.createEtchedBorder());
JLabel label3 = new JLabel("Panel 3");
label3.setHorizontalAlignment(SwingConstants.CENTER);
panel3.add(label3,BorderLayout.CENTER);
JPanel panel4 = new JPanel(new BorderLayout());
panel4.setBorder(BorderFactory.createEtchedBorder());
JLabel label4 = new JLabel("Panel 4");
label4.setHorizontalAlignment(SwingConstants.CENTER);
panel4.add(label4,BorderLayout.CENTER);
//Here goes the interesting code
this.getContentPane().add(panel1, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.6, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(2, 2,
2, 2), 0, 0));
this.getContentPane().add(panel2, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.6, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(2, 2,
2, 2), 0, 0));
this.getContentPane().add(panel3, new GridBagConstraints(2, 0, 1, 1, 1.0, 0.6, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(2, 2,
2, 2), 0, 0));
//next row
this.getContentPane().add(panel4, new GridBagConstraints(0, 1, 3, 1, 1.0, 0.4, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(2, 2,
2, 2), 0, 0));
this.setPreferredSize(new Dimension(400, 200));
this.pack();
}
public static void main(String[] args) {
TestLayout frame = new TestLayout();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Generated output
The key part of the GridBagLayout is the GridBagConstraints
new GridBagConstraints(columnNumber, rowNumber, columnSpan, rowSpan, columnWeigth, rowWeigth, alignment, fillType, insets, padX, pady)
see in example how rowWeigth is set to 0.6 for first row and 0.4 to second row so that first row takes up some more space (60%). Adjust them as you like (if you like same space, just set 0.5 to both).

Button does not create JPanel

I am new in Java and am doing some window application for my college.
I am trying to do some kind of menu with three buttons in start, and when one of buttons is clicked it's supposed to create a JPanel with two more buttons, but my code doesn't work.
Here is the code:
import java.awt.*;
public class mainScreen extends JFrame {
private JPanel contentPane;
public mainScreen() {
super("Aplikacija za atletska natjecanja");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(0, 0, screenSize.width, screenSize.height);
contentPane = new JPanel();
contentPane.setBackground(SystemColor.info);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
setContentPane(contentPane);
JPanel top = new JPanel();
top.setBounds(200, 11, screenSize.width - 400, screenSize.height - (screenSize.height - 100));
contentPane.add(top);
JPanel mainMenu = new JPanel();
mainMenu.setBounds(200, 110, screenSize.width - 400, screenSize.height - (screenSize.height - 30));
contentPane.add(mainMenu);
mainMenu.setLayout(new GridLayout(1, 0, 0, 0));
JButton btnTrkacke = new JButton("Trka\u010Dke");
btnTrkacke.setBackground(SystemColor.text);
mainMenu.add(btnTrkacke);
btnTrkacke.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JPanel panTrk = new JPanel();
panTrk.setBounds(201, 140, (screenSize.width - 400) / 3, 30);
contentPane.add(panTrk);
panTrk.setLayout(new GridLayout(1, 0, 0, 0));
JButton btnTrkAtl = new JButton("Atleti\u010Dari");
btnTrkAtl.setBackground(SystemColor.text);
panTrk.add(btnTrkAtl);
JButton btnTrkDisc = new JButton("Discipline");
btnTrkDisc.setBackground(SystemColor.text);
panTrk.add(btnTrkDisc);
}
});
JButton btnSkakacke = new JButton("Skaka\u010Dke");
btnSkakacke.setBackground(SystemColor.text);
mainMenu.add(btnSkakacke);
JButton btnBacacke = new JButton("Baca\u010Dke");
btnBacacke.setBackground(SystemColor.text);
mainMenu.add(btnBacacke);
}
}
That same panel should also be created when I click on the other two buttons, but on other the position... Is it better to create class for that pane and then call it when button is clicked?
You're forgetting to call revalidate and repaint on the contentPane after changing its components:
contentPane.revalidate();
contentPane.repaint();
e.g.,
#Override
public void actionPerformed(ActionEvent e) {
JPanel panTrk = new JPanel();
panTrk.setBounds(201, 140, (screenSize.width - 400) / 3, 30);
contentPane.add(panTrk);
panTrk.setLayout(new GridLayout(1, 0, 0, 0));
JButton btnTrkAtl = new JButton("Atleti\u010Dari");
btnTrkAtl.setBackground(SystemColor.text);
panTrk.add(btnTrkAtl);
JButton btnTrkDisc = new JButton("Discipline");
btnTrkDisc.setBackground(SystemColor.text);
panTrk.add(btnTrkDisc);
contentPane.revalidate(); // ***** added *****
contentPane.repaint(); // ***** added *****
}
revalidate tells the container to re-lay out its components.
repaint requests to the paint manager that the component and any children should be re-drawn.
As an aside: you're using null layout manager and absolute positioning with setBounds(...), and you really don't want to do this. While to a newbie this seems the best way to create complex GUI's, the more you deal with Swing GUI creation, the more you will find that doing this will put your GUI in a straight-jacket, painting it in a very tight corner and making it very hard to extend or enhance. Just don't do this.
will ask here, coz its same project
so it shuld work like this.... 3 buttons, and under each button is hiden panel with two button, so whan some button is clicked under him shuld show panel, whan some ather button is clicked under him shuld show panel, but ather two panels shuld hide.... and this works great until some button is clicked 2 time in a row, after that whan i click some ather button panel under that button dont wont to hide..
here is the code
JPanel mainMenu = new JPanel();
mainMenu.setBounds(200, 110, screenSize.width - 400, screenSize.height - (screenSize.height - 30));
contentPane.add(mainMenu);
mainMenu.setLayout(new GridLayout(1, 0, 0, 0));
JButton btnTrkacke = new JButton("Trka\u010Dke");
btnTrkacke.setBackground(SystemColor.text);
mainMenu.add(btnTrkacke);
btnTrkacke.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
panTrk = new JPanel();
panTrk.setBounds(201, 140, (screenSize.width - 400) / 3, 30);
contentPane.add(panTrk);
panTrk.setLayout(new GridLayout(1, 0, 0, 0));
JButton btnTrkAtl = new JButton("Atleti\u010Dari");
btnTrkAtl.setBackground(SystemColor.text);
panTrk.add(btnTrkAtl);
JButton btnTrkDisc = new JButton("Discipline");
btnTrkDisc.setBackground(SystemColor.text);
panTrk.add(btnTrkDisc);
contentPane.revalidate();
contentPane.repaint();
panSka.setVisible(false);
panBac.setVisible(false);
}
});
JButton btnSkakacke = new JButton("Skaka\u010Dke");
btnSkakacke.setBackground(SystemColor.text);
mainMenu.add(btnSkakacke);
btnSkakacke.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
panSka = new JPanel();
panSka.setBounds(201 + (screenSize.width - 400) / 3, 140, (screenSize.width - 400) / 3, 30);
contentPane.add(panSka);
panSka.setLayout(new GridLayout(1, 0, 0, 0));
JButton btnSkaAtl = new JButton("Atleti\u010Dari");
btnSkaAtl.setBackground(SystemColor.text);
panSka.add(btnSkaAtl);
JButton btnSkaDisc = new JButton("Discipline");
btnSkaDisc.setBackground(SystemColor.text);
panSka.add(btnSkaDisc);
contentPane.revalidate();
contentPane.repaint();
panTrk.setVisible(false);
panBac.setVisible(false);
}
});
JButton btnBacacke = new JButton("Baca\u010Dke");
btnBacacke.setBackground(SystemColor.text);
mainMenu.add(btnBacacke);
btnBacacke.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
panBac = new JPanel();
panBac.setBounds(201 + (screenSize.width - 400) / 3 * 2, 140, (screenSize.width - 400) / 3, 30);
contentPane.add(panBac);
panBac.setLayout(new GridLayout(1, 0, 0, 0));
JButton btnBacAtl = new JButton("Atleti\u010Dari");
btnBacAtl.setBackground(SystemColor.text);
panBac.add(btnBacAtl);
JButton btnBacDisc = new JButton("Discipline");
btnBacDisc.setBackground(SystemColor.text);
panBac.add(btnBacDisc);
contentPane.revalidate();
contentPane.repaint();
panSka.setVisible(false);
panTrk.setVisible(false);
}
});

Increasing distance from top of JPanel

I'm trying to increase the distance of my JButtons from the top of my Panel to make it more visually appealing, i've tried using an invisible button but have had no luck.
public class SimpleBorder {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Border etched = (Border) BorderFactory.createEtchedBorder();
String[] items = {"A", "B", "C", "D"};
JList list = new JList(items);
JTextArea text = new JTextArea(10, 40);
JScrollPane scrol = new JScrollPane(text);
JScrollPane scrol2 = new JScrollPane(list);
JPanel panel= new JPanel();
panel.add(scrol2,BorderLayout.WEST);
panel.add(scrol, BorderLayout.EAST);
panel.setBorder(etched);
frame.add(panel);
frame.setVisible(true);
}
}
Any ideas ?
The key basically lies, in the fact, that the component doesn't knows it's actual size, till frame.pack() won't be called. Hence after this I am performing this calculation, to determine how much empty space to put for Border and again calling frame.pack() to repack() everything after putting the Border.
Please do have a look at this example, and see if this suite your needs :
import java.awt.*;
import javax.swing.*;
public class MainMenu {
private JButton playButton;
private JButton instructionButton;
private JButton scoreboardButton;
private JButton exitButton;
private JPanel menuPanel;
private GridBagConstraints gbc;
public MainMenu() {
gbc = new GridBagConstraints();
gbc.insets = new Insets(15, 15, 15, 15);
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
}
private void displayGUI() {
JFrame frame = new JFrame("Main Menu");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel(new BorderLayout());
menuPanel = new JPanel(new GridBagLayout());
menuPanel.setOpaque(true);
menuPanel.setBackground(Color.BLACK);
playButton = new JButton("Play");
instructionButton = new JButton("Instructions");
scoreboardButton = new JButton("Scoreboard");
exitButton = new JButton("Exit");
addComp(menuPanel, playButton, 0, 0, 1, 1, 1.0, 0.20,
GridBagConstraints.HORIZONTAL);
addComp(menuPanel, instructionButton, 0, 1, 1, 1, 1.0, 0.20,
GridBagConstraints.HORIZONTAL);
addComp(menuPanel, scoreboardButton, 0, 2, 1, 1, 1.0, 0.20,
GridBagConstraints.HORIZONTAL);
addComp(menuPanel, exitButton, 0, 3, 1, 1, 1.0, 0.20,
GridBagConstraints.HORIZONTAL);
contentPane.add(menuPanel);
frame.setContentPane(contentPane);
frame.pack();
contentPane.setBorder(
BorderFactory.createEmptyBorder(
contentPane.getHeight() - (contentPane.getHeight() / 4),
20, 5, 20));
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private void addComp(JPanel panel, JComponent comp,
int gridx, int gridy,
int gridwidth, int gridheight,
double weightx, double weighty,
int fill) {
gbc.gridx = gridx;
gbc.gridy = gridy;
gbc.gridwidth = gridwidth;
gbc.gridheight = gridheight;
gbc.weightx = weightx;
gbc.weighty = weighty;
gbc.fill = fill;
panel.add(comp, gbc);
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
new MainMenu().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
Here is the output :
EDIT 1 :
Moreover, if you will use GridLayout instead of using GridBagLayout for the MainMenu, then I guess the results will be more promising. Please have a look at this example for that change :
import java.awt.*;
import javax.swing.*;
public class MainMenu {
private JButton playButton;
private JButton instructionButton;
private JButton scoreboardButton;
private JButton exitButton;
private JPanel menuPanel;
private void displayGUI() {
JFrame frame = new JFrame("Main Menu");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel(new GridBagLayout());
menuPanel = new JPanel(new GridLayout(0, 1, 5, 5));
menuPanel.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
menuPanel.setOpaque(true);
menuPanel.setBackground(Color.BLACK);
playButton = new JButton("Play");
instructionButton = new JButton("Instructions");
scoreboardButton = new JButton("Scoreboard");
exitButton = new JButton("Exit");
menuPanel.add(playButton);
menuPanel.add(instructionButton);
menuPanel.add(scoreboardButton);
menuPanel.add(exitButton);
contentPane.add(menuPanel);
frame.setContentPane(contentPane);
frame.pack();
contentPane.setBorder(
BorderFactory.createEmptyBorder(
contentPane.getHeight() -
(contentPane.getHeight() -
(3 * menuPanel.getHeight())),
20, 0, 20));
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
new MainMenu().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
EDIT 2 :
Another variant is looking much better, though, this time, the base JPanel is using GridLayout and the MenuPanel is using GridBagLayout. Please have a look at this example :
import java.awt.*;
import javax.swing.*;
public class MainMenu {
private JButton playButton;
private JButton instructionButton;
private JButton scoreboardButton;
private JButton exitButton;
private JPanel menuPanel;
private GridBagConstraints gbc;
public MainMenu() {
gbc = new GridBagConstraints();
gbc.insets = new Insets(15, 15, 15, 15);
gbc.anchor = GridBagConstraints.CENTER;
}
private void displayGUI() {
JFrame frame = new JFrame("Main Menu");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel(new GridLayout(1, 1, 5, 2));
menuPanel = new JPanel(new GridBagLayout());
menuPanel.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
menuPanel.setOpaque(true);
menuPanel.setBackground(Color.BLACK);
playButton = new JButton("Play");
instructionButton = new JButton("Instructions");
scoreboardButton = new JButton("Scoreboard");
exitButton = new JButton("Exit");
addComp(menuPanel, playButton, 0, 0, 1, 1, 1.0, 0.10,
GridBagConstraints.CENTER);
addComp(menuPanel, instructionButton, 0, 1, 1, 1, 1.0, 0.10,
GridBagConstraints.CENTER);
addComp(menuPanel, scoreboardButton, 0, 2, 1, 1, 1.0, 0.10,
GridBagConstraints.CENTER);
addComp(menuPanel, exitButton, 0, 3, 1, 1, 1.0, 0.10,
GridBagConstraints.CENTER);
contentPane.add(menuPanel);
frame.setContentPane(contentPane);
frame.pack();
contentPane.setBorder(
BorderFactory.createEmptyBorder(
contentPane.getHeight() -
(contentPane.getHeight() -
(2 * menuPanel.getHeight()) + 100),
20, 2, 20));
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private void addComp(JPanel panel, JComponent comp,
int gridx, int gridy,
int gridwidth, int gridheight,
double weightx, double weighty,
int fill) {
gbc.gridx = gridx;
gbc.gridy = gridy;
gbc.gridwidth = gridwidth;
gbc.gridheight = gridheight;
gbc.weightx = weightx;
gbc.weighty = weighty;
gbc.fill = fill;
panel.add(comp, gbc);
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
new MainMenu().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}

Component size in SpringLayout

I use SpringLayout on my form, But as you see, its look isn't good (large and bad size)!
public class t8 extends JFrame {
JButton okButton, cancellButton;
JTextField idTF, nameTf;
JLabel idlbl, namelbl;
public t8() {
add(createPanel(), BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 500);
setLocation(400, 100);
setVisible(true);
}
public static void main(String[] args) {
new t8();
}
public JPanel createPanel() {
JPanel panel = new JPanel();
okButton = new JButton("Ok");
cancellButton = new JButton("Cancel");
idTF = new JTextField(10);
nameTf = new JTextField(10);
idlbl = new JLabel("ID");
namelbl = new JLabel("Name");
panel.add(idlbl);
panel.add(idTF);
panel.add(namelbl);
panel.add(nameTf);
panel.add(okButton);
panel.add(cancellButton);
panel.setLayout(new SpringLayout());
SpringUtilities.makeCompactGrid(panel, 3, 2, 20, 50, 50, 100);
return panel;
}
}
I change makeCompactGrid numbers, But was not success!
(The width of JTextFields are large, and my button's size are different)
If you don't care about the layout manager, but only care about the layout, then you should use a GridLayout, or if you don't want all component to be the same size, a GridBagLayout. Here's how with a grid layout (only the modified method is shown):
public JPanel createPanel() {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout());
okButton = new JButton("Ok");
cancellButton = new JButton("Cancel");
idTF = new JTextField(10);
nameTf = new JTextField(10);
idlbl = new JLabel("ID");
namelbl = new JLabel("Name");
panel.add(idlbl);
panel.add(idTF);
panel.add(namelbl);
panel.add(nameTf);
panel.add(okButton);
panel.add(cancellButton);
return panel;
}
And with a GridBagLayout:
public JPanel createPanel() {
JPanel panel = new JPanel();
GridBagLayout gb = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
panel.setLayout(gb);
okButton = new JButton("Ok");
cancellButton = new JButton("Cancel");
idTF = new JTextField(10);
nameTf = new JTextField(10);
idlbl = new JLabel("ID");
namelbl = new JLabel("Name");
add(panel, idlbl, 0, 0, 1, 1, gb, gbc, false);
add(panel, idTF, 0, 1, 1, 1, gb, gbc, true);
add(panel, namelbl, 1, 0, 1, 1, gb, gbc, false);
add(panel, nameTf, 1, 1, 1, 1, gb, gbc, true);
add(panel, okButton, 2, 0, 1, 1, gb, gbc, false);
add(panel, cancellButton, 2, 1, 1, 1, gb, gbc, true);
return panel;
}
private void add(Container outer, Component c, int x, int y, int w, int h, GridBagLayout gb, GridBagConstraints gbc, boolean wide) {
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = w;
gbc.gridheight = h;
if (wide) {
gbc.weightx = 100;
} else {
gbc.weightx = 0;
}
gb.setConstraints(c, gbc);
outer.add(c);
}
I believe that the extra GridBagLayout complexity just might be worth it.
I would suggest you to use Netbeans drag and drop tool which will allow you to set the components physically and will also give you the preview.
If you want to do it with code just use the free layout and set the location and size of every component manually By setSize() and setLocation() methods, although this will require more lines of code but will ensure you that all the components are in their correct position.

Categories