Does somebody know how to remove white rectangle border on JButton ? This issue is there only for windows look & feel when the button is a little bit rounded.
Please find attached the example on the image.
Setting the border to empty or null doesn't help. The same for margin.
The white margin/border dissapear only when I set the opacity of the button to false, but unfortunately in this case also the whole button is opaque on some versions of windows.
When I set opacity to false, it looks like:
Code example:
public class TestFrame extends javax.swing.JFrame {
/**
* Auto-generated main method to display this JFrame
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
TestFrame inst = new TestFrame();
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}
});
}
public TestFrame() {
this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
this.setLayout(null);
this.getContentPane().setBackground(Color.BLACK);
JButton button = new JButton();
button.setBounds(10, 10, 100, 50);
button.setBorder(BorderFactory.createEmptyBorder()); // not working
button.setBorder(null); // not working
button.setMargin(new Insets(0,0,0,0)); // not working
add(button);
pack();
setSize(400, 300);
}
}
Thanks,
Lubos
Seems like a painting problem. You can use:
button.setBackground( Color.BLACK );
EDIT: See comments below. This sample still shows the effect, even using a proper layout. Setting the background color seems to show the unwanted border. This effect doesn't show with Metal. It seems as if Windows L&F shows a rounded edge, but the button is still rectangular. The space between is only noticable if the BG color of the container is changed to something obvious, like black.
import java.awt.*;
import javax.swing.*;
public class TestFrame extends JFrame
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e)
{
e.printStackTrace();
}
TestFrame inst = new TestFrame();
inst.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}
});
}
public TestFrame()
{
JButton button = new JButton("One");
JButton button2 = new JButton("Two");
JPanel p = new JPanel();
p.setBackground(Color.BLACK);
p.setLayout(new FlowLayout());
p.add(button);
p.add(button2);
add(p);
setSize(400, 300);
}
}
Related
Environment:
Using Netbeans 8.1
Oracle JDK 1.8
Win 10 pro
Context:
A GUI with a JCheckBoxMenuItem to change LookAndFeel(LAF) at runtime.
darkLAF=JTattoo's HiFi LAF
defaultLAF=Sun's Windows LAF(com.sun.java.swing.plaf.windows.WindowsLookAndFeel)
Problem:
GUI launches(in EDT) with defaultLAF. User changes to darkLAF..the title bar should have changed..it doesn't.
When the user switches back to defaultLAF, the JMenuItems(File and Edit) show greyer backgrounds not the defaultLAF style.
Screenshots:
The launched defaultLAF
upon switching to darkLAF
user switched back to defaultLAF
expected look for darkLAF
Code:
Inside the itemStateChangeListener for JCheckBoxMenuItem
try{
if (checkBox.isSelected())
UIManager.setLookAndFeel(darkLookAndFeel);
else
UIManager.setLookAndFeel(defaultLookAndFeel);
} catch (UnsupportedLookAndFeelException ex) {
//handle err
}
//GUI is a class extending JFrame
SwingUtilities.updateComponentTreeUI(this);
//some JFileChooser
SwingUtilities.updateComponentTreeUI(fc);
pack();
Catch:
User shouldn't be asked to do a GUI restart.
It was a little bit hard, but I've found a solution.
Steps you need to switch to the JTatto L&F
Dispose window
Set L&F
Set window style of root pane to JRootPane.FRAME
Update UI
Make Frame undecorated
Make Frame visible
Steps you need to switch back to Windows L&F
Dispose window
Set L&F
Update UI
Make Frame decorated
Make Frame visible
Here is the code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MinFrame extends JFrame {
public MinFrame() {
super("Minimal-Frame-Application");
// setup menu
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("File");
menu.setMnemonic('F');
JMenuItem menuItem = new JMenuItem("Exit");
menuItem.setMnemonic('x');
menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4, KeyEvent.ALT_MASK));
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
menu.add(menuItem);
menuBar.add(menu);
setJMenuBar(menuBar);
// setup widgets
JPanel contentPanel = new JPanel(new BorderLayout());
contentPanel.setBorder(BorderFactory.createEmptyBorder(0, 4, 4, 4));
JScrollPane westPanel = new JScrollPane(new JTree());
JEditorPane editor = new JEditorPane("text/plain", "Hello World");
JScrollPane eastPanel = new JScrollPane(editor);
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, westPanel,eastPanel);
splitPane.setDividerLocation(148);
contentPanel.add(splitPane, BorderLayout.CENTER);
AbstractButton winLF = new JButton("Windows");
winLF.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
MinFrame.this.dispose();
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.updateComponentTreeUI(MinFrame.this.getRootPane());
MinFrame.this.setUndecorated(false);
MinFrame.this.setVisible(true);
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
AbstractButton customLF = new JButton("JTatto");
customLF.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
MinFrame.this.dispose();
UIManager.setLookAndFeel("com.jtattoo.plaf.smart.SmartLookAndFeel");
MinFrame.this.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
SwingUtilities.updateComponentTreeUI(MinFrame.this.getRootPane());
MinFrame.this.setUndecorated(true);
MinFrame.this.setVisible(true);
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
JPanel buttons = new JPanel();
buttons.add(winLF);
buttons.add(customLF);
contentPanel.add(buttons, BorderLayout.SOUTH);
setContentPane(contentPanel);
// add listeners
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
// show application
setLocation(32, 32);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(400, 300);
setVisible(true);
} // end CTor MinFrame
public static void main(String[] args) {
try {
// select Look and Feel
// UIManager.setLookAndFeel("com.jtattoo.plaf.smart.SmartLookAndFeel");
// start application
new MinFrame();
}
catch (Exception ex) {
ex.printStackTrace();
}
} // end main
}
I'm trying to create a GUI with java. My gui will be simple. You can see what I want from here : http://sketchtoy.com/64839370
In order to do that, I have decided to use BorderLayout as suggested on the web. I have two Jpanel object and I have put them into jFrame whose layout is borderlayout. You can see my simplified code below :
private Display display= new Display(); // Display extends JPanel
public Simulation()
{
super();
// frame settings
setTitle("Label of JFrame ");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setBounds(100,100,1094,560);
contentPane=this.getContentPane();
setResizable(false);
contentPane.setLayout(new BorderLayout());
try {
LeftPanelLogo=ImageIO.read(new File("logo.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// generate left panel (information panel)
leftPanel=new JPanel(){
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d=(Graphics2D)g;
g2d.drawImage(LeftPanelLogo, 10, 250, null);
}
};
//leftPanel.setLayout(null);
// add panels to contentPane
leftPanel.setBackground(Color.WHITE);
display.setBackground(Color.BLACK);
contentPane.add(leftPanel,BorderLayout.WEST);
contentPane.add(display,BorderLayout.CENTER);
}
In Display class constructor I have only the following code:
try
{
bgPicture = ImageIO.read(new File("bg.jpg"));
}
catch (IOException e)
{
e.printStackTrace();
}
When I run the code, I saw that almost all the screen is fulfilled with the panel which is on the center, and I could not see the leftPanel, (in other words, all screen was black since I set the background of display panel to black)
So, how could I fix it ?
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class LogoLayout {
private JComponent ui = null;
LogoLayout() {
initUI();
}
public void initUI() {
if (ui!=null) return;
ui = new JPanel(new BorderLayout(4,4));
ui.setBorder(new EmptyBorder(4,4,4,4));
BufferedImage logo = new BufferedImage(
276,560,BufferedImage.TYPE_INT_RGB);
/* All that's needed */
ui.add(new JLabel(new ImageIcon(logo)), BorderLayout.LINE_START);
ui.add(new JTextArea("Display", 3, 44));
/* All that's needed */
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
LogoLayout o = new LogoLayout();
JFrame f = new JFrame("Logo Layout");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
the script works fine for dragging around one image but if I try to get two of them going at once it acts as if the class can only be called once? here is the code where i am adding two imageicons , but only one is showing:
import java.awt.*;
import javax.swing.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseAdapter;
public class TestMouseDrag {
public static void main(String[] args) {
new TestMouseDrag();
}
public TestMouseDrag() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new DragMyIcon("C:\\Users\\anon\\Desktop\\Hobbit.png")).setLocation(100, 100);
frame.add(new DragMyIcon("C:\\Users\\anon\\Desktop\\alien.png")).setLocation(100, 100)
frame.pack();
frame.setSize(700,700);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class DragMyIcon extends JPanel {
public static final long serialVersionUID = 172L;
private JLabel label;
public DragMyIcon(String path) {
setLayout(null);
ImageIcon icon = null;
icon = new ImageIcon(path);
label = new JLabel(icon);
label.setBounds(0,0,100, 100);
label.setHorizontalAlignment(JLabel.CENTER);
label.setVerticalAlignment(JLabel.CENTER);
add(label);
MouseHandler handler = new MouseHandler();
label.addMouseListener(handler);
label.addMouseMotionListener(handler);
}
}
protected class MouseHandler extends MouseAdapter {
private boolean active = false;
private int xDisp;
private int yDisp;
#Override
public void mousePressed(MouseEvent e) {
active = true;
JLabel label = (JLabel) e.getComponent();
xDisp = e.getPoint().x - label.getLocation().x;
yDisp = e.getPoint().y - label.getLocation().y;
label.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
}
#Override
public void mouseReleased(MouseEvent e) {
active = false;
JLabel label = (JLabel) e.getComponent();
label.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
#Override
public void mouseDragged(MouseEvent e) {
if (active) {
JLabel label = (JLabel) e.getComponent();
Point point = e.getPoint();
label.setLocation(point.x - xDisp, point.y - yDisp);
label.invalidate();
label.repaint();
}
}
#Override
public void mouseMoved(MouseEvent e) {
}
}}
Your code does not respect the layout managers that it is using -- BorderLayout. When you add a component to a BorderLayout using container without specifying position, it is placed by default BorderLayout.CENTER and covers anything added previously.
Solution: read up on the layout managers including BorderLayout to see how to use them.
Also, you're probably better off not adding two DragMyIcon objects, but rather changing DragMyIcon so that it allows for multiple JLabels.
I've looked around and viewed various threads on here. the one I found closest to what I'm attempting to do is this one:
Hovering over JButtons and displaying a message
Basically I'm trying to replace button.setToolTipText(""); with an ImageIcon. I'm using this as a preview of the next page you're about to visit inside the JFrame, to give to user an Idea or quick overview of the next page. (I have figured out the imaging, just not the ToolTip).
Here is what I tried using based on what I've seen in the various thread, but obviously it didn't work, hence I'm asking this question.
Code I used: Log.setToolTip(new ImageIcon(getIconLog));
You can use MouseListener and JLabel act as a tooltip. Like this...
public static void main(String[] args){
final JFrame f = new JFrame();
f.setSize(500, 400);
f.setVisible(true);
f.setLayout(null);
f.setDefaultCloseOperation(3);
final JButton b = new JButton("ToolTip");
b.setBounds(100, 100, 70, 70);
f.add(b);
final JLabel toolTip = new JLabel();
b.addMouseListener(new MouseListener() {
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
f.remove(toolTip);
f.repaint();
}
#Override
public void mouseEntered(MouseEvent e) {
try {
toolTip.setIcon(new ImageIcon(ImageIO.read(new File("your image"))));
} catch (IOException e1) {
e1.printStackTrace();
}
toolTip.setBounds(b.getLocation().x+b.getWidth(), b.getLocation().y-b.getHeight(), 100, 50);
f.add(toolTip);
f.repaint();
}
#Override
public void mouseClicked(MouseEvent e) {
}
});
}
I had a friend make a background for the program I made so that it wouldn't look so plain, and I thought the best way to place the images would be to make a JLabel, fill it with an image, and set it to the size of the screen. This worked fine, except there is a small border around the JFrame and I can't get the JLabel to touch the edges of the frame. Thoughts? I have attached a picture.
public class ProgramDriver extends JFrame {
private JPanel contentPane;
private static CardLayout cardLayout;
private JTextField addGradeN;
private JTextField addGradeD;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ProgramDriver frame = new ProgramDriver();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
//Global Variables
...
manager = new StateManager(gb);
//JFrame Settings
setTitle("Grade Book");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 656, 530);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
cardLayout = new CardLayout(0,0);
contentPane.setLayout(cardLayout);
setResizable(false);
//Home Panel
final JPanel Home = new JPanel();
contentPane.add(Home, "Home");
Home.setLayout(null);
JButton btnSeeGrades = new JButton("See Grades");
...
//Grades Panel
JPanel Grades = new JPanel();
contentPane.add(Grades, "Grades");
Grades.setLayout(null);'
The problem isn't with the JFrame, the problem is with your code. We can spend the rest of our natural life at guessing what's wrong or you can post some example code.
Now it's up to you, we can keep trying to throw wrong guess after wrong guess at you, frustrating us all, or you can help us help you...
Here are two examples I did. The first uses a JLabel as the primary content for a JPanel, where the child components are placed on it. Nice and simple.
The second uses a custom JPanel which paints the image onto the background of the component. I then use this to replace the frames content pane. This is a little more involved, but it has the added benefit of been easily updated (replacing the content pane won't effect the rest of the program)
Example 1: JLabel used as background
public class TestBackground {
public static final String BACKGROUND_PATH = "/Volumes/Macintosh HD2/Dropbox/MT015.jpg";
public static void main(String[] args) {
new TestBackground();
}
public TestBackground() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new LabelPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
protected class LabelPane extends JPanel {
public LabelPane() {
BufferedImage bg = null;
try {
bg = ImageIO.read(new File(BACKGROUND_PATH));
} catch (IOException ex) {
ex.printStackTrace();
}
JLabel label = new JLabel(new ImageIcon(bg));
setLayout(new BorderLayout());
add(label);
label.setLayout(new GridBagLayout());
JLabel lblMessage = new JLabel("Look at me!");
lblMessage.setForeground(Color.WHITE);
lblMessage.setFont(lblMessage.getFont().deriveFont(Font.BOLD, 48));
label.add(lblMessage);
}
}
}
Example 2: Image used as background, replacing content pane...
public class TestBackground {
public static final String BACKGROUND_PATH = "/Volumes/Macintosh HD2/Dropbox/MT015.jpg";
public static void main(String[] args) {
new TestBackground();
}
public TestBackground() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new BackgroundPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
protected class BackgroundPane extends JPanel {
private BufferedImage bg = null;
public BackgroundPane() {
try {
bg = ImageIO.read(new File(BACKGROUND_PATH));
} catch (IOException ex) {
ex.printStackTrace();
}
setLayout(new GridBagLayout());
JLabel lblMessage = new JLabel("Look at me!");
lblMessage.setForeground(Color.WHITE);
lblMessage.setFont(lblMessage.getFont().deriveFont(Font.BOLD, 48));
add(lblMessage);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(1153, 823);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (bg != null) {
g.drawImage(bg, 0, 0, this);
}
}
}
}
To expand on Eng.Fouad's answer, you'll want to use the drawImage(...) method that takes 6 parameters, image, x and y location, image width and height, and image observer, and draw it like so from within a JPanel:
g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
For example, my sscce:
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
#SuppressWarnings("serial")
public class ExpandingImage extends JPanel {
public static final String GUITAR = "http://duke.kenai.com/Oracle/OracleStrat.png";
BufferedImage img;
public ExpandingImage(String imgUrlPath) throws IOException {
URL imgUrl = new URL(imgUrlPath);
img = ImageIO.read(imgUrl);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (img != null) {
g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
}
}
private static void createAndShowGui() {
ExpandingImage mainPanel;
try {
mainPanel = new ExpandingImage(GUITAR);
JFrame frame = new JFrame("ExpandingImage");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setVisible(true);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Edit
I see that you're using an EmptyBorder around the contentPane. Why if you don't want this border to be present?
As an alternative, you can override the method paintComponent(Graphics g) of JPanel (the contentPane) and use drawImage() on the Graphics object g as in this example.
have you tried JFrame function setUndecorated() ?
Make the frame undecorated. frame.setUndecorated(true)
If you want to make it move, you can use the ComponentMover of the Java2S.
Make sure that it is undecorated before it is visible.
Next, use setContentPane(new JLabel(new ImageIcon("myimage.jpg")));
After, that you can add contents as usual.