Swing: GlassPane and the custom painted semitransparent Buttons - java

I have a short toolbar at the left side of my application. When user points this toolbar, I open a semitransparent full toolbar (I use GlassPane to do it). All except semitransparency works fine.
Here is the screenshot of my example program:
As you see the first button is painted correctly, but all another have completly transparent background.
Here is my code (SSCCE):
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
import javax.swing.plaf.basic.BasicButtonUI;
import javax.swing.plaf.metal.MetalLookAndFeel;
/**
* <code>FlyOutExample</code>.
*/
public class FlyOutExample implements Runnable {
private static final String[] BUTTONS = {"First button", "Second", "Another button", "Last Button", "End"};
private static final Color HT_BLUE = new Color(0, 0, 255, 160); // half transparent blue
private JPanel shortPanel = new JPanel(new GridLayout(5, 1));
private JPanel fullPanel = new JPanel(new GridLayout(5, 1));
private JPanel fullPanelWrapper = new JPanel(new BorderLayout());
private JPanel shortPanelWrapper = new JPanel(new BorderLayout());
private JFrame frm;
public static void main(String[] args) {
SwingUtilities.invokeLater(new FlyOutExample());
}
#Override
public void run() {
try {
UIManager.setLookAndFeel(MetalLookAndFeel.class.getName());
} catch (Exception e) {
e.printStackTrace();
}
for (String s : BUTTONS) {
JButton b = new JButton(s.substring(0, 1));
b.setBackground(Color.BLUE);
b.setForeground(Color.RED);
b.setUI(new BasicButtonUI());
shortPanel.add(b);
b = new JButton(s);
b.setForeground(Color.RED);
b.setOpaque(false);
b.setHorizontalAlignment(SwingConstants.LEADING);
b.setBackground(HT_BLUE);
b.setUI(new BasicButtonUI() {
#Override
public void update(Graphics g, JComponent c) {
Color old = g.getColor();
g.setColor(HT_BLUE);
g.fillRect(0, 0, c.getWidth(), c.getHeight());
g.setColor(old);
paint(g, c);
}
});
fullPanel.add(b);
}
frm = new JFrame("Flyout example");
shortPanelWrapper.setOpaque(false);
shortPanelWrapper.add(shortPanel, BorderLayout.NORTH);
JPanel bluePanel1 = new JPanel();
bluePanel1.setOpaque(true);
bluePanel1.setBackground(Color.BLUE);
shortPanelWrapper.add(bluePanel1);
fullPanel.setOpaque(false);
fullPanelWrapper.setOpaque(false);
fullPanelWrapper.add(fullPanel, BorderLayout.NORTH);
JPanel bluePanel2 = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
Color old = g.getColor();
g.setColor(HT_BLUE);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(old);
}
};
bluePanel2.setOpaque(false);
fullPanelWrapper.add(bluePanel2);
MouseListener openListener = new OpenSideBarListener();
for (Component c : shortPanel.getComponents()) {
c.addMouseListener(openListener);
}
bluePanel1.addMouseListener(openListener);
MouseListener closeListener = new CloseSideBarListener();
for (Component c : fullPanel.getComponents()) {
c.addMouseListener(closeListener);
}
bluePanel2.addMouseListener(closeListener);
JPanel topPanel = new JPanel();
topPanel.setBackground(Color.GREEN);
topPanel.setPreferredSize(new Dimension(0, 30));
JPanel bottomPanel = new JPanel();
bottomPanel.setBackground(Color.GREEN);
bottomPanel.setPreferredSize(new Dimension(0, 30));
frm.add(topPanel, BorderLayout.NORTH);
frm.add(bottomPanel, BorderLayout.SOUTH);
frm.add(shortPanelWrapper, BorderLayout.WEST);
frm.add(new JScrollPane(new JTable(40, 7)));
frm.pack();
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frm.setLocationRelativeTo(null);
frm.setVisible(true);
}
private void openPopup() {
if (shortPanelWrapper.getMousePosition() != null) {
Container glassPane = (Container) frm.getGlassPane();
glassPane.setLayout(null);
fullPanelWrapper.setLocation(shortPanelWrapper.getLocation());
fullPanelWrapper.setSize(140, shortPanelWrapper.getHeight());
glassPane.add(fullPanelWrapper);
glassPane.setVisible(true);
}
}
private void closePopup() {
if (fullPanelWrapper.getMousePosition() == null) {
Container glassPane = (Container) frm.getGlassPane();
glassPane.removeAll();
glassPane.setVisible(false);
}
}
private class OpenSideBarListener extends MouseAdapter {
#Override
public void mouseEntered(MouseEvent e) {
openPopup();
}
}
private class CloseSideBarListener extends MouseAdapter {
#Override
public void mouseExited(MouseEvent e) {
closePopup();
}
}
}
My JDK is: 1.8_91, OS: Windows 7
My question is: what should I do to paint all my buttons correct?
P.S. In real application I have a custom UI for all buttons present in the left toolbar, so please don't remove the UI for my buttons.
UPDATE
I've started the app again (without any changes) and got another bug
Here ist the new picture:
Probably it's a bug of my graphic card?

Related

Java - how to zoom in/zoom out text in JTextArea

I am writing in a notepad. And I want to implement text scaling in my notepad. But I don't know how to do it. I'm trying to find it but everyone is suggesting to change the font size. But I need another solution.
I am create new project and add buttons and JTextArea.
package zoomtest;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JTextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class zoom {
private JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
zoom window = new zoom();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public zoom() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.NORTH);
JButton ZoomIn = new JButton("Zoom in");
ZoomIn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//Code here...
}
});
panel.add(ZoomIn);
JButton Zoomout = new JButton("Zoom out");
Zoomout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//Code here...
}
});
panel.add(Zoomout);
JTextArea jta = new JTextArea();
frame.getContentPane().add(jta, BorderLayout.CENTER);
}
}
Introduction
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section. Pay close attention to the Laying Out Components Within a Container section.
I reworked your GUI. Here's how it looks when the application starts. I typed some text so you can see the font change.
Here's how it looks after we zoom out.
Here's how it looks after we zoom in.
Stack Overflow scales the images, so it's not as obvious that the text is zooming.
Explanation
Swing was designed to be used with layout managers. I created two JPanels, one for the JButtons and one for the JTextArea. I put the JTextArea in a JScrollPane so you could type more than 10 lines.
I keep track of the font size in an int field. This is a simple application model. Your Swing application should always have an application model made up of one or more plain Java getter/setter classes.
Code
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class ZoomTextExample {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
new ZoomTextExample();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private int pointSize;
private Font textFont;
private JFrame frame;
private JTextArea jta;
private JTextField pointSizeField;
public ZoomTextExample() {
this.pointSize = 16;
this.textFont = new Font(Font.DIALOG, Font.PLAIN, pointSize);
initialize();
}
private void initialize() {
frame = new JFrame("Text Editor");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createButtonPanel(), BorderLayout.NORTH);
frame.add(createTextAreaPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
JButton zoomIn = new JButton("Zoom in");
zoomIn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
incrementPointSize(+2);
updatePanels();
}
});
panel.add(zoomIn);
panel.add(Box.createHorizontalStrut(20));
JLabel label = new JLabel("Current font size:");
panel.add(label);
pointSizeField = new JTextField(3);
pointSizeField.setEditable(false);
pointSizeField.setText(Integer.toString(pointSize));
panel.add(pointSizeField);
panel.add(Box.createHorizontalStrut(20));
JButton zoomOut = new JButton("Zoom out");
zoomOut.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
incrementPointSize(-2);
updatePanels();
}
});
panel.add(zoomOut);
return panel;
}
private JPanel createTextAreaPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
jta = new JTextArea(10, 40);
jta.setFont(textFont);
JScrollPane scrollPane = new JScrollPane(jta);
panel.add(scrollPane, BorderLayout.CENTER);
return panel;
}
private void updatePanels() {
pointSizeField.setText(Integer.toString(pointSize));
textFont = textFont.deriveFont((float) pointSize);
jta.setFont(textFont);
frame.pack();
}
private void incrementPointSize(int increment) {
pointSize += increment;
}
}

Why can't I change the JButton (disabled) text color?

I started programming Java. This is my first window application. I did a simple tic-tac-toe game and I want the "o" button font color to be a different color. But it doesn't work. I can change the background color, but not the fonts, why?
package moje;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.print.PrinterJob;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JTextField;
public class Kolko_i_krzyzyk extends JFrame implements ActionListener {
static JTextField tekst;
static JLayeredPane ekran = new JLayeredPane();
static JButton button = new JButton();
static int licznik=0;
public Kolko_i_krzyzyk () {
super("Kółko i krzyżyk");
ekran = new JLayeredPane();
setVisible(true);
setSize(800, 800);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
//Siatka podzielona 3 na 3
setLayout(new GridLayout(3,3));
//Tworzenie 9 przycisków
for(int i = 1; i<=9; i++) {
JButton button = new JButton();
add(button);
button.addActionListener(this);
}
}
public static void main(String[] args) {
JFrame okno = new Kolko_i_krzyzyk();
}
#Override
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
if(licznik%2==0 ) {
button.setText("x");
button.setFont(new Font ("Arial", Font.BOLD, 90));
}
else {
button.setText("O");
button.setForeground(Color.RED);
button.setFont(new Font ("Arial", Font.BOLD, 90));
}
button.setEnabled(false);
licznik++;
}
}
The issue here is the default behavior when disabling the JButton via setEnabled(false).
This will grey out the button and ignore any color formatting you did to the text (foreground).
There are several workarounds to modify this behavior (as seen in this similar question).
Here is a short demonstration (without the final game logic of course) , which changes the UI of the JButton via setUI().
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.plaf.metal.MetalButtonUI;
public class Test {
private int counter = 0;
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new Test().buildGui());
}
private void buildGui() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.add(panel);
panel.setLayout(new GridLayout(3, 3));
for (int i = 1; i <= 9; i++) {
JButton button = new JButton() {
#Override
public Dimension getPreferredSize() {
return new Dimension(150, 150);
}
};
button.setFont(new Font("Arial", Font.BOLD, 90));
panel.add(button);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (counter % 2 == 0) {
button.setText("X");
button.setUI(new MetalButtonUI() {
// override the disabled text color for the button UI
protected Color getDisabledTextColor() {
return Color.BLUE;
}
});
} else {
button.setText("O");
button.setUI(new MetalButtonUI() {
protected Color getDisabledTextColor() {
return Color.RED;
}
});
}
button.setEnabled(false);
counter++;
}
});
}
frame.pack();
frame.setVisible(true);
}
}
Result:
Another (simpler) way to do it would be to build some ImageIcons for "X" and "O", then set these on the buttons via setIcon()/setDisabledIcon(). This would save you the trouble from modifying the button UI.

JDialog only load at the end of the program

I am using a JDialog for a project, which is load when I click on a button located inside a JFrame.
This JDialog is supposed to display an image, but the image appears only when the code called by the JFrame class is executed. My problem is that I want the image to be displayed when I call it, not at the end of my programm.
Here is my code of the JDialog :
public class LoadingWindow {
private JDialog dialog;
public LoadingWindow() {
this.dialog = new JDialog();
this.dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
this.dialog.setTitle("Veuillez patienter");
this.dialog.setSize(300, 200);
URL url = LoadingWindow.class.getResource("/images/wait.gif");
ImageIcon icon = new ImageIcon(url);
JLabel imageLabel = new JLabel();
imageLabel.setIcon(icon);
imageLabel.setHorizontalAlignment(JLabel.CENTER);
imageLabel.setVerticalAlignment(JLabel.CENTER);
this.dialog.getContentPane().add(imageLabel);
this.dialog.setLocationRelativeTo(null);
this.dialog.setVisible(true);
}
public void stop() {
this.dialog.dispose();
}
}
Inside my JFrame, I call the JDialog this way :
MyJDialog mjd = new MyJDialog ();
[CODE]
mjd.stop();
Thanks !
Here's an example of a GUI that opens a JDialog.
Here's the image I used.
I create a JFrame and a JPanel with a JButton. The JButton has an ActionListener that opens a JDialog. The JDialog displays the car image.
Here's the complete runnable code I used.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class JDialogTest implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new JDialogTest());
}
private JFrame frame;
#Override
public void run() {
frame = new JFrame("JDialog Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(
150, 100, 150, 100));
panel.setPreferredSize(new Dimension(400, 400));
JButton button = new JButton("Open JDialog");
button.addActionListener(new ButtonListener());
panel.add(button);
return panel;
}
public class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
new CalculateDecor(frame, "Spash Screen");
}
}
public class CalculateDecor extends JDialog {
private static final long serialVersionUID = 1L;
public CalculateDecor(JFrame frame, String title) {
super(frame, true);
Image image = getImage();
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setTitle(title);
JPanel panel = new JPanel(new BorderLayout());
JLabel label = new JLabel();
label.setHorizontalAlignment(JLabel.CENTER);
label.setIcon(new ImageIcon(image));
panel.add(label);
add(panel);
pack();
setLocationRelativeTo(frame);
setVisible(true);
System.out.println(getDecorationSize());
}
private Dimension getDecorationSize() {
Rectangle window = getBounds();
Rectangle content = getContentPane().getBounds();
int width = window.width - content.width;
int height = window.height - content.height;
return new Dimension(width, height);
}
private Image getImage() {
try {
return ImageIO.read(getClass().getResourceAsStream(
"/car.jpg"));
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
}

java removing tabs and restoring jpanel back to original

i have a jpanel (jpanel A) with a button and when pressed
will open a tab jpanel (example 1)
so when you press the button you end up with 2 tabs jpanel A and example 1.
the original japanel is now a tabbed panel
when i delete example 1 i am left with jpanel A however this panel is in a tab
.
is there a way that i can revert back to the original jpanel when the other jpanel (example 1) is deleted.
i have made a sample application similar to mine:
after clicking on call a jpanel you get.
Then click press for tab 2 times you get 2 new tabs
after removing the 2 tabs you get:
WHAT I AM TRYING TO DO IS END UP WITH THIS:
i.e. BACK TO THE ORIGINAL REMOVE THE TAB KEEP THE CONTENT
THE APPLICATION IS SPLIT INTO 3 CLASSES.
CreatePanel to make the right hand side jpanel and hold the button to make tab.
MainGUI to create the jframe left side to call a panel on the right side.
CloseButtonTabbedPane to create the tab and control them.
here is the code:
MainGUI
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
public class MainGUI extends JFrame {
private JPanel jPanelLeft;
private JPanel jPanelRight;
private JButton callPanelBtn;
private JTabbedPane tab;
public MainGUI() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(1280, 600); // set frame size
this.setVisible(true); // display frame
this.setTitle("Tab Example");
setLayout(new BorderLayout()); // layout manager
jPanelLeft = new JPanel();
jPanelLeft.setLayout(null);
jPanelLeft.setPreferredSize(new Dimension(400, 800)); // to set the size of the left panel
jPanelLeft.setBackground(Color.blue);
this.add(jPanelLeft, BorderLayout.WEST);
callPanelBtn = new JButton("Call a jPanel");
callPanelBtn.addActionListener(btn);
callPanelBtn.setBounds(150, 200, 150, 40);
jPanelLeft.add(callPanelBtn);
jPanelRight = new JPanel();
jPanelRight.setBorder(new EmptyBorder(0, 0, 0, 0));
jPanelRight.setLayout(new GridLayout(0, 1));
this.add(jPanelRight);
tab = new CloseButtonTabbedPane();
}//endd constructor
ActionListener btn = new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if (ae.getActionCommand() == "Call a jPanel") {
jPanelRight.add(new CreatePanel(t));
jPanelRight.revalidate();
}
}
};
// Actionlistener for CreatePanel
ActionListener t = new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if (tab.getTabCount() <= 8) {
// if no tabs make main tab
if (tab.getTabCount() == 0) {
tab.addTab("Main Content", jPanelRight); // name for listener not to close
add(tab);
revalidate();
repaint();
}
if (tab.getTabCount() > 0) {
JPanel newJPanel = new JPanel();
tab.addTab("new ", newJPanel);
tab.setSelectedIndex(tab.getTabCount() - 1);
}
}
}
};
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MainGUI();
}
});
} // end main
}//end class
CreatePanel
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;
public class CreatePanel extends JPanel {
private JPanel jPanel1;
private final JButton tabBTN;
public CreatePanel(ActionListener t){
jPanel1 = new JPanel();
jPanel1.setLayout(null);
jPanel1.setBorder(BorderFactory.createBevelBorder(1, Color.lightGray, Color.lightGray));
jPanel1.setPreferredSize(new Dimension(850, 300));
jPanel1.setBackground(Color.green);
add(jPanel1);
//add button for tabs
tabBTN = new JButton("Press for Tab");
tabBTN.setBounds(400, 100, 150, 30);
tabBTN.addActionListener(t);
jPanel1.add(tabBTN);
}//end constructor
}//end class
CloseButtonTabbedPane
import javax.swing.*;
import javax.swing.plaf.metal.MetalIconFactory;
import javax.swing.plaf.basic.BasicTabbedPaneUI;
import java.awt.image.BufferedImage;
import java.awt.*;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class CloseButtonTabbedPane extends JTabbedPane {
public CloseButtonTabbedPane() {
}
#Override
public void addTab(String title, Icon icon, Component component, String tip) {
super.addTab(title, icon, component, tip);
int count = this.getTabCount() - 1;
setTabComponentAt(count, new CloseButtonTab(component, title, icon));
}
#Override
public void addTab(String title, Icon icon, Component component) {
addTab(title, icon, component, null);
}
#Override
public void addTab(String title, Component component) {
addTab(title, null, component);
}
public class CloseButtonTab extends JPanel {
private Component tab;
public CloseButtonTab(final Component tab, String title, Icon icon) {
this.tab = tab;
setOpaque(false);
FlowLayout flowLayout = new FlowLayout(FlowLayout.CENTER, 3, 3);
setLayout(flowLayout);
setVisible(true);
JLabel jLabel = new JLabel(title);
jLabel.setIcon(icon);
add(jLabel);
JButton button = new JButton(MetalIconFactory.getInternalFrameCloseIcon(16));
button.setMargin(new Insets(0, 0, 0, 0));
button.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 1));
button.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {
JTabbedPane tabbedPane = (JTabbedPane) getParent().getParent();
if (tabbedPane.getSelectedIndex() >= 1) {
tabbedPane.remove(tab);
}
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
JButton button = (JButton) e.getSource();
button.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY, 1));
}
public void mouseExited(MouseEvent e) {
JButton button = (JButton) e.getSource();
button.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 1));
}
});
add(button);
}
}
}
I don't know if there is factory solution but for all JComponents you can set a custom UI Object that handles the Look & Feel means the appearance using the setUI method. One implementation for JTabbedPanes is called BasicTabbedPaneUI and has a method calculateTabAreaHeight that should calulate the height of the Tab Bar on Top.
So you could set your own instance of BasicTabbedPaneUI to your JTabbedPane overriding this method to return 0 if only one tab exists.
Put this in your constructor
[...]
tab = new CloseButtonTabbedPane();
tab.setUI(new BasicTabbedPaneUI(){
#Override
protected int calculateTabAreaHeight(int tabPlacement, int horizRunCount, int maxTabHeight){
if (tab.getTabCount() == 1) return 0;
return super.calculateTabAreaHeight(tabPlacement, horizRunCount, maxTabHeight);
}
});

How to correctly update an Image in a JLabel?

I'm French so my English is quite bad but I have a real problem with java:
I'm trying to show an Image built manually with some fillRect & co.
It works. Next, I want to update this image as a function of the text I enter in the text field. And there is the problem: it doesn't change anything, and if I manually rescale the window of the JFrame, the image shows totally deformed or scaled badly.
I'm a beginner and I have difficulties with GUI, moreso when I want to couple it with Images.
Can you help me? Why doesn't it work as I want? This is my code below, a bit long but actually quite simple ! Thanks :)
I've changed it a bit, this is the 2e VERSION.
Now the problem s that I can't change a condition in order to modify the color of a simple rectangle, try "lol" in the entry field !
CODE VERSION 2
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Color;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.ImageIcon;
public class Fenetre extends JFrame {
private JFrame frame;
private JPanel container = new JPanel();
private JTextField jtf;
private JLabel label = new JLabel("Commandes ");
private JButton b = new JButton ("OK");
private Graphics graph;
private Image img;
private JLabel screen;
private boolean color;
/**
* Constructeur de l'objet
*/
public Fenetre(){
color = true;
frame = new JFrame();
frame.setTitle("Animation");
frame.setSize(1000, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
container.setBackground(Color.white);
container.setLayout(new BorderLayout());
JPanel top = new JPanel();
jtf = new JTextField();
jtf.setPreferredSize(new Dimension(800, 30));
b.addActionListener(new BoutonListener());
frame.setContentPane(top);
frame.setVisible(true);
paintComponent(graph);
screen = new JLabel( new ImageIcon(img));
top.add(screen);
top.add(label);
top.add(jtf);
top.add(b);
frame.setContentPane(top);
}
class BoutonListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
if(jtf.getText().equals("lol")) lol();
System.out.println("Entry : " + jtf.getText());
}
}
public void paintComponent(Graphics g)
{
if(img == null) {
img = frame.createImage(1000,300);
g = img.getGraphics();
}
g.setColor(Color.white);
g.fillRect(0,0,1000,300);
if(color) g.setColor(Color.orange); else g.setColor(Color.blue);
g.fillRect(8,25,200,100);
g.setColor(Color.green);
g.drawString("Text",10,10);
}
public void lol()
{
if(color) color = false; else color = true;
}
}
PREVIOUS CODE
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Color;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.ImageIcon;
public class Fenetre extends JFrame {
private JPanel container = new JPanel();
private JTextField jtf;
private JLabel label = new JLabel("Commandes ");
private JButton b = new JButton ("OK");
private Graphics g;
private Image img;
private JLabel screen;
/**
* Constructeur de l'objet
*/
public Fenetre(){
this.setTitle("Animation");
this.setSize(1000, 400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
container.setBackground(Color.white);
container.setLayout(new BorderLayout());
JPanel top = new JPanel();
jtf = new JTextField();
jtf.setPreferredSize(new Dimension(800, 30));
b.addActionListener(new BoutonListener());
this.setContentPane(top);
this.setVisible(true);
paint(g);
screen = new JLabel( new ImageIcon(img));
top.add(screen);
top.add(label);
top.add(jtf);
top.add(b);
this.setContentPane(top);
}
class BoutonListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
System.out.println("Entry : " + jtf.getText());
if(jtf.getText().equals("lol")) lol();
}
}
#Override
public void paint(Graphics g)
{
if(img == null) {
img = createImage(1000,300);
g = img.getGraphics();
}
g.setColor(Color.white);
g.fillRect(0,0,1000,300);
g.setColor(Color.orange);
g.fillRect(8,25,200,100);
g.setColor(Color.green);
g.drawString("Text",10,10);
}
#Override
public void update(Graphics g)
{
g.setColor(Color.blue);
g.fillRect(8,25,300,100);
}
public void lol()
{
g.setColor(Color.blue);
g.fillRect(8,25,200,100);
}
}
I see several problems in your code:
You are confusing your g member variable with the g parameter of the paint method. When lol is called, g is null and you get a NullPointerException
You should never grab a hold on Graphics (only in really rare cases). Instead you override properly paintComponent() and you use the Graphics parameter to draw what you want. When you want to update the component, you call repaint()
Don't override paint, but override paintComponent()
Don't override paint of JFrame. Use a dedicate component for that. No need to use a JLabel for that, a simple JComponent is enough.
Don't extend JFrame if you are not extending its functionality.
After adding components to the component hierarchy, call revalidate()
Fix those issues and come back with another question if you still have problems.
You should probably consider reading this tutorial and the few next steps. It will show you basic examples of things similar to what you are trying to do.
EDIT:
I took your V2 code and patched it as I could. This is very far from perfect but you should get the gist of how you can do this:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Fenetre extends JComponent {
private boolean color;
/**
* Constructeur de l'objet
*/
public Fenetre() {
color = true;
setPreferredSize(new Dimension(1000, 300));
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.white);
g.fillRect(0, 0, 1000, 300);
if (color) {
g.setColor(Color.orange);
} else {
g.setColor(Color.blue);
}
g.fillRect(8, 25, 200, 100);
g.setColor(Color.green);
g.drawString("Text", 10, 10);
}
public void lol() {
if (color) {
color = false;
} else {
color = true;
}
repaint();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
initUI();
}
});
}
protected static void initUI() {
JFrame frame = new JFrame();
frame.setTitle("Animation");
frame.setSize(1000, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
JPanel container = new JPanel();
final JTextField jtf = new JTextField();
final Fenetre fenetre = new Fenetre();
JLabel label = new JLabel("Commandes ");
JButton b = new JButton("OK");
container.setBackground(Color.white);
container.setLayout(new BorderLayout());
JPanel top = new JPanel();
jtf.setPreferredSize(new Dimension(800, 30));
class BoutonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (jtf.getText().equals("lol")) {
fenetre.lol();
}
System.out.println("Entry : " + jtf.getText());
}
}
b.addActionListener(new BoutonListener());
top.add(fenetre);
top.add(label);
top.add(jtf);
top.add(b);
top.revalidate();
frame.setContentPane(top);
frame.setVisible(true);
}
}
Your Swing graphics programming has several significant problems, and I urge you to go through the tutorials to learn how to do this better. For example, you are
calling the paint method directly -- something you should almost never do except in very special situations (this is not one of them)
Drawing directly in the JFrame's paint(...) method. Instead you will want to draw in the paintComponent(...) method override of a class derived from JComponent such as JPanel.
Calling update unnecessarily as if this were an AWT program. You don't do this in Swing unless you're changing the Look & Feel.
Again, take a look at the tutorials on this -- you will not regret doing this, trust me.
edit -- too slow! 1+ to Guillaume

Categories

Resources